java - 用户输入后循环不中断,中断前需要多个输入

我的循环有问题。我试图让用户输入一个数字选择,如果他们选择一个项目会重复,如果他们输入 5 则退出。但是,在运行它时,如果我选择 2 个项目,则需要我输入 5 两次才能退出循环.

我很感激任何帮助。

public static void coffee() {
        double espressoP = 4.50;
        double latteP = 4.50;
        double cappuccinoP = 6.00;
        double coldBrewP = 4.00;
        int coffeeChoice = 0;
        boolean exit = true;
        
        
        System.out.println("=== Select Coffee: ===");
        System.out.println("1. Espresso   $4.50");
        System.out.println("2. Latte      $4.50");
        System.out.println("3. Cappuccino $6.00");
        System.out.println("4. Cold Brew  $4.00");
        System.out.println("5. Quit coffee selection.");
        System.out.println("Select a coffee [Enter 1 - 5]:");
        
        while (exit = true) {
            coffeeChoice = scnr.nextInt();
            if (coffeeChoice == 1) {
                System.out.println("Added 1 Espresso.");
                C1 += 1;
                totPrice = totPrice + espressoP;
                System.out.println(C1 + " " + totPrice);
                coffee();
            }
            else if (coffeeChoice == 2) {
                System.out.println("Added 1 Latte.");
                C2 += 1;
                totPrice = totPrice + latteP;
                System.out.println(C2 + " " + totPrice);
                coffee();
            }
            else if (coffeeChoice == 3) {
                System.out.println("Added 1 Cappuccino.");
                C3 += 1;
                totPrice = totPrice + cappuccinoP;
                System.out.println(C3 + " " + totPrice);
                coffee();
            }
            else if (coffeeChoice == 4) {
                System.out.println("Added 1 Cold Brew.");
                C4 += 1;
                totPrice = totPrice + coldBrewP;
                System.out.println(C4 + " " + totPrice);
                coffee();
            }
            else if (coffeeChoice == 5) {
                exit = false;
                break;
                
            }
            else {
                System.out.println("Invalid entry. Enter a selection between 1 and 5.");
                scnr.next();
            }
                 
        }

回答1

更新。同意评论。 exit = true 是一个错字,break 将使其无效。多次要求输入“5”的原因是因为递归。

相似文章

随机推荐

最新文章