java - My loop with try catch is stuck in endless loop and it should prompt the user each time for an input
问题描述
I'm trying to ask the user for a number and if they enter anything wrong (not an int between 1 and 99) then catch (to prevent crash if string) and loop until enter a right number. My loop is stuck in an endless loop somehow. Note: I do have the Scanner imported and the exception imported too.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String result;
int number;
boolean done = false;
while (true) {
try {
System.out.println("Please select a number from 1 to 99.");
number = input.nextInt();
input.nextLine();
if (number >= 1 || number <= 99) {
result = checkNumber(number);
System.out.println(result);
break;
}
} catch (InputMismatchException exception) {
}
}
}
解决方案
input.nextInt()
won't consume anything not an int
. It will throw an exception. You ignore the exception and try to consume an int
. It's still not an int
. Same exception. Infinite loop. Add another input.nextLine()
in your catch block.
推荐阅读
- pandas - Ignore errors in pandas astype
- symfony - FosUser 覆盖角色属性
- timeout - 当为帧请求设置抑制肯定响应时,否定响应的 UDS 协议超时
- jquery - 替换 DOM 中的任何匹配内容
- javascript - 使用 fetch() 将数据发布到 NodeJS
- process - ServiceNow 中是否有模块或工具来组织服务目录中请求的重复任务的债务?
- .htaccess - 如何重定向重写的查询字符串 URL
- javascript - 根据按钮单击更改类名,同时避免更多 if / elses
- etl - Airflow retain the same database connection?
- c# - Rhino 模拟 AssertWasNotCalled 提取到泛型方法失败