1

If I remove input.nextLine() from the catch block, an infinite loop starts. The coment says that input.nextLine() is discarding input. How exactly is it doing this?

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();

    // Display the result
    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(); // discard input 
  }
} while (continueInput);
}
}

One more thing.. The code listed below, on the other hand, works perfectly without including any input.nextLine() statement. Why?

import java.util.*;

public class InputMismatchExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter four inputs::");
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
int d = input.nextInt();
int[] x = {a,b,c,d};
for(int i = 0; i<x.length; i++)
    System.out.println(x[i]);
}
}
Wololo
  • 833
  • 8
  • 20

1 Answers1

2

Because input.nextInt(); will only consume an int, there is still pending characters in the buffer (that are not an int) in the catch block. If you don't read them with nextLine() then you enter an infinite loop as it checks for an int, doesn't find one, throws an Exception and then checks for an int.

You could do

catch (InputMismatchException ex) {
    System.out.println("Try again. (" + 
      "Incorrect input: an integer is required) " +
      input.nextLine() + " is not an int"); 
}
Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226
  • I replaced my catch block with the one you provided. Here's the console output: Enter an integer: 5.4 Try again. (Incorrect input: an integer is required) 5.4 is not an int. I can't understand, why is input.nextLine giving 5.4? Shouldn't it be a newline character ('\n') – Wololo Jun 29 '15 at 23:36
  • @Saud Not in your first example. It didn't read `5.4` as an `int`, because `5.4` **isn't** an `int`. Thus the `InputMismatchException`, *it tries to read an `int` but there isn't an `int` to read; there is `5.4` ready to read (and `readInt` will not read `5.4`)*. Your second example would terminate if you entered `5.4` for `a`, `b`, `c` or `d`. – Elliott Frisch Jun 29 '15 at 23:44
  • Ah! Thanks ... Got it – Wololo Jun 29 '15 at 23:47