0

when an invalid input is entered it goes to the catch block and infinitely executes the catch block without looping back to try block to get another input

It works when valid data is entered

public static double getInputNumber(Scanner input){
    double num=0;
    while(true) {
        try {
            num = input.nextDouble();
            return num;
        } catch (Exception ex) {
            System.out.println("Invalid value entered.. Enter again : ");
        }
    }
}

expected - when an invalid value entered,show the user the error message and get a re-input until the users enters a valid value.

actual - when invalid value entered it displays the error message repeatedly in the screen without going for a re-input

  • Possible duplicate of [Try-Catch inside While Loop](https://stackoverflow.com/questions/24857070/try-catch-inside-while-loop) – Marcin Chaj Sep 10 '19 at 04:53

2 Answers2

0

Just add input.next()

} catch (Exception ex) {
   System.out.println("Invalid value entered.. Enter again : ");
   input.next();
}

input.next() clears scanner.

0

It could well be that input has been closed, or the next token in the input is NOT a double. Either of these would cause an exception to be thrown, without advancing the input, so resulting in your infinite loop.

So you need to catch the cause of the error, to take the appropriate action - eg, something like :

public static double getInputNumber(Scanner input){
    double num=0;
    while(true) {
              try {
                  num = input.nextDouble();
                  return num;
               } catch (InputMismatchException ex) {
                   System.out.println("Invalid value entered.. Enter again : ");
               } catch (NoSuchElementException ex) {
                   System.out.println("Input exhausted ");
                   return 0;
               } catch (IllegalStateException ex) {
                   System.out.println("Scanner closed ");
                   return 0;
               }
          }
    }
}

You could also use input.hasNextDouble() to check before calling nextDouble()

racraman
  • 4,988
  • 1
  • 16
  • 16