【问题标题】:Implementing try-catch inside a loop在循环中实现 try-catch
【发布时间】:2020-07-13 15:33:19
【问题描述】:

我想在循环中创建一个 try-catch 块,让用户有多个机会以正确的格式输入信息。当我输入格式不正确的内容时,程序会显示 sysout 消息“请输入格式正确的姓名和年龄”。来自 catch 块。

问题是当我在此消息之后输入格式正确的信息时,它一直显示相同的消息“请以正确的格式输入姓名和年龄”。即使它应该退出并询问我是否要继续。

这是我所拥有的:

        int inAge;
        String inName;

        while (true) {
            try {
                inAge = Integer.parseInt((input.substring((input.indexOf(',') + 1))));
                inName = input.substring(0, input.indexOf(','));
                list.add(new Plant(inName, inAge));
                break;
            } catch (Exception e) {
                System.out.println("Please enter name and age with correct format.");
                in.next();
            }
        }

        System.out.println("Do you wish to continue? (Yes or No)");
        endOrNo = in.nextLine();

        if ("yes".equalsIgnoreCase(endOrNo))
            go = true;
        else
            go = false;

【问题讨论】:

    标签: java loops try-catch user-input


    【解决方案1】:

    您可能调用 next() 而不是 nextLine(),这可能会读取错误的输入并不断将您带回异常块。

    【讨论】:

      【解决方案2】:

      你需要更新输入变量的值。

      while (true) {
                  try {
                      input = in.nextLine(); // accept input
                      inAge = Integer.parseInt((input.substring((input.indexOf(',') + 1))));
                      inName = input.substring(0, input.indexOf(','));
                      list.add(new Plant(inName, inAge));
                      break;
                  } catch (Exception e) {
                      System.out.println("Please enter name and age with correct format.");
                      input = in.next();
                  }
              }
      
              System.out.println("Do you wish to continue? (Yes or No)");
              endOrNo = in.nextLine();
      
              if ("yes".equalsIgnoreCase(endOrNo))
                  go = true;
              else
                  go = false;
       
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-05-27
        • 2015-04-24
        • 2014-09-11
        • 1970-01-01
        • 2017-10-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多