I have solved this problem using interpretation 1 in my request for
clarification, where a text menu is used, since it seems probably to
me that this is the desired interpretation. If you would like instead
a windowing interface, please indicate this and I can provide a Swing
application.
I am not sure what is meant by the line:
"Please try to include explanations where appropriate"
I am not sure how much expertise in Java you have, so I am not sure
what explanation to include. If you any part of the Java program I
have given is not clear, use the "Request Clarification" to solicit
clarification and I would be happy to clarify the solution.
Similarly, if you would like detailed comments in the code, I would be
happy to provide that as well. Also, if you want javaDoc style
comments, please so indicate and they can be provided.
The only subtlety here was that the problem specification is incorrect
when it states:
"If a and b are both zero there is no solution"
In fact, if a,b, and c are each 0, then there is an infinity of
solutions, since any value of x trivially satisfies the equation.
It is true, however, that, if a and b are zero and c is nonzero, then
there are no solutions.
If you would like different functionality or increased functionality,
please so indicate using "Request Clarification" button and I will be
happy to modify the code per specification.
I am enclosing a sample script run below.
Log for run of Quadratic .
Comments (not in actual log) are preceded by the "#" character.
Some blank lines have been added for clarity.
% javac Quadratic.java
% java Quadratic
1. Calculate quadratic
2. End
Input option: 1
# This is the golden ratio: the solution to x^2x1=0
# (actually only the first solution is the golden ratio)
Input a, b, and c separated by spaces
1 1 1
Solving the equation: 1*x^2 + 1*x + 1 = 0
Solutions are: X= 1.618033988749895 or X= 0.6180339887498949
1. Calculate quadratic
2. End
Input option: 1
Input a, b, and c separated by spaces
1 4 4
Solving the equation: 1*x^2 + 4*x + 4 = 0
Solution is: x= 2.0
1. Calculate quadratic
2. End
Input option: 1
# An equation with no solutions, because a=b=0
Input a, b, and c separated by spaces
0 0 8
Solving the equation: 0*x^2 + 0*x + 8 = 0
No solutions
1. Calculate quadratic
2. End
Input option: 1
# An equation with infinity of solutions because a=b=0
Input a, b, and c separated by spaces
0 0 0
Solving the equation: 0*x^2 + 0*x + 0 = 0
All x are solutions
1. Calculate quadratic
2. End
Input option: 1
# A linear equation
Input a, b, and c separated by spaces
0 2 8
Solving the equation: 0*x^2 + 2*x + 8 = 0
Solution is: x= 4.0
1. Calculate quadratic
2. End
Input option: 1
Input a, b, and c separated by spaces
2 8 8
Solving the equation: 2*x^2 + 8*x + 8 = 0
Solution is: x= 2.0
1. Calculate quadratic
2. End
Solving the equation: 1*x^2 + 3*x + 2 = 0
Solutions are: X= 2.0 or X= 1.0
1. Calculate quadratic
2. End
Input option: 2
[Program halts]
Here is the actual code, which I have also placed at
http://www.rbnn.com/google/Quadratic.java .
Quadratic.java
import java.io.*;
import java.util.StringTokenizer;
public class Quadratic{
public double a;
public double b;
public double c;
public double[] roots;
public Quadratic(double a, double b, double c){
this.a=a;
this.b=b;
this.c=c;
}
public double[] solve(){
if (a==0&&b==0&&c==0)
roots=null;
else if (a==0&&b==0)
roots=new double[0];
else if (a==0)
roots=new double[]{c/b};
else{
double discriminant= b*b4*a*c;
if (discriminant<0)
roots=new double[0];
else if (discriminant==0)
roots=new double[]{ (b + Math.sqrt(discriminant))/(2*a)};
else
roots=new double[]{
(b + Math.sqrt(discriminant))/(2*a),
(b  Math.sqrt(discriminant))/(2*a)
};
}
return roots;
}
public static void main(String[] args){
try{
BufferedReader reader=new BufferedReader(new
InputStreamReader(System.in));
while(true){
System.out.println("1. Calculate quadratic");
System.out.println("2. End");
System.out.print("Input option: ");
String line=reader.readLine();
int option;
try{
option=Integer.parseInt(line);
}
catch(NumberFormatException e){
System.out.println("Invalid entry. Try again");
continue;
}
if (option==2) System.exit(0);
if (option!=1){
System.out.println("Invalid option. Try once more");
continue;
}
System.out.println("Input a, b, and c separated by spaces");
line=reader.readLine();
StringTokenizer tokenizer=new StringTokenizer(line);
if (tokenizer.countTokens()!=3){
System.out.println("Invalid coefficients: expected 3
coefficients");
continue;
}
int a,b,c;
try{
a=Integer.parseInt(tokenizer.nextToken());
b=Integer.parseInt(tokenizer.nextToken());
c=Integer.parseInt(tokenizer.nextToken());
}
catch(NumberFormatException e){
System.out.println("coeffecients must be integers");
continue;
}
Quadratic quadratic=new Quadratic(a,b,c);
System.out.println("Solving the equation: "+a+"*x^2 + "+b+"*x +
"+c+" = 0");
double[]roots=quadratic.solve();
if (roots==null)
System.out.println("All x are solutions");
else if (roots.length==0)
System.out.println("No solutions");
else if (roots.length==1)
System.out.println("Solution is: x= "+roots[0]);
else if (roots.length==2)
System.out.println("Solutions are: X= "+roots[0]+" or X=
"+roots[1]);
}
}
catch(Exception e){
System.out.println("Unexpected error: "+e);
System.exit(1);
}
}
} 
Clarification of Answer by
rbnnga
on
02 Dec 2002 12:32 PST
I have modified the program as follows:
1. I have added numerous comments throughout the code .
2. In order to simplify the code, I have removed the instance
variables and made all of the methods static. In this way, you do not
need to actually construct an instance of the Quadratic class. This
may make the code easier to understand.
3. Instead of the user putting all the coefficients on one line, I
have separately prompted for each coefficient. This avoids the use of
StringTokenizer, and I hope makes the code easier to understand .
4. I have added a blank line before each menu printing to make the
output look better.
The new code is available here:
http://www.rbnn.com/google/quadratic2/Quadratic.java
and is also appended to this clarification .
The new log run looks like this:
% javac Quadratic.java
% java Quadratic
1. Calculate quadratic
2. End
Input option: 1
Input a: 1
Input b: 1
Input c: 1
Solving the equation: 1*x^2 + 1*x + 1 = 0
Solutions are: X= 1.618033988749895 or X= 0.6180339887498949
1. Calculate quadratic
2. End
Input option: 1
Input a: 0
Input b: 0
Input c: 2
Solving the equation: 0*x^2 + 0*x + 2 = 0
No solutions
1. Calculate quadratic
2. End
Input option: 1
Input a: 1
Input b: 2
Input c: 8
Solving the equation: 1*x^2 + 2*x + 8 = 0
Solutions are: X= 2.0 or X= 4.0
1. Calculate quadratic
2. End
Input option: 1
Input a: 2
Input b: 4
Input c: 16
Solving the equation: 2*x^2 + 4*x + 16 = 0
Solutions are: X= 2.0 or X= 4.0
1. Calculate quadratic
2. End
Input option: 1
Input a: 0
Input b: 2
Input c: 8
Solving the equation: 0*x^2 + 2*x + 8 = 0
Solution is: x= 4.0
1. Calculate quadratic
2. End
Input option: 1
Input a: 1
Input b: 2
Input c: 8
Solving the equation: 1*x^2 + 2*x + 8 = 0
No solutions
1. Calculate quadratic
2. End
Input option: 2
Quadratic.java
[Because code does not usually upload well to a browser you should
probably use the URL:
http://www.rbnn.com/google/quadratic2/Quadratic.java to download the
code]
import java.io.*; // import IO stuff, used to read input from the
user
/** The class quadratic has only static methods and is used to solve
quadratics of the form
a x^2 + b x + c =0
over the reals
*/
public class Quadratic{
static BufferedReader reader; //This will be used for input from
the user.
/** This static method returns an array of doubles that
represent the roots of the equation represented by this Quadratic.
If all x are roots, then null is returned.
*/
public static double[] solve(double a, double b, double c){
if (a==0&&b==0&&c==0) //All values are roots
return null;
else if (a==0&&b==0) //no roots
return new double[0]; // return empty array
else if (a==0) //linear equation?
return new double[]{c/b}; //return array with one element
else{
double discriminant= b*b4*a*c;
if (discriminant<0) //roots are nonreal?
return new double[0]; //return empty array
else if (discriminant==0) //only one root?
//Just return an array whose only element is that root
return new double[]{ (b + Math.sqrt(discriminant))/(2*a)};
else // two roots
//So just return an array with two elements that equal the roots in
question
return new double[]{
(b + Math.sqrt(discriminant))/(2*a),
(b  Math.sqrt(discriminant))/(2*a)
};
}
}
/** The main method continually requests input from the user.
The user is presented with a text menu whether to continue or not,
and coefficients are requested
until End is selected in the menu.
*/
public static void main(String[] args){
//Initialize the reader so that we can read input from standard input
try{
reader=new BufferedReader(new InputStreamReader(System.in));
}
catch(Exception e){ //Some unexpected IO error occurred, so exit
System.err.println("Unable to create reader");
System.exit(1); //give up
}
while(true){ //do this forever, until user wants to end
System.out.println("\n1. Calculate quadratic");
System.out.println("2. End");
System.out.print("Input option: ");
int option = readint(); // Read the option the user selected
if (option<1option>2){ //bad option
System.out.println("Invalid option, try again");
continue; //Try again
}
if (option==2) //user is done
System.exit(0); //exit normally
//Now the user has selected option 1, so we get the coefficients
System.out.print("Input a: ");
int acoeff=readint();
System.out.print("Input b: ");
int bcoeff=readint();
System.out.print("Input c: ");
int ccoeff=readint();
//Now we have the coefficients, create a new Quadratic instance
that represents them
//Now we solve the quadratic
System.out.println("Solving the equation: "+acoeff+"*x^2 +
"+bcoeff+"*x + "+ccoeff+" = 0");
double[]roots=solve(acoeff, bcoeff, ccoeff);
//We have solved the equation, and now we print the results
if (roots==null)
System.out.println("All x are solutions");
else if (roots.length==0)
System.out.println("No solutions");
else if (roots.length==1)
System.out.println("Solution is: x= "+roots[0]);
else if (roots.length==2)
System.out.println("Solutions are: X= "+roots[0]+" or X=
"+roots[1]);
}
}
/**This utility function just reads an integer from standard
input, and returns 0 if there is some error*/
static int readint(){
try{ // We just wrap everything in a big try/catch
//We use the "reader" variable, which should hold standard input
String line=reader.readLine() ;
//Get an int from the line read
return Integer.parseInt(line);
}
catch(Exception e){
//Some error occurred, probably NumberFormatException. We just
return 0 here.
return 0;
}
}
}
