Java while循环无限捕获不匹配异常
Java while loop endlessly catching mismatch exception
我正在尝试在 java 中创建一个简单的 while 循环,它要求用户输入一个数字并将其存储在一个变量中。我也在检查以确保他们输入的值是一个数字。如果用户输入字符串,循环应该告诉用户他们没有输入数字。在告诉用户没有输入数字后,它还应该要求用户再次输入数字。
目前,如果用户输入字符串,这段代码会不断地捕获异常。我如何让这个循环工作?
Scanner reader = new Scanner(System.in);
isInt = false;
while(!isInt){
try{
System.out.println("Enter a number");
int aNumber = reader.nextInt();
isInt = true;
}
catch(InputMismatchException e){
System.out.println("You didn't enter a number");
}
}
nextInt()
方法不使用非数字输入。此方法的 Javadocs 引用了重载方法 nextInt(int)
,其中指出:
Scans the next token of the input as an int. This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.
(强调我的)
在 catch
块中,添加一行调用 reader.next()
以使用(并忽略)非数字输入,以便可以在下一次迭代中检查下一个标记while
循环。
我正在尝试在 java 中创建一个简单的 while 循环,它要求用户输入一个数字并将其存储在一个变量中。我也在检查以确保他们输入的值是一个数字。如果用户输入字符串,循环应该告诉用户他们没有输入数字。在告诉用户没有输入数字后,它还应该要求用户再次输入数字。
目前,如果用户输入字符串,这段代码会不断地捕获异常。我如何让这个循环工作?
Scanner reader = new Scanner(System.in);
isInt = false;
while(!isInt){
try{
System.out.println("Enter a number");
int aNumber = reader.nextInt();
isInt = true;
}
catch(InputMismatchException e){
System.out.println("You didn't enter a number");
}
}
nextInt()
方法不使用非数字输入。此方法的 Javadocs 引用了重载方法 nextInt(int)
,其中指出:
Scans the next token of the input as an int. This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.
(强调我的)
在 catch
块中,添加一行调用 reader.next()
以使用(并忽略)非数字输入,以便可以在下一次迭代中检查下一个标记while
循环。