将其封装在一个方法中 - 如下所示。然后只需使用该方法从用户那里获取整数。
public static int getInt() {
System.out.print("Please enter an integer");
if (console.hasNext("stop")) {
System.out.println("***Terminated***");
System.exit(0);
}
while(!console.hasNextInt()) {
System.out.print("Input is not a valid integer!");
console.next();
}
int temp = console.nextInt();
while(temp<0 && temp>100) {
System.out.println("invalid input");
temp = console.nextInt();
}
return temp;
}
编辑:
如果使用这种方法而不是 try-catch 块,这就是完整的解决方案。
package standard;
import java.util.Scanner;
public class Main {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int[] cw_Mark = new int[6];
for (int i = 0; i < cw_Mark.length; i++) {
System.out.println("Please Enter Your Module " + (i + 1)
+ " Coursework Mark: ");
cw_Mark[i] = getInt();
}
}
//Gets the next integer from the console.
public static int getInt() {
System.out.print("Please enter an integer");
if (console.hasNext("stop")) {
System.out.println("***Terminated***");
System.exit(0);
}
while (!console.hasNextInt()) {
System.out.print("Input is not an integer!");
console.next();
}
int temp = console.nextInt();
while (temp <= 0 && temp >= 100) {
System.out.println("Input must be between 0 and 100");
temp = console.nextInt();
}
return temp;
}
}