如何安全扫描整数输入?

发布于 2024-12-05 00:09:39 字数 446 浏览 2 评论 0原文

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 直到程序被终止。

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

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

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

Despite the exception handling, this code will enter an infinite loop when non-integer input is given. Instead of Scanner pausing to collect input in the next iteration, it simply continues throwing InputMismatchExceptions until the program is killed.

What's the best way to scan for integer (or another type, I suppose) input, discarding invalid input and continuing the loop normally?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

人生戏 2024-12-12 00:09:39

在尝试将输入的值分配给 int 之前,您应该检查输入是否可以解析为 int。您不应该使用异常来确定输入是否正确,这是不好的做法,应该避免。

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

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

You should check whether or not the input can be parsed as an int before attempting to assign the input's value to an int. You should not be using an exception to determine whether or not the input is correct it is bad practice and should be avoided.

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

This way you can check whether or not the input can be interpreted as an int and if so assign the value and if not display a message. Calling that method does not advance the scanner.

怪我太投入 2024-12-12 00:09:39

将您的代码更改为此

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

change your code to this

catch (InputMismatchException exception) 
{ 
    System.out.println("Integers only, please."); 
    scanner.nextLine();
} 
把梦留给海 2024-12-12 00:09:39

来自 javadoc:如果下一个标记无法转换为有效的 int 值,则此方法将抛出 InputMismatchException,如下所述。如果翻译成功,扫描仪将前进到匹配的输入。

请注意第二句话,只有在成功时才会前进。这意味着您需要将 catch 块更改为如下所示:

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

From the javadoc: This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.

Note the second sentence there, it only advances IF it is successful. This means that you will need to change your catch block to something like the following:

catch (InputMismatchException exception) 
{ 
    System.out.println("Integers only, please."); 
    scanner.next();
}
落墨 2024-12-12 00:09:39

如果它扫描非 int 变量,则会弹出异常,否则标志将为 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 );

If it scans a non-int variable, exception will pop, if not flag will be true and loop will exit.

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 );
桜花祭 2024-12-12 00:09:39

我认为这更好,

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 循环,之前尝试过,如果你错过了一些东西,它就会进入无限循环。

I think this is better

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);



}

}

I was confused with the code sample, so I had to rewrite it. Hope this helps you even its been years. I know its different, but when I tried adding the numbers using the sample code I got confused along the way.

At first what was bugging me was it counts the error.

I would rather do away with the do-while loop, tried it before and if you miss something it goes on to an infinite loop.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文