4 回答

TA貢獻1條經(jīng)驗 獲得超2個贊
while (true) {
try {
id1 = sc.nextInt();
break;
} catch (InputMismatchException e) {
System.out.println("請輸入整數(shù)型的ID:");
sc.next();// 讀取下一個值,如果不加這條語句,控制臺得到的還是你上次輸入的數(shù),再一次進入catch語句,所以會一直循環(huán)報錯
}
}

TA貢獻1條經(jīng)驗 獲得超0個贊
sc .nextInt() 只會在找到匹配之后 才會 向前移動,因此每一次匹配仍然會在當前的輸入之中進行匹配
具體可以查看:
String java.util.Scanner.next(Pattern pattern)
Returns the next token if it matches the specified pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext(Pattern) returned true. If the match is successful, the scanner advances past the input that matched the pattern.
添加回答
舉報