如何安全地扫描整数输入?

6
Scanner scanner = new Scanner();
int number = 1;

do
{
    try
    {
        option = scanner.nextInt();
    }
    catch (InputMismatchException exception)
    {
        System.out.println("Integers only, please.");
    }
}
while (number != 0);

尽管有异常处理,但当输入非整数时,此代码将进入无限循环。而不是Scanner在下一次迭代中暂停收集输入,它只是继续抛出InputMismatchException直到程序被终止。

什么是扫描整数(或其他类型)输入的最佳方法,丢弃无效的输入并正常继续循环?

5个回答

7

在将输入值赋给一个整数之前,您应该检查输入是否可以解析为整数。不应该使用异常来确定输入是否正确,这是一种不良实践,应该避免。

if(scanner.hasNextInt()){
   option = scanner.nextInt();
}else{
   System.out.printLn("your message");
}

通过这种方式,您可以检查输入是否可以解释为整数,如果可以,则分配值,如果不行,则显示消息。调用该方法不会推进扫描器。


7

将您的代码更改为以下内容

catch (InputMismatchException exception) 
{ 
    System.out.println("Integers only, please."); 
    scanner.nextLine();
} 

还要添加一个检查器来检查输入的字符串是否只包含数字字符,如果输入了其他内容,则显示错误。 - Gonçalo Vieira
这就是为什么我讨厌扫描仪的原因。不过+1。 - Martijn Courteaux
这是一个100%的好解决方案,但我很高兴这里还有其他答案。如果没有任何关于为什么会修复它的解释(例如,“nextInt()在标记转换失败时不会向前移动”),那么以后学习和参考这些内容的人将能够修复它,但不会理解为什么它有效。尽管如此,对这个答案点赞。 - Alex G

4
从Javadoc中可以看到:如果下一个标记无法按照以下所述转换为有效的int值,则此方法将抛出InputMismatchException。如果转换成功,扫描器将跳过匹配的输入。
请注意第二个句子,只有在成功时才会前进。这意味着您需要将catch块更改为以下内容:
catch (InputMismatchException exception) 
{ 
    System.out.println("Integers only, please."); 
    scanner.next();
}

1
如果扫描的是非整数变量,将会出现异常,如果不是,则标记为 true 并退出循环。
Scanner scanner = new Scanner();
int number = 1;
boolean flag = false;

do
{
    try
    {
        option = scanner.nextInt();
        flag=true;
    }
    catch (InputMismatchException exception)
    {
        System.out.println("Integers only, please.");
    }
}
while ( flag );

0

我认为这样更好

import java.util.*;

class IntChkTwo{

public static void main(String args[]){

    Scanner ltdNumsScan = new Scanner(System.in);
    int ltdNums = 0;
    int totalTheNums = 0;
    int n = 4;



    System.out.print("Enter Five Numbers: ");
    for(int x=0;x<=n;x++){
        try{
            ltdNums = ltdNumsScan.nextInt();
            totalTheNums = totalTheNums + ltdNums;
        }catch(InputMismatchException exception){
            n+=1;//increases the n value 
                    //maintains the same count of the numbers
                    //without this every error is included in the count
            System.out.println("Please enter a number");
            ltdNumsScan.nextLine();

        }//catch ends
    }//for ends

    int finalTotalNums = totalTheNums;
    System.out.println("The total of all of the five numbers is: "+finalTotalNums);



}

}

我对代码示例感到困惑,所以不得不重写它。希望即使过了几年,这也能帮到你。我知道这很不同,但当我尝试使用示例代码添加数字时,我在途中感到困惑。

起初让我困扰的是它计算错误。

我宁愿放弃do-while循环,之前尝试过,如果你错过了什么,它就会进入无限循环。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接