Java: Infinite loop using Scanner in.hasNextInt()

Tomek picture Tomek · Nov 25, 2009 · Viewed 46.3k times · Source

I am using the following code:

while (invalidInput)
{
    // ask the user to specify a number to update the times by
    System.out.print("Specify an integer between 0 and 5: ");

    if (in.hasNextInt())
    {
        // get the update value
        updateValue = in.nextInt();

        // check to see if it was within range
        if (updateValue >= 0 && updateValue <= 5) 
        { 
            invalidInput = false; 
        } 
        else 
        {
            System.out.println("You have not entered a number between 0 and 5. Try again.");
        }
    } else
    {
        System.out.println("You have entered an invalid input. Try again.");
    }
}

However, if I enter a 'w' it will tell me "You have entered invalid input. Try Again." and then it will go into an infinite loop showing the text "Specify an integer between 0 and 5: You have entered an invalid input. Try again."

Why is this happening? Isn't the program supposed to wait for the user to input and press enter each time it reaches the statement:

if (in.hasNextInt())

Answer

Kaleb Brasee picture Kaleb Brasee · Nov 25, 2009

In your last else block, you need to clear the 'w' or other invalid input from the Scanner. You can do this by calling next() on the Scanner and ignoring its return value to throw away that invalid input, as follows:

else
{
      System.out.println("You have entered an invalid input. Try again.");
      in.next();
}