I am working on a Java project. It is a simple Quadratic Formula code. But when I wanted to convert my double value to a string (where a=1.0, b=0 and c= -4.0 in ax^2+bx+c)
. My test failed. I tried to figure out what went wrong. I found out where it was and apparently Double.toString(x)
where double x=2.0
, did not return "2.0". So then I tried
String.valueOf(x), which did not work either. I then simple put
"2.0"` and it passed my test cases.
Where did I go wrong? Or does Java just hate me.
edit: Wow you guys, commented so quickly. Any advice will be helpful, including things not related to the original topic (repeated syntax or whatever).
Note: As my story says, the only thing I changed was Double.toString(x1) to "2.0" when content was "1.0 0 -4.0" and it passed my test case.
public class QuadraticFormula {
public String quadraticFormula(String content) {
//**
* content should be a string in the format of "a b c" or this will
* return an empty string.
* returning "" will indicate that content was not correctly inputted.
* returns a string in the format of "x1 and x2" where x1 and x2 are the
* answers from the Quadratic Formula.
*/
try {
int m=content.indexOf(" ");
int n=content.indexOf(" ", m+1);
if (m==-1||n==-1) {
return "";
}
double a=Double.parseDouble(content.substring(0,m));
double b=Double.parseDouble(content.substring(m+1,n));
double c=Double.parseDouble(content.substring(n+1));
if (b*b<4*a*c) {
return "imaginary";
} else {
double x1=(-b+Math.sqrt(Math.abs(b*b-4*a*c)))/(2*a);
double x2=(-b-Math.sqrt(Math.abs(b*b-4*a*c)))/(2*a);
return Double.toString(x1) + " and " + Double.toString(x2);
}
} catch (IndexOutOfBoundsException e) {
return "";
} catch (NullPointerException e) {
return "";
} catch (NumberFormatException e) {
return "";
}
}
}