Java: Infinite loop using Scanner in.hasNextInt()

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

Leave a Comment