Search code examples
javaloopswhile-loopinfinite-loopinfinite

Loop repeating infinitely and displaying error message without user prompting


When this loop is called if runs infinitely and displays the catch error without the user even entering anything. I am not able to find any reasons for this. Suggestions?

 public Purchase groceryStoreMenu(LemonadeStand lemonadeStand) {

    boolean getMenu = true;
    int userEnteredNumber = -1;
    currentPurchase = new Purchase();

    while(getMenu){
         try{

           System.out.println("Grocery Store");
           System.out.printf("%s\t%s%n%s\t%s%n%s\t%s%n%s\t%s%n%s\t%s%n%s\t%s%n" , "1:" , "Buy lemons", "2:", "Buy cups" , "3:" , "Buy sugar" , 
           "4:" , "Buy ice" , "5:" , "Done"); 

           userEnteredNumber = reader.nextInt();

           if (userEnteredNumber == 1 ) {
              money = lemonadeStand.profit(0);
              lemonsMenu(money);
           }else if (userEnteredNumber == 2){
              money = lemonadeStand.profit(0);
              cupsMenu(money); 
           }else if (userEnteredNumber == 3){
              money = lemonadeStand.profit(0);
              sugarMenu(money); 
           }else if (userEnteredNumber == 4){
               money = lemonadeStand.profit(0);
               iceMenu(money); 
           }else if (userEnteredNumber == 5){
             getMenu = false;
           } else {
            throw new Exception();
           }
          } catch(Exception e) {
            System.out.println("Error in number format. Enter a valid number from the choices (1,2,3,4,5)");
          }

    }
   return currentPurchase;

Solution

  • Your code isn't stopping at reader.nextInt(). This is probably because you aren't waiting for user input in that method.