Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

This is the program

public class bInputMismathcExceptionDemo {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    boolean continueInput = true;
    do {
        try {
            System.out.println("Enter an integer:");
            int num = input.nextInt();

            System.out.println("the number is " + num);
            continueInput = false;
        }
        catch (InputMismatchException ex) {
            System.out.println("Try again. (Incorrect input: an integer is required)");
        } 
        input.nextLine();
    }   
    while (continueInput);

}
}

I know nextInt() only read the integer not the " ", but why should we need the input.nextLine() to read the " "? is it necessary?? because I think even without input.nextLine(), after it goes back to try {}, the input.nextInt() can still read the next integer I type, but in fact it is a infinite loop.

I still don't know the logic behind it, hope someone can help me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
262 views
Welcome To Ask or Share your Answers For Others

1 Answer

The reason it is necessary here is because of what happens when the input fails.

For example, try removing the input.nextLine() part, run the program again, and when it asks for input, enter abc and press Return

The result will be an infinite loop. Why?

Because nextInt() will try to read the incoming input. It will see that this input is not an integer, and will throw the exception. However, the input is not cleared. It will still be abc in the buffer. So going back to the loop will cause it to try parsing the same abc over and over.

Using nextLine() will clear the buffer, so that the next input you read after an error is going to be the fresh input that's after the bad line you have entered.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...