java NaN和-infinity

时间:2018-02-22 07:41:43

标签: java string double try-catch

如果结果等于NaN或-infinity,我没有想办法捕捉或命令我的程序。 每当我在程序中输入0时,它会给我一个NaN和-Infinity的结果。 我面临的问题是x1和x2是双重类型,显然无法与String类型进行比较。任何帮助将不胜感激。

public class Exercise {

public static void main(String[] args){
    double x1 = 0;
    double x2 = 0;

    Scanner scanner = new Scanner(System.in);

    System.out.println("Feed me with a, b and c");

    try{
            double a = scanner.nextDouble();
            double b = scanner.nextDouble();
            double c = scanner.nextDouble();
            scanner.close();
            double discriminant = (b * b) - 4 * (a * c);

        if (discriminant > 0){

            x1 = (-b + Math.sqrt(discriminant)) / (2 * a);
            x2 = (-b - Math.sqrt(discriminant)) / (2 * a);

            System.out.println("The dish of yours has two components " + x1 
        + " and " + x2);
        }

        if (discriminant == 0){

            x1 = -b / (2 * a);
            System.out.println("The dish of yours has two identical 
        components " + x1 +" and " + x1);

        }

        if (discriminant < 0){

            System.out.println("The dish of yours doesn't have any 
         component");

        }

        }
        catch (InputMismatchException e) {
            System.out.println("I can't digest letters");
        }
        catch (Exception e) {
            System.out.println("This is inedible");
    }
    }
    }

2 个答案:

答案 0 :(得分:5)

您可以通过

检查NaN
if (Double.isNaN(yourResult)) { ... }

无限性:

if (Double.isInfinite(yourResult)) { ... }

您永远不应该使用==来检查NaN,因为NaN被视为不等于NaN

或者,您可以检查a是否为0.因为这可能是Infinity和NaN出现的唯一情况。如果是这样的话,可以说&#34;哪里有我的菜?&#34; :)

另外,我只是试着给Nan NaN NaN并且它什么都没输出。考虑检查a,b和c是否也是NaN或Infinities。 :)

答案 1 :(得分:0)

在使用之前,通过验证输入a,b和c,可以避免错误。

Ex:检查是否!= 0。