尝试捕获创建无限循环 [英] Try-catch creates infinite loop

查看:57
本文介绍了尝试捕获创建无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够接受用户的输入,直到输入的价格大于初始价格为止,但我还需要使其坚固,以使用户不能通过输入双精度或整数以外的其他内容来破坏程序.如果用户输入的不是double/int,则为其他内容.

I need to be able to take user input until the input is greater than the initial price, but I also need to make it robust so that the user can't break the program by entering something other than a double/integer. If the user does enter something other than a double/int.

问题在于它会创建一个循环并重复请输入有效的货币" +请输入:价格"

The problem is that it creates a loop and repeats "Please enter valid currency" + "Please enter: price"

 public static double findChange()
{
    System.out.println("\nPlease insert: " + price + " (enter payment amount)");
    initialPrice = price;
    while (payment < price)
    {  
        try{
            payment = kb.nextDouble();
        }
        catch (Exception e)
        {
            System.out.println("Please enter valid currency");
        }
        if (payment > 0){
            totalPayment += payment;
            price -= payment;
            price = (price * 100);
            payment = 0;
        }
        if (totalPayment < initialPrice)
            System.out.println("Please Insert:" + price);
    }

    change = totalPayment - initialPrice;
    change = Math.round(change * 100);
    change = change / 100;
    System.out.println("\nChange Given: $" + change);

    return change;
}

推荐答案

看到无限循环的原因是,您永远不会从输入中清除无效的条目.如果您查看文档,它说

The reason you're seeing an infinite loop is that you never clear the invalid entry out of the input. If you look at the docs, it says

如果翻译成功,扫描程序将前进经过匹配的输入.

If the translation is successful, the scanner advances past the input that matched.

失败时,应调用 kb.next()删除不匹配双精度字的输入,以便继续进行下一个用户输入.否则,您将一遍又一遍地尝试解析相同的无效文本:

When it fails, you should call kb.next() to remove the input that did not match a double, so that you can move on to the next user entry. Otherwise, you'll keep trying to parse the same invalid text over and over:

catch (Exception e)
{
    System.out.println("Please enter valid currency");
    kb.next();
}

您还可以改进其他一些内容.此处无需使用 try catch ,因为您可以使用 hasNextDouble 方法来检查输入是否有效.如果您确实决定坚持使用异常处理,则应该捕获 InputMismatchException 而不是通用的 Exception ,否则您可能会遇到更多问题(例如,如果输入已用尽).您也可以在输入失败时放入 continue ,这样它就不会评估假设您正确读取了值的其余代码.

A few other things you can improve as well. There's no need to be using a try and catch here, since you can use the hasNextDouble method to check that the input is valid. If you do decide to stick with exception handling though, you should catch InputMismatchException rather than a generic Exception, or else you risk running into some more problems (for example, if the input gets exhausted). You can also put a continue in when the input fails, so that it doesn't evaluate the rest of the code which is assuming that you correctly read a value.

if(kb.hasNextDouble()){
    payment = kb.nextDouble();
} else{
    System.out.println("Please enter valid currency");
    kb.next();
    continue;
}

请注意,您的逻辑仍然存在问题,循环将永远不会退出(因为 payment 始终会重置为零).我假设您想执行 totalPayment<价格.

Note that there's still a problem with your logic, and the loop will never exit (since payment always gets reset to zero). I assume you want to do totalPayment < price instead.

这篇关于尝试捕获创建无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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