考慮這一點,如果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);
}
我認爲這是這樣,如果我inputed,比如說,一個char
時,預期的int
它只會返回null
。所以如果我檢查了null,那就足夠了。那麼我錯過了什麼/沒有了解?
所以這不是關於掃描儀庫的問題。如果你想把它煮沸,那就是我不知道一個整數不可能是null
。所以認爲這是重複的用戶,可能是這樣。但它肯定不是您建議的帖子的重複內容。
'int'永遠不能爲null。決不! – Hackerdarshi
掃描器類在輸入不匹配時拋出異常,而不是'int',而'int'不能爲 – Sanjeev
這可能很有用:http://stackoverflow.com/q/970029/423955 Java基元類型不能爲空。只有對象的引用可以爲null。 –