need help on this, please with comments thanks Creating a Class This exercise is
ID: 3561214 • Letter: N
Question
need help on this, please with comments
thanks
Creating a Class
This exercise is based on Programming Exercise 8.10 on page 298 of the text. This problem asks you to create a class that represents a quadratic equation and provides methods giving the solutions. The text version of the question has the relevant formulas, or you can look them up online.
Create a Java class named QuadraticEquation that has the following features:
If the equation has no real roots, the methods getRoot0 and getRoot1 should just return the value NaN. If you check the documentation of the squareroot method, you will find that this is easy to do.
QuadraticEquation.zip is a project with a test program for your work. Use the existing QuadraticEquation.javafile for your code.
Explanation / Answer
public class QuadraTest {
public static void main(String[] args) {
QuadraticEquation qe = new QuadraticEquation((double)1,(double)-3,(double)2);
System.out.println(" Discriminator : "+qe.getDiscriminant());
System.out.println("Root1: " + qe.getRoot0());
System.out.println("Root2: " + qe.getRoot1());
}
}
public class QuadraticEquation {
private double a=0,b=0,c=0;
private String root0="" , root1="";
public QuadraticEquation(double a,double b,double c) {
this.a = a;
this.b = b;
this.c = c;
}
public double getDiscriminant() {
// Solve the discriminant (SQRT (b^2 - 4ac)
return Math.sqrt((b * b) - (4 * a * c));
}
//We can change this method to return double, to indicat NaN converted to string
public String getRoot0() {
calculateRoots();
return this.root0;
}
//We can change this method to return double, to indicat NaN converted to string
public String getRoot1() {
calculateRoots();
return this.root1;
}
private void calculateRoots() {
double discr = Math.sqrt((b * b) - (4 * a * c));
if(discr > 0)
{
//Equation has 2 roots"
root0 = Double.toString((-b + discr)/2 * a);
root1 = Double.toString((-b - discr)/2 * a);
}
if(discr == 0)
{
//Equation has 1 root
root0 = Double.toString((-b + discr)/2 * a);
root1 = root0;
}
if(discr < 0) {
root0 = "NaN";
root1 = "NaN";
}
}
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;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.