Java: Infinite loop using Scanner in.hasNextInt()

Posted by Tomek on Stack Overflow See other posts from Stack Overflow or by Tomek
Published on 2009-11-25T02:25:52Z Indexed on 2010/05/04 5:28 UTC
Read the original article Hit count: 330

Filed under:
|
|
|
|

Hi everyone,

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())

Thanks in advance,

Tomek

© Stack Overflow or respective owner

Related posts about scanner

Related posts about hasnextint