try {
num1 = input.nextInt();
} catch (Exception ex) {
System.out.println("輸入錯誤,請重新輸入");
input.nextInt(); // 錯誤:再次調用 nextInt() 仍讀取緩衝區中無效數據
}
Scanner.nextInt() 遇到非整數輸入(如字母 'e')時拋出 InputMismatchException,但不會消費該無效 token,導致緩衝區仍殘留 'e'。catch 塊中再次調用 nextInt() 會再次讀取同一無效數據,陷入無限異常循環。
input.next() 或 input.nextLine() 跳過錯誤輸入。hasNextInt() 判斷後再讀取,避免異常開銷。while (!input.hasNextInt()) {
System.out.println("請輸入整數:");
input.next(); // 跳過非整數 token
}
num1 = input.nextInt();
同理處理 num2。此寫法健壯且無異常性能損耗。