I believe your while condition is being met by the invalid input.
Perhaps try something like:
String userInput = "";
while (true) { // loop until valid input
userInput = scanner.nextLine();
if (isInteger(userInput))
break;
System.out.print("Please enter a valid number.");
}
private static boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch(NumberFormatException e) {
return false;
}
These previous answers may also help: https://stackoverflow.com/a/53904761/6423542 https://stackoverflow.com/a/24836513/6423542