0

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;
user3053348
  • 9
  • 1
  • 4

3 Answers3

0

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

jbangerter
  • 366
  • 1
  • 9
0

you need to define Scanner for reading user input try following

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"); 
           Scanner reader = new Scanner(System.in);
           userEnteredNumber = reader.nextInt();
dev2d
  • 4,245
  • 3
  • 31
  • 54
0
 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"); 

There are missing parameters in the string format

There are 6 sets of "%s\t%s%n" when you only require 5 sets for the options, the missing parameters for the 6th is creating an exception

FuriKuri
  • 76
  • 1
  • Thank you. That fixes my other problem as well. Although I called this menu in first in the main, it was automatically going to a later menu. – user3053348 Dec 11 '13 at 03:15