简体   繁体   English

使用Scanner.nextInt()与Scanner.nextLine()进行异常处理

[英]Exception Handling with Scanner.nextInt() vs. Scanner.nextLine()

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. 我试图用input.nextInt()代替它来编写程序。 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. 当我传递非整数的值时,控制台显示熟悉的“线程异常...”错误消息。

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()? Scanner.nextLine()的用途是什么? Why did each of these scenarios play out differently? 为什么每种情况的表现都不一样?

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 感谢大家

When any of the nextXxx(...) methods fails, the scanner's input cursor is reset to where it was before the call. 当任何nextXxx(...)方法失败时,扫描仪的输入光标将重置为调用之前的位置。 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. 因此,异常处理程序中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. 还值得注意的是,如果nextInt()调用成功,则扫描器将立即定位在数字的最后一个字符之后。 Assuming that you are interacting with the user via console input / output, it may be necessary or advisable to consume the rest of the line (up to the newline) by calling nextLine() . 假设您正在通过控制台输入/输出与用户进行交互,则可能有必要或建议通过调用nextLine()使用其余的行(直到新行nextLine() It depends what your application is going to do next. 这取决于您的应用程序下一步要做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM