Solution
Simple yet powerful solution
Size 1.7 kB - File type text/javaFile contents
import java.util.Scanner;
public class Quadratic
{
//-----------------------------------------------------------------
// Determines the roots of a quadratic equation.
//-----------------------------------------------------------------
public static void main (String[] args)
{
int a, b, c; // ax^2 + bx + c
double discriminant, root1, root2;
boolean restart;
Scanner scan = new Scanner (System.in);
do {
System.out.print ("Enter the coefficient of x squared: ");
a = scan.nextInt();
System.out.print ("Enter the coefficient of x: ");
b = scan.nextInt();
System.out.print ("Enter the constant: ");
c = scan.nextInt();
try {
// Use the quadratic formula to compute the roots.
// Assumes a positive discriminant.
if (a == 0){
throw new IllegalArgumentException("a can't be zero");
}//end of if
else {
discriminant = Math.pow(b, 2) - (4 * a * c);
if (discriminant < 0)
throw new IllegalArgumentException("Discrimant < zero");
root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a);
root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a);
System.out.println ("Root #1: " + root1);
System.out.println ("Root #2: " + root2);
}//end of else
}//end of try
catch (IllegalArgumentException e){
System.out.println("No solution");
System.out.println(e.getMessage());
}
System.out.println();
System.out.println("True to continue and False to exit");
restart = scan.nextBoolean();
} while(restart);
} //end of main
} //end of class