Home > Software engineering >  While loop not breaking after user input, requiring multiple inputs before breaking
While loop not breaking after user input, requiring multiple inputs before breaking

Time:05-19

I'm having issues with my loop. I'm trying to have the user input a number selection that repeats if they select an item and exits if they input 5. However, when running it, if I select 2 items, it would require me to enter 5 twice to exit the loop.

I appreciate any help.

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

CodePudding user response:

Updated. Agree with comments. exit = true is a typo, break will nullify it. Reason of multiple asking for input "5" is because of recursion.

  •  Tags:  
  • java
  • Related