如果结果等于nan或-infinity,我无法找出一种捕捉或给我程序的订单。每当我将0输入我的程序时,它都会给我NAN和-Infinity的结果。我面临的问题是X1和X2是双重类型,显然无法与字符串类型进行比较。任何帮助将不胜感激。
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");
}
}
}
您可以通过执行
检查NaN
if (Double.isNaN(yourResult)) { ... }
和无限制:
if (Double.isInfinite(yourResult)) { ... }
您绝不应该使用==
检查NaN
,因为NaN
被认为不等于NaN
!
或者,您可以检查a
是否为0。因为这可能是Infinity和Nan出来的唯一情况。如果是,请说"我的菜在哪里?":(
另外,我只是尝试给出Nan NaN NaN
,但什么也没输出。考虑检查A,B和C是否也是NAN或无限态度。:(
简单地可以通过在使用之前验证输入A,B和C来避免您的错误。
。ex:检查a!= 0。