有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java My while循环似乎正在重新启动,除非插入负数?

我的while循环工作正常,直到我输入一个负数,我做错了什么?输入负数后,循环停止,代码完成执行。我希望它重新启动完整的while循环,以便我可以继续输入,直到BudgetMaining达到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) 个答案

  1. # 1 楼答案

    如果不希望在itemPrice小于0时停止while循环,请从while循环中删除&& itemPrice >= 0条件