Exception Handling with Scanner.nextInt() vs. Scanner.nextLine()

允我心安 提交于 2019-12-05 06:29:39

问题


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.

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.

When I removed that line of code altogether, the console would endlessly run the catch block's System.out.println() expression.

What is the purpose of 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


回答1:


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.

And when you removed the nextLine(), the code repeatedly attempted to reparse the same "rubbish" number.


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 may be 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.



来源:https://stackoverflow.com/questions/25277286/exception-handling-with-scanner-nextint-vs-scanner-nextline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!