Try-catch creates infinite loop [duplicate]

只谈情不闲聊 提交于 2021-02-20 19:08:39

问题


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

回答1:


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.

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

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

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.




回答2:


Since you want it to recognize any input, but only use doubles, try Double.parseDouble(String). I also moved the rest of the logic to your try block, since it should only occur when valid input is received. If it can't parse the double, it breaks out without attempting the rest of the logic and tries again.

while (payment < price && price > 0){
    try{
        payment = Double.parseDouble(kb.next());
        if (payment > 0){
            totalPayment += payment;
            price -= payment;
            price = (price * 100); 
            payment = 0;
        }
        if (totalPayment < initialPrice){
            System.out.println("Please Insert:" + price);
        }
    }
    catch (Exception e) {
        System.out.println("Please enter valid currency");
    }
}


来源:https://stackoverflow.com/questions/34292881/try-catch-creates-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!