Java: Infinite loop using Scanner in.hasNextInt()

前端 未结 4 1538
Happy的楠姐
Happy的楠姐 2020-11-27 19:30

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 intege         


        
4条回答
  •  心在旅途
    2020-11-27 19:46

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

提交回复
热议问题