繁体   English   中英

循环无限重复并显示错误消息,而无需用户提示

[英]Loop repeating infinitely and displaying error message without user prompting

调用此循环时,if无限运行并显示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;

您的代码不会在reader.nextInt()处停止。 这可能是因为您不等待该方法中的用户输入。

您需要定义扫描仪以读取用户输入,请尝试以下操作

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

字符串格式缺少参数

当您只需要5套选项时,就有6套“%s \\ t%s%n”,第六种缺少的参数正在创建异常

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM