10

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 "\n", but why should we need the input.nextLine() to read the "\n"? 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.

Tharif
  • 13,172
  • 9
  • 51
  • 73
高亮节
  • 169
  • 1
  • 1
  • 7
  • 2
    read this http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html –  Jan 26 '15 at 16:09

2 Answers2

8

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.

RealSkeptic
  • 32,074
  • 7
  • 48
  • 75
  • thank you, so nextLine() not only clear "\n", but also clear "abc"?? – 高亮节 Jan 27 '15 at 04:03
  • Yes. It reads all the characters up to and including the end-of-line, and returns the line. The string it returns excludes the end-of-line, but you're not interested in its return value in this case, only in what it consumes, which is the entire line. – RealSkeptic Jan 27 '15 at 07:07
4

but why should we need the input.nextLine() to read the "\n"? is it necessary??

Yes (actually it's very common to do that), otherwise how will you consume the remaining \n? If you don't want to use nextLine to consume the left \n, use a different scanner object (I don't recommend this):

Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);

input1.nextInt();
input2.nextLine();

or use nextLine to read the integer value and convert it to int later so you won't have to consume the new line character later.

Maroun
  • 87,488
  • 26
  • 172
  • 226