Java扫描仪输入验证 [英] Java scanner input validation

查看:56
本文介绍了Java扫描仪输入验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从输入中仅接受三个数字: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);

此外,当ScannerhasNextInt返回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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆