1

I'm trying to keep a scanner command in a while loop until the user gives good input. If I run the following, it keeps looping through without waiting for input if I get the input wrong first (but waits for the first input). Why is that?

while (true){ 
    System.out.println("Enter temperature in Fahrenheit: ");
    try {
        x = in.nextFloat();
        break;
    } catch (InputMismatchException e) {
        System.out.println("Please enter a valid temperature!");
        e.printStackTrace();
        continue;
    }
}
  • We need to see more code. Maybe a complete running solution as we cannot tell what `in` does. Also, the continue isn't needed there. The behavior is the same without it. – just_a_programmer Mar 06 '20 at 17:27
  • 1
    @just_a_programmer safe to assume that `in` is a `Scanner`... because of the `.nextFloat()` method. Make sure you're calling `.nextLine()` after `.nextFloat()` to **consume the newline character**. – sleepToken Mar 06 '20 at 17:30
  • Try adding in.nextLine() in the try-catch block. – farmac Mar 06 '20 at 17:30
  • This fixed it. Thank you! –  Mar 06 '20 at 18:00

2 Answers2

2

Try this way:

    while (true){ 
        System.out.println("Enter temperature in Fahrenheit: ");
        try {
            x = Float.parseFloat(in.nextLine());
            break;
        } catch (Exception e) {
            System.out.println("Please enter a valid temperature!");
            e.printStackTrace();
            continue;
        }
    }
Sir Beethoven
  • 313
  • 1
  • 8
1

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.

per https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

It's rereading the same token over and over, continually trying to convert it to a float and failing.

You need to consume that token inside the exception handler, so that the next iteration of the loop will block waiting for more input.

Dave Costa
  • 44,298
  • 8
  • 52
  • 70