在 while 循环中检查输入是否为数字

Check if input is a number in a while loop

我开始在 Java 中编写代码(以前从未这样做过),我对输入验证感到头疼。

我需要当用户输入从 0 到 1000 的数字时,while 循环不断执行。那很好用。问题是我想检查他是否输入了一个数字,如果他没有输入,while 循环应该继续执行并等待下一个输入。到目前为止,我的代码仅在输入非数字内容时抛出 InputMismatchException,我不明白为什么。

这是我的代码:

Scanner score = new Scanner(System.in);
    int i = 0;
    while (i < 1000000) {
        System.out.print("Insert the new score: ");
        if (score.hasNextInt()) {
            i = score.nextInt();
            if (i > 0) {
                if (i < 200000) {
                    // do something
                } else if (i < 500000) {
                    // do something
                } else if (i < 700000) {
                    // do something
                } else if (i < 100001) {
                    // do something
                }
            } else if (i < 0) {
                // do something else
            }
        } else {
            System.out.print("The score should be a number.");
            i = score.nextInt();
        }
    }

您需要将输入语句包装在 try/catch 块中并捕获 InputMisMatchException。 InputMisMatchException 的发生是因为在需要整数的 Scanner 中使用了 nextInt() 。

Scanner input = new Scanner(System.in);
int i = 0;
do {
    try {
        System.out.print("Enter integer ");
        i = input.nextInt();
    } catch (InputMismatchException e) {
       //anything but integer gets caught here.
        System.out.print("Please enter only integer.");
    }
    //necessary to take the cursor back to start of line, clear the buffer
     input.nextLine();

} while (i < 1000000);

以上代码示例显示了如何捕获 InputMisMatchException。

我注意到您在代码中使用了 input.hasNextInt(),您只需在代码的 else 块中替换以下内容即可。

i = score.nextInt()

score.nextLine(); 

如其他答案所述,这句话将清除等待下一次输入的缓冲区。异常是由于 score.nextInt(),替换应该修复它。

else{
    System.out.print("The score should be a number.");
    i = score.nextInt(); //<---problem
}

这里您知道输入的不是数字,因此您不应该尝试将其读作 intnextInt()。因此,要使用无效数据,请使用

  • next() 将从扫描仪数据中 return 作为 Sting,您稍后可以忽略它(您甚至不需要将其存储在字符串变量中)
  • 或者如果你想消耗整行使用nextLine()(但要小心避免:Skipping nextLine() after using next(), nextInt() or other nextFoo() methods

您可能希望使用 try-catch 块将 while 内容换行。

Scanner score = new Scanner(System.in);
int i = 0;
while (i < 1000000){
try{
    System.out.print("Insert the new score: ");
    if (score.hasNextInt()){
    i = score.nextInt();
    if (i>0){
        if (i<200000){
            do something
        }
        else if (i<500000){
            do something
        }
        else if (i<700000){
            do something
        }
        else if (i<100001){
            do something
        }
    }else if (i<0){
        do something else
    }
    }else{
        System.out.print("The score should be a number.");
        i = score.nextInt();
    }
}catch(Exception e){}
}

您收到此错误是因为您告诉 Scanner 获取整数,即使用户没有键入整数。您需要接受所有输入(通过 String)并自己进行验证。

我修改了您的代码以将输入作为字符串 (Scanner#nextLine),然后尝试更新分数。

Scanner score = new Scanner(System.in);
int i = 0;
while (i < 1000000) {
    System.out.print("Insert the new score: ");
    if (score.hasNext()) {
        final String input = score.nextLine();
        try {
            i = Integer.parseInt(input);
        } catch (final Exception e) {
            System.out.print("The score should be a number.");
            continue;
        }
    }
    if (i>0) {
        if (i<200000) {
            //do something
        }
        else if (i<500000) {
            //do something
        }
        else if (i<700000) {
            //do something
        }
        else if (i<100001) {
            //do something
        }
    } else if (i<0) {
        //do something else
    }
}

请注意,continue; 语句将无限期地要求用户输入整数,直到用户输入为止,就像您在问题中所要求的那样。

在最后的 else 子句中,您调用了 score.nextInt(),尽管您知道下一个数字不是 int。这就是你得到例外的原因。只需将 else 替换为:

else {
    System.out.print("The score should be a number.");
    score.nextLine(); //This is the line you need to change
}

score.nextLine(); 将安全地消耗下一行输入,并让您回到循环中。