【发布时间】:2016-06-29 21:05:53
【问题描述】:
考虑一下,如果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 那么就足够了。那么我错过了什么/没有理解什么?
所以这不是关于 Scanner 库的问题。如果你想把它归结为我不知道整数不能是null。所以认为这是重复的用户,它可能是。但这肯定不是您建议的帖子的重复..
【问题讨论】:
-
int永远不能是null。从来没有! -
扫描程序类在输入不匹配时抛出异常,而不是
nullint不能是 -
这可能有用:stackoverflow.com/q/970029/423955 Java 原始类型不能为空。只有对对象的引用可以为空。
-
有一个
hasNextInt()方法用于一个目的...
标签: java