问题
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 need to consume a token from a scanner in order to allow it to read the next token:
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. ");
scan.next(); // Skip a token
}
}
回答2:
You can break any loops with break;
.
Check the state of an input and break the while when you want
来源:https://stackoverflow.com/questions/55444997/how-do-i-stop-while-loop-from-running-infinitely