简体   繁体   中英

Floating-Point Variables and Exception Handling

My program is supposed to accept a floating-point variable and then exit. However I am practicing some exception handling stuff and found a problem. Whenever you enter a letter into this program the program of course throws an InputMismatchException but it gets stuck inside an infinite loop. I assume my problem is based off of my misunderstanding of try-catch statements and exception handling.

public static void main(String [] args){

    Scanner reader = new Scanner(System.in);
    boolean done = false;

    do{
        try{
            System.out.print("Enter a number: ");
            float number = reader.nextFloat();
            done = true;
        }
        catch (Exception e){
            System.out.println("uh oh");
        }
    }while(!done);
}

This problem does not occur if I use a different variable type so I'm not sure if it's a logical error or just something funky with floating-point variables.

Float#nextFloat() does not consume the token in the Scanner if it throws an InputMismatchException . So when you get the exception and loop (because done is still false ), you try to call nextFloat() again. Since the token is still not a value that can parsed into a float , the Scanner again throws the exception. And again, and again, ad nauseam.

You should use hasNextFloat() to check for the existence of a token that can be parsed to a float value. Or consume the incorrect value with Scanner#next() , as suggested by Quirliom .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM