我試圖創建一個簡單的程序,用戶輸入一個整數,如果它不是一個整數,它會打印出發生錯誤并且程序循環直到用戶輸入一個整數。我找到了這個 try-catch 解決方案,但它不能正常工作。如果用戶不輸入整數,程序將無限循環。正確的解決方案是什么?Scanner input = new Scanner(System.in);int number;boolean isInt = false;while(isInt == false){ System.out.println("Enter a number:"); try { number = input.nextInt(); isInt = true; } catch (InputMismatchException error) { System.out.println("Error! You need to enter an integer!"); }}
1 回答

有只小跳蛙
TA貢獻1824條經驗 獲得超8個贊
你很接近。
解析字符串比嘗試從 獲取 int 更容易失敗,Scanner因為掃描器將阻塞,直到它獲取int.
Scanner input = new Scanner(System.in);
int number;
boolean isInt = false;
while (isInt == false) {
System.out.println("Enter a number:");
try {
number = Integer.parseInt(input.nextLine());
isInt = true;
} catch (NumberFormatException error) {
System.out.println("Error! You need to enter an integer!");
}
}
添加回答
舉報
0/150
提交
取消