title: Preventing scanner from reading leftover input in Java
body: <p>I am wondering how I can stop the scanner from reading extra erroneous input from the user.</p>
  
  <p>For example, I would like to read in the user input <code>2 one</code> as <code>2</code> into the variable <code>diam</code>, which the program below achieves.  </p>
  
  <p>The issue is then, that the next loop automatically detects the <code>one</code> leftover from the input, and executes the <code>if</code> statement accordingly.</p>
  
  <p>I was able to work around this by creating two scanners, but unfortunately this is not allowed for this particular assignment.  In addition, we are required to use <code>.hasNextInt()</code> in our program.  </p>
  
  <p>How do I prevent this "spill-over" using only one scanner?  I have to assume this question has been posed before, but I did not have much luck finding an answer.</p>
  
  <pre><code>    Scanner scnr = new Scanner(System.in);
  
      System.out.print("Enter the diameter of a "
              + "cylinder (in centimeters): ");
      // BEGIN: diameter input verification loop      
      for (;;) {
          if (!scnr.hasNextInt()) {
              System.out.print("Please enter an integer value "
                      + "(less than 2,147,483,648) as decimal digits: ");
              scnr.nextLine(); 
              continue;
          }
          diam = scnr.nextInt();
          if (diam &gt;= 0) {
             //null statement
          } 
          else {
            System.out.print("Please enter a positive integer value: ");
            continue;
          }
      break;
      }
      //END: diameter input verification loop
  
      //prompts user for container height     
      System.out.print("Enter the height of a "
              + "cylinder (in centimeters): ");
  
      // BEGIN: height input verification loop        
      for (;;) {
          if (!scnr.hasNextInt()) {
              System.out.print("Please enter an integer value "
                      + "(less than 2,147,483,648) as decimal digits: ");
              scnr.nextLine(); 
              continue;
          }
          height = scnr.nextInt();
          if (height &gt;= 0) {
             //null statement
          } 
          else {
            System.out.print("Please enter a positive integer value: ");
            continue;
          }
      break;
      }
      //END: height input verification loop`
  </code></pre>