quadratic equation solver help!

• October 20th, 2011, 08:41 AM
overlord
quadratic equation solver help!
I need to write a program that prints all real solutions to the quadratic equation "ax2 + bx + c = 0" i need to implementa class QuadraticEquation whose constructor recieves the coefficients of a, b and c and i need to supply methods getSolution1 and getSolution2 and the getSolution1 should return the smaller number. Lastly i also need to supply a method boolean hasSolution() that returns false if the Discriminant is negative. Any help would be greatly appreciated because I dont even have a clue of where to start
• October 20th, 2011, 09:11 AM
copeg
Re: quadratic equation solver help!
• October 20th, 2011, 11:39 AM
Tjstretch
Re: quadratic equation solver help!
First hint, you're going to have to (For greatest ease) delete the whitespace before you attempt to decode its formula. Then you need to decide how your x2 is going to look like. EG, x^2 x2 xpow2.
Then you can either complete the square, or just use the quadratic formula.

As for your hasSolution method, it is going to need parameters a, b and c, like
Code Java:

```public static boolean hasSolution(double a, double b, double c) { //Code not included }```

Your main method is going to have to start with some kind of decoder, however it will be either really simple or medium difficulty depending on if you are going to allow more then 1 number coefficients. May I recommend using two-three lines for the quadratic formula,
it will look much cleaner.

Back to the decoder, since you know it will have the number x at the end of a and b, a quick for loop and second string will do the trick

Code Java:

```/* *Precondition: input is the user's input */ char c = input.charAt(0); int i = 1; String stringA = ""; while(c != 'x') { stringA += c; c = input.charAt(i); i++; }```
Then you need to skip 1 chars for the ^2 (Assuming you use that), then you need to check if is ax^2 + bx + c = 0, or ax^2 -bx + c, so
Code Java:

```double a = Double.valueOf(stringA); i += 1; //We are already at the x char operator = input.charAt(i);```
We can ignore the operator for right now.
That is pretty much the first step, for decoding the rest, the logic will be
for B:
• Get all the chars before the second x
• Convert the value into a double.
• If operator1 is a subtraction sign, multibly b by -1
• Increment i again to get past the x, and to the operator
• Save the operator in operator

For c,
do what you did for a, except without looking for an operator and waiting for '=' instead of x.