【问题标题】:Executing a try/catch within a while loop在 while 循环中执行 try/catch
【发布时间】:2015-04-24 09:19:44
【问题描述】:

我正在尝试在 while 循环中执行 try catch 块。当我要求用户输入一个数字(应该是一个数字)时,我使用 try catch 来捕获任何输入不匹配异常。我将它嵌套在一个while循环中,以便如果捕获到任何异常,用户可以根据需要重新输入他们的输入。问题是,如果捕获到异常,扫描器将由于某种原因不允许用户重新输入他们的输入。当您返回显示 hours = kb.nextDouble 的行时,会在第二次迭代期间捕获错误。这是代码。

boolean condition = true;
while(condition==true) {
    try {
    // prompt user to enter hours of service used
    System.out.println("Please enter the number of hours of service you  have used: ");
    hours = kb.nextDouble();
    // validate hours
    while(hours <=0){
    System.out.println("You must enter a positive number.");
    hours = kb.nextDouble();    
    } condition = false;
    } catch (InputMismatchException ime){
        System.out.println("You must enter a decimal value for hours.");
        }
    }

【问题讨论】:

    标签: exception-handling while-loop try-catch nested-loops inputmismatchexception


    【解决方案1】:

    根据Class Scanner的文档:

    "当扫描器抛出 InputMismatchException 时,扫描器不会 传递导致异常的令牌,以便可以检索它 或通过其他方法跳过。”

    将 kb.next() 放入 catch 块中可以跳过有问题的输入。

    【讨论】:

    • 感谢您的解释!
    猜你喜欢
    • 2014-09-11
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多