1
votes

I am trying to execute a try catch block within a while loop. When I ask the user to enter a number (which should be a double) I use a try catch to catch any input mismatch exceptions. I nested this inside a while loop so that if any exceptions are caught, the user may re-enter their input as necessary. The problem is that if an exception is caught, the scanner will not allow the user to re-enter their input for some reason. The errors are caught during the second iteration when you return to the line that says hours = kb.nextDouble. Here is the code.

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.");
        }
    }
1

1 Answers

0
votes

According to the doc for 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."

Putting kb.next() in the catch block would serve to skip the offending input.