简体   繁体   English

浮点变量和异常处理

[英]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. 每当你在这个程序中输入一个字母时,程序当然会抛出一个InputMismatchException,但它会被卡在无限循环中。 I assume my problem is based off of my misunderstanding of try-catch statements and exception handling. 我认为我的问题是基于我对try-catch语句和异常处理的误解。

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 . Float#nextFloat()如果抛出InputMismatchException则不会使用Scanner的令牌。 So when you get the exception and loop (because done is still false ), you try to call nextFloat() again. 所以当你得到异常和循环(因为done仍然是false )时,你会尝试再次调用nextFloat() Since the token is still not a value that can parsed into a float , the Scanner again throws the exception. 由于令牌仍然不是可以解析为float的值,因此Scanner再次抛出异常。 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. 您应该使用hasNextFloat()来检查是否存在可以解析为float值的标记。 Or consume the incorrect value with Scanner#next() , as suggested by Quirliom . 或者使用Scanner#next()消耗不正确的值,如Quirliom所建议的那样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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