while (true) {
try {
age = sc.nextInt();
if (age > 0 && age < 150) break;
System.out.println("請重新輸入年齡");
} catch (Exception e) {
System.out.println("請重新輸入年齡");
sc.next(); // 關鍵行
}
}
sc.next()?Scanner.nextInt() **不消耗非整數輸入**。當使用者輸入 abc:
nextInt() 拋出 InputMismatchException。abc**。nextInt() 讀到同樣 abc,**無限迴圈**拋出例外。sc.next() 讀取並**丟棄下一個 token (以空白分隔)**,清除非法輸入,使迴圈能等待新輸入。
while (true) {
System.out.print("請輸入年齡 (1-149): ");
if (sc.hasNextInt()) {
int age = sc.nextInt();
if (age > 0 && age < 150) {
System.out.println("輸入有效: " + age);
break;
}
System.out.println("年齡超出範圍");
} else {
System.out.println("非數字輸入: " + sc.next()); // 同時清除並提示
}
}
| 方法 | 行為 | 適用場景 |
|---|---|---|
| nextInt() | 解析整數,失敗拋例外、不消耗 token | 確定輸入合法時 |
| hasNextInt() | 預檢下一 token 是否整數,不消耗 | 輸入驗證迴圈 |
| next() | 讀取並消耗下一 token (字串) | 清除緩衝區、讀取字串 |
| nextLine() | 讀取整行 (含空白) | 讀取含空格字串 |
nextInt() 後緩衝區殘留換行符,後續 nextLine() 讀到空行 → 需額外呼叫 nextLine() 清除。next()/nextLine() 需理解分隔符差異。理解 Scanner 緩衝區與 token 機制,改用 hasNextX() 預檢模式,即能撰寫健壯的互動式輸入驗證。