【发布时间】:2018-05-30 20:12:08
【问题描述】:
我正在尝试创建一个检查整数的函数,并将继续循环,直到用户正确输入 17 或更高的整数。但是,如果我输入了错误的输入,例如“K”或“&”,它将陷入无限循环。
public static int getAge(Scanner scanner) {
int age;
boolean repeat = true;
while (repeat) {
try
{
System.out.println("Enter the soldier's age: ");
age = scanner.nextInt();
repeat = false;
}
catch(InputMismatchException exception)
{
System.out.println("ERROR: You must enter an age of 17 or higher");
repeat = true;
}
}
return age;
}
【问题讨论】:
-
你的解决方案有什么问题是它不起作用。你忘了问一个问题
标签: java input while-loop integer try-catch