## Thursday, 1 September 2016

### Chapter 9 Exercise 10, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

Design a class named QuadraticEquation for a quadratic equation ax2 + bx + x = 0.

The class contains:
■ Private data fields a, b, and c that represent three coefficients.
■ A constructor for the arguments for a, b, and c.
■ Three getter methods for a, b, and c.
■ A method named getDiscriminant() that returns the discriminant
■ The methods named getRoot1() and getRoot2() for returning two roots of the equation
These methods are useful only if the discriminant is non-negative. Let these methods return 0 if the discriminant is negative.
Draw the UML diagram for the class and then implement the class.
Write a test program that prompts the user to enter values for a, b, and c and displays
the result based on the discriminant. If the discriminant is positive, display the two roots.
If the discriminant is 0, display the one root. Otherwise, display “The equation has no roots.”
See Programming Exercise 3.1 for sample runs.

public class QuadraticEquation {

private double a;
private double b;
private double c;

public QuadraticEquation(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}

public double getA() {
return a;
}

public void setA(double a) {
this.a = a;
}

public double getB() {
return b;
}

public void setB(double b) {
this.b = b;
}

public double getC() {
return c;
}

public void setC(double c) {
this.c = c;
}

public double getDiscriminant() {
return b * b - 4.0 * a * c;
}

public double getRoot1() {
return  (-b + Math.pow(getDiscriminant(), 0.5)) / (2.0 * a);
}

public double getRoot2() {
return  (-b - Math.pow(getDiscriminant(), 0.5)) / (2.0 * a);
}

}


import java.util.Scanner;

public class Exercise_10 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);
System.out.print("Enter a, b, c: ");
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();

double discriminant = equation.getDiscriminant();

if (discriminant > 0) {
System.out.println("The roots are " + equation.getRoot1()
+ " and " + equation.getRoot2());
} else if (discriminant == 0) {
System.out.println("The root is " + equation.getRoot1());
} else {
System.out.println("The equation has no roots");

}
}

}