Solve a quadratic equation in java using the dialog box. This is my code but the
ID: 3822962 • Letter: S
Question
Solve a quadratic equation in java using the dialog box. This is my code but there are a couple of errors, can you tell me what I am doing wrong.
import javax.swing.JOptionPane;
public class {
public static void main(String[] args) {
double a = Integer.parseInt(JOptionPane.showInputDialog("Please enter value for a "));
double b = Integer.parseInt(JOptionPane.showInputDialog("Please enter value for b "));
double c = Integer.parseInt(JOptionPane.showInputDialog("Please enter value for c "));
double D;
double x1;
double x2;
double x;
String ans1, ans2, ans3, ans4, ans5, ans6, ans7, ans8, ans9;
ans1 = ("All Solutions");
ans2 = ("No Solutions");
ans3 = ("One Solution");
ans4 = ("x = "+x);
ans5 = ("No Solution");
ans6 = ("duplicate Solution");
ans7 = ("x = "+x);
ans8 = ("x1 = "+x1);
ans9 = ("x2 = "+x2);
if (a==0)
if (b==0)
if (c==0)
JOptionPane.showMessageDialog(null, ans1);
else
JOptionPane.showMessageDialog(null, ans2);
else {
JOptionPane.showMessageDialog(null, ans3);
x = -c/b;
JOptionPane.showMessageDialog(null, ans4);
}
else {
D = b*b - 4*a*c;
if (D<0)
JOptionPane.showMessageDialog(null, ans5);
else if (D==0){
JOptionPane.showMessageDialog(null, ans6);
x = -b/2*a;
JOptionPane.showMessageDialog(null, ans7);
}
else {
x1 = (-b + Math.sqrt(D))/2*a;
x2 = (-b - Math.sqrt(D))/2*a;
JOptionPane.showMessageDialog(null, ans8);
JOptionPane.showMessageDialog(null, ans9);
}
}
}
}
Explanation / Answer
String ans1, ans2, ans3, ans4, ans5, ans6, ans7, ans8, ans9;
ans1 = ("All Solutions");
ans2 = ("No Solutions");
ans3 = ("One Solution");
ans4 = ("x = "+x);
ans5 = ("No Solution");
ans6 = ("duplicate Solution");
ans7 = ("x = "+x);
ans8 = ("x1 = "+x1);
ans9 = ("x2 = "+x2);
Here the variables ans4, ans7, ans8 and ans9 are assigned with double values, actually there are declared as string variables. So, it shows an error.
ans4, ans7, ans8 and ans9 declared as double.
In the following line there is no need of brackets
ans1 = ("All Solutions"); it is modified as ans1 = " All Solutions";
ans2 = ("No Solutions"); ans2 = "No Solutions";
ans3 = ("One Solution"); ans3 ="One Solution";
Change the above modifications and we will get the output.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.