Chapter 9 Exercise 10, Introduction to Java Programming , Tenth Edition Y. Danie
ID: 3841249 • Letter: C
Question
Chapter 9 Exercise 10, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY. Please include some comments in your source code.
*9.10 (Algebra: quadratic equations)
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.
Explanation / Answer
import java.util.Scanner;
public class QuadraticEquation
{
public QuadraticEquation(int x, int y, int z)
{
a = x;
b = y;
c = z;
}
public int getA()
{
return a;
}
public int getB()
{
return b;
}
public int getC()
{
return c;
}
public double getDiscriminant()
{
return (b*b) - (4*a*c);
}
public float getRoot1()
{
double descriminant = getDiscriminant();
//return 0, if descriminant < 0
if (descriminant < 0)
return 0;
double root1 = (Math.sqrt(getDiscriminant) - double(b)) / double(2*a);
return root1;
}
public float getRoot2()
{
double descriminant = getDiscriminant();
//return 0, if descriminant < 0
if (descriminant < 0)
return 0;
double root2 = ((-1 * Math.sqrt(getDiscriminant) - double(b)) / double(2*a);
return root2;
}
private int a, b, c;
}
class TestApp
{
public static void main(String[] args)
{
System.out.println("Please enter a :");
String s = scan.next();
int a = scan.nextInt();
System.out.println("Please enter b :");
String s = scan.next();
int b = scan.nextInt();
System.out.println("Please enter c :");
String s = scan.next();
int c = scan.nextInt();
QuadraticEquation equation = new QuadraticEquation(a, b , c);
double discriminant = equation.getDiscriminant();
if (discriminant < 0)
{
System.out.println("The equation has no roots");
}
else if (discriminant == 0)
{
float root1 = equation.getRoot1();
System.out.println("only root is " + Float.toString(root1));
}
else
{
float root1 = equation.getRoot1();
float root2 = equation.getRoot2();
System.out.println("root1 is " + Float.toString(root1) + "root2 is " + Float.toString(root2));
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.