循环无限重复并在没有用户提示的情况下显示错误消息

时间:2013-12-11 02:52:01

标签: java loops while-loop infinite-loop infinite

当调用此循环时,如果无限运行并显示catch错误而用户甚至不输入任何内容。我无法找到任何理由。建议?

 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;

3 个答案:

答案 0 :(得分:0)

您的代码并未停留在reader.nextInt()。这可能是因为您没有等待该方法中的用户输入。

答案 1 :(得分:0)

您需要定义Scanner以读取用户输入,请尝试按照

进行操作
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();

答案 2 :(得分: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"); 

字符串格式中缺少参数

当您只需要5组选项时,有6组“%s \ t%s%n”,第6项缺少的参数正在创建例外