Try-catch creates an endless loop

I need to be able to enter user input until the input is more than the initial price, but I also have to make it reliable so that the user cannot break the program by entering something other than double / integer. If the user enters something other than 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;
}
+4
source share
2 answers

, , , . ,

, .

, kb.next(), , , . :

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

, . try catch, hasNextDouble . , InputMismatchException, Exception, (, ). continue , , , , .

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

, - , ( payment reset ). , totalPayment < price .

+8

, , , Double.parseDouble(String). try, . , , .

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");
    }
}
0

Source: https://habr.com/ru/post/1620142/


All Articles