Java扫描仪输入验证 [英] Java scanner input validation
问题描述
我尝试从输入中仅接受三个数字:1、2、3.除此以外的其他任何数字都必须无效.我已经创建了方法,但是我不知道为什么它不起作用.我必须更改什么?
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;
推荐答案
您的循环逻辑
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);
此外,当Scanner
的hasNextInt
返回false
时,您需要从扫描仪上取走无效的输入,例如忽略的nextLine
.否则,您将陷入无限循环:
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
}
这篇关于Java扫描仪输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!