Wololo
Wololo

Reputation: 861

How is nextLine() discarding input in this code?

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]);
}
}

Upvotes: 0

Views: 714

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201467

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"); 
}

Upvotes: 2

Related Questions