Search code examples
mathnanequationquadratic

I am getting NaN for an answer to my quadratic equation calculator- JAVA


This is my main class:

import java.util.Scanner;

public class calc {
public static void main(String[] args){
    Scanner variablea = new Scanner(System.in);
    Scanner variableb = new Scanner(System.in);
    Scanner variablec = new Scanner(System.in);
    int a1, b1, c1;
    System.out.println("enter your 'A' variable");
    a1 = variablea.nextInt();
    System.out.println("enter your 'B' variable");
    b1 = variableb.nextInt();
    System.out.println("enter your 'C' variable");
    c1 = variablec.nextInt();

    algorithm algorithmObject = new algorithm();
    algorithmObject.algorithm(a1, b1, c1);

}

}

and this is the second one

      public class algorithm{
public void algorithm(int a, int b, int c){
    double x1;
    double square = Math.sqrt(b*b - 4*a*c);
    double numerator = b*-1 + square;
    double finalanswer = numerator/2*a;

    System.out.println(finalanswer);
}

}

Eclipse doesn't give me any errors, but after it asks for my 3 variables and I enter them, it just gives NaN. Any idea what I have done wrong?


Solution

  • There are issues with the code but the culprit is most likely this line:

    double square = Math.sqrt(b*b - 4*a*c);
    

    If b*b - 4*a*c is negative (there is no solution to the equation) then square is NaN and every computation involving it will be NaN as well. You can check it here.


    You could improve your calculator by first checking if b*b - 4*a*c < 0 and if it is so then you could write to the console that there is no real solution (and of course stop the computations there).


    I would change public void algorithm(int a, int b, int c) to

    public void algorithm(double a, double b, double c)
    

    Integer arithmetic can surprise you when you least expect it and I see no reason why a, b and c should be constrained to be int-s.


    OK, hope this helped.