title: How Do I Safely Scan for Integer Input?
body: <pre><code>Scanner scanner = new Scanner();
  int number = 1;
  
  do
  {
      try
      {
          option = scanner.nextInt();
      }
      catch (InputMismatchException exception)
      {
          System.out.println("Integers only, please.");
      }
  }
  while (number != 0);
  </code></pre>
  
  <p>Despite the exception handling, this code will enter an infinite loop when non-integer input is given.  Instead of <code>Scanner</code> pausing to collect input in the next iteration, it simply continues throwing <code>InputMismatchException</code>s until the program is killed.</p>
  
  <p>What's the best way to scan for integer (or another type, I suppose) input, discarding invalid input and continuing the loop normally?</p>