【问题标题】:Using a Try / Catch in a while loop在 while 循环中使用 Try / Catch
【发布时间】:2016-05-14 14:33:58
【问题描述】:

我要求我的用户通过正则表达式格式“ABC-1234”输入,否则会抛出 IllegalArgumentException。我想继续要求正确的输入(我正在考虑 while 或 do while 将布尔变量设置为 false 而输入不正确......)我将如何使用 try/catch 来做到这一点?

这是我到目前为止所拥有的。谢谢!

try {
            Scanner in = new Scanner (System.in);

            System.out.println("Please enter id: ");
            String id = in.nextLine();

            Inventory i1 = new Inventory (id, "sally", 14, 2, 2);
            System.out.println(i1);

        } catch (Exception ex) {

             System.out.println(ex.getMessage());

        }

【问题讨论】:

    标签: java while-loop try-catch do-while illegalargumentexception


    【解决方案1】:

    显然,您需要某种循环,并且您需要某种机制在成功时跳出循环。假设 IllegalArgumentException 是从 Inventory 构造函数中抛出的,您的解决方案可以简单地是:

    while (true) {
        try {
            // ...
            Inventory i1 = new Inventory(id, "sally", 12, 2, 2);
            System.out.println(i1);
            break; // or return i1 if you enclose this snippet in a function
        } catch (Exception ex) {
            // ...
        }
    } 
    

    【讨论】:

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