/**
* Finds the roots of a quadratic formula.
*/
public class RootFinder
{
public static void main(String[] args)
{
// declare and initialize the coefficiants of the formula to solve
// ((x+2)(x-2) here)
double a;
a = 1.0;
double b;
b = 0.0;
double c;
c = -4.0;
// compute the discriminant
double discriminant = b * b - 4 * a * c;
//compute the roots
double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
// display the results
System.out.println(root1 + " and " + root2);
}
}
import java.util.*;
/**
* Finds the roots of a quadratic formula.
*/
public class RootFinder2
{
public static void main(String[] args)
{
Scanner in;
in = new Scanner(System.in);
// declare and initialize the coefficiants of the formula to solve
// ((x+2)(x-2) here)
System.out.println("Enter the coefficient of the x^2 term:");
double a;
a = in.nextDouble();
System.out.println("Enter the coefficient of the x term:");
double b;
b = in.nextDouble();
System.out.println("Enter the coefficient of the constant term:");
double c;
c = in.nextDouble();
// compute the discriminant
double discriminant = b * b - 4 * a * c;
//compute the roots
double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
// display the results
System.out.println(root1 + " and " + root2);
}
}
This code can also be downloaded from the files
RootFinder.java,
and RootFinder2.java.