简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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