java 使用 Scanner.nextInt() 与 Scanner.nextLine() 进行异常处理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25277286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Exception Handling with Scanner.nextInt() vs. Scanner.nextLine()
提问by user3900383
This question is solely for educational purposes. I took the following code from a textbook on Java and am curious why input.nextLine() is used in the catch block.
这个问题仅用于教育目的。我从一本关于 Java 的教科书中获取了以下代码,我很好奇为什么在 catch 块中使用 input.nextLine()。
I tried to write the program using input.nextInt() in its place. The program would no longer catch the exception properly. When I passed a value other than an integer, the console displayed the familiar "Exception in thread..." error message.
我尝试使用 input.nextInt() 来编写程序。程序将不再正确捕获异常。当我传递一个不是整数的值时,控制台会显示熟悉的“线程中的异常...”错误消息。
When I removed that line of code altogether, the console would endlessly run the catch block's System.out.println() expression.
当我完全删除那行代码时,控制台将无休止地运行 catch 块的 System.out.println() 表达式。
What is the purpose of Scanner.nextLine()? Why did each of these scenarios play out differently?
Scanner.nextLine() 的目的是什么?为什么这些场景中的每一个都有不同的表现?
import java.util.*;
public class InputMismatchExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try{
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println(
"The number entered is " + number);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" +
"Incorrect input: an integer is required)");
input.nextLine();
}
}
while (continueInput);
}
}
Thanks everyone
感谢大家
回答by Stephen C
When any of the nextXxx(...)
methods fails, the scanner's input cursor is reset to where it was before the call. So the purpose of the nextLine()
call in the exception handler is to skip over the "rubbish" number ... ready for the next attempt at getting the user to enter a number.
当任何nextXxx(...)
方法失败时,扫描仪的输入光标将重置为调用前的位置。因此,nextLine()
异常处理程序中调用的目的是跳过“垃圾”号码……准备下一次让用户输入号码的尝试。
And when you removed the nextLine()
, the code repeatedly attempted to reparse the same "rubbish" number.
当您删除 时nextLine()
,代码反复尝试重新解析相同的“垃圾”数字。
It is also worth noting that if the nextInt()
call succeeded, the scanner would be positioned immediately after the last character of the number. Assuming that you are interacting with the user via console input / output, it maybe necessary or advisable to consume the rest of the line (up to the newline) by calling nextLine()
. It depends what your application is going to do next.
还值得注意的是,如果nextInt()
调用成功,扫描仪将立即定位在号码的最后一个字符之后。假设您通过控制台输入/输出与用户交互,则可能有必要或建议通过调用nextLine()
. 这取决于您的应用程序接下来要做什么。