First of all there are two roots(values for x) in quadratic equation. you have to find those two. That roots can be either real roots or imaginary roots based on b*b-4*a*c
positive or negative. Since solution for a*x^2+b*x+c=0, is x=[-b+squareroot(b^2-4*a*c)]/2*a
or x=[-b-squareroot(b^2-4*a*c)]/2*a
. So there are no real values if b^2-4*a*c<0
. You should learn that first. follow this link.
You can do something like this
public static void main(String[] args) {
Double[] result = quadraticEquation(4, 8, 1);
if(result==null){
System.out.println("There is no real roots for x");
}else{
for(Double d:result){
System.out.println("value for x:" +d);
}
}
}
public static Double[] quadraticEquation(int a, int b, int c) {
Double[] arr = new Double[2];
if ((b*b - (4 * a * c)) < 0) {
return null;
} else {
arr[0] = (-b + Math.sqrt((b*b - 4 * a * c))) / 2 * a;
arr[1] = (-b - Math.sqrt((b*b - 4 * a * c))) / 2 * a;
}
return arr;
}
I don't know why you want only one solution. If you really want one you can do as follows.
public static void main(String[] args) {
Double result = quadraticEquation(4, 8, 1);
if(result==null){
System.out.println("There is no real roots for x");
}else{
System.out.println("a value for x:" +result);
}
}
public static Double quadraticEquation(int a, int b, int c) {
Double val =0.0;
if ((b*b - (4 * a * c)) < 0) {
return null;
} else {
val = (-b + Math.sqrt((b*b - 4 * a * c))) / 2 * a;
}
return val;
}