在while循环中处理从Scanner读取整数时出错 [英] Error handling reading ints from Scanner in while loop

查看:149
本文介绍了在while循环中处理从Scanner读取整数时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试捕获异常并让它重复,但它只是创建一个无限循环然后崩溃程序...为什么这样做?我的捕获物有问题吗?

I am try to catch an exception and get it to repeat, but it just creates an endless loop and then crashes the program... why is it doing this? Is it something wrong with my catch?

我查看了网络和stackoverflow,只能找到与我想要达到的目标无关的答案。 / p>

I have looked around the web and stackoverflow and can only find answers that don't related to what I am trying to achieve.

        boolean bError = true;
        System.out.println("How many players");
        do
        {
            try
            {
                PLAYERS = input.nextInt();

                if(PLAYERS > 5)
                {
                    System.out.println("maximum of 5");
                }//if
                else
                {
                    bError = false;
                }

            }
            catch(InputMismatchException e)
            {
                System.out.println(e);
                bError = true;
            }

        }while(bError && PLAYERS > 5);


推荐答案

如果输入无效,它会进入无限循环数字,因为无效的令牌仍然留在流上, nextInt()一直反复尝试抓住它。

It goes into an endless loop if you enter an invalid number because the invalid token is still left on the stream, and nextInt() keeps trying over and over again to grab it.

您必须从流中获取数据。

You will have to get the data off the stream.

您可以做的一件事是使用 nextLine()相反,然后显式尝试将返回的 String 解析为整数(例如,使用 Integer.parseInt() )。

One thing you could do is use nextLine() instead, then explicitly try and parse the returned String into an integer (e.g. with Integer.parseInt()).

你可以做的另一件事是调用 input.next()(或 input.nextLine())在异常处理程序中,读取(并丢弃)垃圾输入。您可能需要调整扫描器分隔符才能获得 next(),如果它不符合您的要求,可以为您工作默认设置。

Another thing you could do is call input.next() (or input.nextLine()) in the exception handler, to read (and discard) the garbage input. You may have to tweak the Scanner delimiters to get next() to work for you if it's not meeting your requirements with default settings.

这篇关于在while循环中处理从Scanner读取整数时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆