How do I stop while loop from running infinitely?
问题 Can't figure out how to stop this while loop from repeating infinitely. I'm using hasNextInt to check if user input is an int. If an int is not entered the loop repeats infinitely. public static void validatingInput(){ Scanner scan = new Scanner(System.in); boolean valid = false; int userNumber = 0; while(!valid) { System.out.println("Enter number between 1 and 20: "); if (scan.hasNextInt()) { userNumber = scan.nextInt(); valid = true; } else System.out.print("Not an int. "); } } 回答1: You