我找不到一种方法来捕捉,或者在结果等于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");
}
}
}发布于 2018-02-22 15:48:52
您可以通过执行以下操作来检查NaN
if (Double.isNaN(yourResult)) { ... }和无穷大,通过做以下操作:
if (Double.isInfinite(yourResult)) { ... }您不应该使用==来检查NaN,因为NaN被认为不等于NaN!
或者,您可以只检查a是否为0。因为这可能是无穷大和NaN出现的唯一情况。如果是,就说“我的菜在哪里?”:)
另外,我刚试着给Nan NaN NaN赋值,结果什么也没有输出。考虑检查a、b和c是否也是NaN或无穷大。:)
发布于 2018-02-22 16:11:15
简单地说,你的错误可以通过在使用之前验证你的输入a,b和c来避免。
例如:检查a!=0。
https://stackoverflow.com/questions/48921978
复制相似问题