【问题标题】:Java scanner input validation [duplicate]Java扫描仪输入验证[重复]
【发布时间】:2018-05-30 16:27:44
【问题描述】:

我试图从我的输入中只接受三个数字:1、2、3。除此之外的任何其他数字都必须是无效的。我已经创建了方法,但我不知道为什么它不起作用。我必须改变什么?

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;

【问题讨论】:

    标签: java validation input java.util.scanner


    【解决方案1】:

    你的循环逻辑

    do {
        ...
    } while (number == 1 || number == 2 || number == 3);
    

    只要答案是有效,就需要一直在循环中。你想反转你的条件:

    do {
        ...
    } while (!(number == 1 || number == 2 || number == 3));
    

    或使用De Morgan's Law 反转单个组件:

    do {
        ...
    } while (number != 1 && number != 2 && number != 3);
    

    此外,当ScannerhasNextInt 返回false 时,您需要将无效输入从扫描仪中移除,例如您忽略的nextLine。否则你会得到一个无限循环:

    while (!scanner.hasNextInt()) {
        System.out.println("Invalid input!");
        scanner.nextLine(); // This input is ignored
    }
    

    【讨论】:

    • 这是我正在寻找的答案。 11分钟后我会接受的
    • 位有问题。如果我输入字母开始无限循环
    • @TeodorKolev 是的,这就是我的编辑内容:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 2021-11-19
    • 2020-12-03
    相关资源
    最近更新 更多