Using GUI (Java), write the program that implements the algorithm for computing
ID: 3621615 • Letter: U
Question
Using GUI (Java), write the program that implements the algorithm for computing the roots of a quadratic equation. The user is prompted to enter the coefficients a, b, c as floating-point numbers, where a does not equal to 0. The program should be implemented as follows:
1. Name the class as "QuadraticEquation"
2.The main method should be used only to get the coefficient values, to echo (display) the coefficient values, check if coefficient a = 0, if so, displays: "Sorry! Coefficient a cannot be zero." then the program should exit, to call methods ("discriminant" and "checkDiscriminant") and to display the result.
3. Use a method called "discriminant" to compute the discriminant.
4. use a method called "checkDiscriminant" that distinguishes the different types of roots for the equation
Case1: if the discriminant < 0, the program displays: " The discriminant is negative. Equation has only complex roots.
Case2: if the discriminant = 0, the program calculates the root then displays: "The discriminant is zero. Equation has two equal roots x = root1"
Case3: if the discriminant > 0, the program calculates the roots then displays: "The discriminant is non-zero and positive. Equation has two distinct roots x1=root1 and x2=root2"
Note that root1 and root2 has to be calculated before the values are displayed.
No computation should take place if a=0. The program should display "Sorry! Coefficient a cannot be zero." and exits
Explanation / Answer
Dear,
Here is the code
import javax.swing.JOptionPane;
public class QuadraticRoots
{
public static void main(String args[])
{
int a,b,c;
//obtain first number from user
String firstnumber = JOptionPane.showInputDialog("Enter coefficient a");
a=Integer.parseInt(firstnumber);
//obtain second number from user
String secondnumber = JOptionPane.showInputDialog("Enter coefficient b");
b=Integer.parseInt(secondnumber);
//obtain third number from user
String thirdnumber = JOptionPane.showInputDialog("Enter coefficient c ");
c=Integer.parseInt(thirdnumber);
//function call to calcuate roots
discriminant(a,b,c);
//exit program
System.exit(0);
}
public static void discriminant(int a ,int b,int c)
{
int d=((b*b)-(4*a*c));
checkDiscriminant(d,a,b,c);
}
public static void checkDiscriminant(int d,int a ,int b, int c)
{
if(d==0)
JOptionPane.showMessageDialog(null,"The discreminant is zero Equation has two equal Roots x"+-(b/(2*a)));
else if((d)>0)
{
double root1= (-b + Math.sqrt(d)) / (2*a);
double root2= (-b + Math.sqrt(d)) / (2*a);
JOptionPane.showMessageDialog(null,"The discreminant is greater than zero Root1 ="+root1+"Root2 ="+root2);
}
else
JOptionPane.showMessageDialog(null,"Roots are complex");
}
}
Hope this will help you
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.