【问题标题】:Checking the user input (scanner) before assigning to an int variable在分配给 int 变量之前检查用户输入(扫描仪)
【发布时间】:2014-11-07 01:36:07
【问题描述】:
int i;
Scanner scan = new Scanner(System.in) {
i = scan.nextInt();
}

我想要做的是在用户输入字符而不是整数时在扫描仪中捕获错误。我尝试了下面的代码,但最终调用了另一个用户输入(因为在仅验证数字的第一个 scan.nextInt() 后调用另一个 scan.nextInt() 为 i 赋值):

int i;
Scanner scan = new Scanner(System.in) {

    while (scan.hasNextInt()){
    i = scan.nextInt();
    } else {
    System.out.println("Invalid input!");
    }
}

【问题讨论】:

    标签: java java.util.scanner


    【解决方案1】:

    您的逻辑似乎有点不对劲,如果输入无效,您必须使用它。此外,您的匿名块似乎很奇怪。我想你想要类似的东西

    int i = -1; // <-- give it a default value.
    Scanner scan = new Scanner(System.in);
    while (scan.hasNext()) { // <-- check for any input.
        if (scan.hasNextInt()) { // <-- check if it is an int.
            i = scan.nextInt(); // <-- get the int.
            break; // <-- end the loop.
        } else {
            // Read the non int.
            System.out.println("Invalid input! " + scan.next()); 
        }
    }
    

    【讨论】:

    • 我在使用“while (scan.hasNext())”时出错,所以我将其更改为“if (scan.hasNext())”,我的问题就解决了!谢谢!
    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 2013-11-26
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多