首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Try catch块导致无限循环?

Try catch块导致无限循环?
EN

Stack Overflow用户
提问于 2011-11-04 10:11:42
回答 2查看 1.5K关注 0票数 1

我正在写一个简单的java控制台游戏。我使用扫描仪从控制台读取输入。我正在尝试验证,如果我要求输入一个整数,如果输入一个字母,我不会得到错误。我试过这个:

代码语言:javascript
复制
boolean validResponce = false;
int choice = 0;
while (!validResponce)
{
    try
    {
        choice = stdin.nextInt();
        validResponce = true;
    }
    catch (java.util.InputMismatchException ex)
    {
        System.out.println("I did not understand what you said. Try again: ");
    }
}

但它似乎创建了一个无限循环,只是打印出catch块。我做错了什么。

是的,我是Java新手

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-11-04 10:16:03

nextInt()不会丢弃不匹配的输出;程序将尝试一遍又一遍地读取它,每次都会失败。在调用nextInt()之前,使用hasNextInt()方法确定是否有int可供读取。

确保当您在InputStream中发现整数以外的内容时,可以使用nextLine()清除它,因为hasNextInt()也不会丢弃输入,它只是测试输入流中的下一个标记。

票数 5
EN

Stack Overflow用户

发布于 2014-06-24 02:19:48

尝试使用

代码语言:javascript
复制
boolean isInValidResponse = true;
//then
while(isInValidResponse){
//makes more sense and is less confusing
    try{
        //let user know you are now asking for a number, don't just leave empty console
        System.out.println("Please enter a number: ");
        String lineEntered = stdin.nextLine(); //as suggested in accepted answer, it will allow you to exit console waiting for more integers from user
        //test if user entered a number in that line
        int number=Integer.parseInt(lineEntered);
        System.out.println("You entered a number: "+number);
        isInValidResponse = false;
    }
//it tries to read integer from input, the exceptions should be either NumberFormatException, IOException or just Exception
    catch (Exception e){
        System.out.println("I did not understand what you said. Try again: ");
    }
}

由于avoiding negative conditionals https://blog.jetbrains.com/idea/2014/09/the-inspection-connection-issue-2/的共同主题

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8004185

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档