在 while 循环中执行 try/catch

Executing a try/catch within a while loop

我正在尝试在 while 循环中执行 try catch 块。当我要求用户输入一个数字(应该是双精度数字)时,我使用 try catch 来捕获任何输入不匹配异常。我将它嵌套在一个 while 循环中,这样如果捕获到任何异常,用户可以根据需要重新输入他们的输入。问题是如果捕获到异常,扫描器将出于某种原因不允许用户重新输入他们的输入。当您 return 到显示 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.");
        }
    }

根据 Class Scanner 的文档:

"When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method."

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