I am failing to figure out a way to catch, or give order to my program if the result equals with NaN or -infinity. Whenever I enter 0 into my program it gives me a result of NaN and -Infinity. The problem I am facing is that the x1 and x2 are double types, that obviously can't be compared with String type. Any help would be much appreciated.
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");
}
}
}
You can check for NaN by doing
if (Double.isNaN(yourResult)) { ... }
And infinities by doing:
if (Double.isInfinite(yourResult)) { ... }
You should never use == to check for NaN because NaN is considered not equal to NaN!
Or, you can just check whether a is 0. Because that is probably the only case where Infinity and NaN will come out. If it is, say something like "Where's my a dish?" :)
Also, I just tried giving Nan NaN NaN and it output nothing. Consider checking whether a, b and c are NaN or Infinities as well. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With