While loop skips user input

RandomSnek :

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;
    }
}
Sir Beethoven :

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;
        }
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31358&siteId=1