4 回答

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

TA貢獻(xiàn)1條經(jīng)驗(yàn) 獲得超0個(gè)贊
sc .nextInt() 只會(huì)在找到匹配之后 才會(huì) 向前移動(dòng),因此每一次匹配仍然會(huì)在當(dāng)前的輸入之中進(jìn)行匹配
具體可以查看:
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.
添加回答
舉報(bào)