所以我得到这段代码来检查输入是否为int:
public static int getInt(){
boolean bool = true;
int answerInt = 0;
while(bool == true){
try{
answerInt = sc.nextInt();
bool = false;
}catch(InputMismatchException e){
System.out.println("Error");
break;
}
}
return answerInt;
}
因此,如果用户输入无效的内容,则程序中的其余输入将变为" null"。为什么会发生这种情况,我该如何解决?
答案 0 :(得分:1)
public static int getInt() {
Scanner sc = new Scanner(System.in);
boolean bool = true;
int answerInt = 0;
System.out.println("Enter an int");
while (bool) {
try {
answerInt = sc.nextInt();
bool = false;
sc.close();
} catch (InputMismatchException e) {
System.out.println("Try again");
sc.next(); //Can you figure out why this line is needed?
}
}
return answerInt;
}