问题
I am trying to accept only three numbers from my input: 1, 2, 3. Any other different than that must be invalid. I have created method but I don't have an idea why it did not working. What must I change?
int number;
do {
System.out.println("Enter 1, 2 or 3");
while (!scanner.hasNextInt()) {
System.out.println("Invalid input!");
}
number = scanner.nextInt();
} while (number == 1 || number == 2 || number == 3)
return number;
回答1:
Your loop logic
do {
...
} while (number == 1 || number == 2 || number == 3);
requires staying in the loop for as long as the answer is valid. You want to invert your condition:
do {
...
} while (!(number == 1 || number == 2 || number == 3));
or use De Morgan's Law to invert individual components:
do {
...
} while (number != 1 && number != 2 && number != 3);
In addition, when Scanner
's hasNextInt
returns false
, you need to take the invalid input off the scanner, for example with nextLine
that you ignore. Otherwise you get an infinite loop:
while (!scanner.hasNextInt()) {
System.out.println("Invalid input!");
scanner.nextLine(); // This input is ignored
}
来源:https://stackoverflow.com/questions/47849658/java-scanner-input-validation