title: Exception Handling with Scanner.nextInt() vs. Scanner.nextLine()
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>When I removed that line of code altogether, the console would endlessly run the catch block's System.out.println() expression. </p>
  
  <p>What is the purpose of Scanner.nextLine()? Why did each of these scenarios play out differently?</p>
  
  <pre><code>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);
      }   
  }
  </code></pre>
  
  <p>Thanks everyone</p>