在while循环中执行try/catch



我正试图在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.");
        }
    }

根据类别扫描仪的文档:

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

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

最新更新