This question is for my intro to Java class and the question is asking me to use classes to solve a quadratic equation.
I am trying to fix my class so that it doesn't return NaN. I have used Math.abs()
to try and fix any situation where the number under the radical would be a negative number, but I'm still getting NaN. Here is my code for the class:
public class Quadratic
{
//Private data members
private double a;
private double b;
private double c;
private double posX;
private double negX;
//Deafault constructor
public void Quadratic()
{
a = 1;
b = 0;
c = 0;
posX = 0;
negX = 0;
}
//The mutators
public void setQuad(Double alpha, double bravo, double charlie)
{
alpha = a;
bravo = b;
charlie = c;
getQuad();
}
//The accessors
public double getQuad()
{
double temp = (Math.pow(b, 2) - (4 * a * c));//getting the number inside the root
if(temp < 0)
temp = Math.abs(temp);
//ensures that the function can run until complex numbers are sorted
posX = (-b + (Math.sqrt(temp)))/(2 * a);//calculates when added
negX = (-b + (Math.sqrt(temp)))/(2 * a);//calculates when subtracted
//error: Keep getting NaN for answers, already accounted for negative inside the root
// not a 0 in the descriminant.
return 0;
}
//My toString which is what will be output at System.out.println(N)
public String toString()
{
if(negX == posX)
return "X = "+ negX;
else
return "X = "+ negX +" and "+ posX;
}
}
Is my math incorrect, or am I using the math utilities incorrectly?