Вопрос

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;
Это было полезно?

Решение

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

Другие советы

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top