我的while循环似乎正在重新启动,除非我插入一个负数?

时间:2017-12-15 17:51:47

标签: java loops while-loop

我的while循环工作正常,直到我输入一个负数,我做错了什么?输入负数后,循环停止,代码完成执行。我希望它重新启动完整的while循环,这样我就可以继续输入,直到budgetRemaining达到0.我感谢你的帮助,谢谢!

Scanner enterPrice = new Scanner(System.in);
    double budgetRemaining = 100;
    double itemPrice;

    System.out.println("Please enter price of item:");
    itemPrice = enterPrice.nextDouble();

    if (itemPrice < budgetRemaining) {
        budgetRemaining -= itemPrice;

        if (itemPrice < 0) {
            budgetRemaining += itemPrice;
            System.out.println("Sorry, you have entered an invalid amount.");

        } while (budgetRemaining > 0 && itemPrice >= 0) {
            System.out.println("You have a remaining budget of $" + budgetRemaining + ". Please enter price of item:");
            System.out.println(itemPrice = enterPrice.nextDouble());

            if (itemPrice < budgetRemaining) {
                budgetRemaining -= itemPrice;

                if (itemPrice < 0) {
                    budgetRemaining += itemPrice;
                    System.out.println("Sorry, you have entered an invalid amount. ");
                }


            } else if (itemPrice > budgetRemaining) {
                System.out.println("Sorry, your item exceeds your budget.");
            }

            if (itemPrice == budgetRemaining) {
                budgetRemaining = 0;
                System.out.println("You have reached your maximum budget. Thank you for shopping with us!");
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

如果您不想在name="{$svgpre}g"小于0时停止,请从while循环中删除&& itemPrice >= 0条件。