如果userChoice
不是整数,请考虑以下问题:
Scanner choice = new Scanner(System.in);
int userChoice = choice.nextInt();
if(....){
.... //not important
}
else if(userChoice == null){
System.out.println("wrong input..");
System.exit(0);
}
我为什么不能这样做?而必须要做的是:
import java.util.InputMismatchException;
..... //bunch of code
Scanner choice = new Scanner(System.in);
int userChoice;
try {
userChoise = choice.nextInt();
if(...){
..... //not important
}
}
catch(InputMismatchException e) {
System.out.println("wrong input..");
System.exit(0);
}
我以为是这样的,如果我输入
char
时期望int
时,它只会返回null
。因此,如果我检查是否为null,那就足够了。那么,我缺少/不了解什么?因此,这不是有关扫描程序库的问题。如果您想将其煮沸,那是因为我不知道整数不能为
null
。所以认为这是重复的用户可能就是这样。但这肯定不是您建议的帖子的重复。 最佳答案
int
不能为null。它可以是其范围内的任何数字。
关于java - 为什么我不能简单地检查变量是否为null而不是检查其他异常?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38100046/