所以我开始研究用Java创建GUI的基础知识。我首先创建了一个基本的数学程序,它将解决Quadratic,其中输入通过Option Pane进行定向。但是,我注意到,只要没有想象的解决方案,程序就会给我解决方案。 这是代码:
package window.math;
import javax.swing.JOptionPane;
public class WindowMath {
public static void Solve(double a, double b, double c){ //Gives the input of A, B, C to the formula
double x;
x = Math.pow(b,2) - 4 * a * c; //Determines whether solution will have imaginary numbers or not
if (x >= 0){ //Real Solution output
double y;
double z;
double j;
double k;
double l;
y = -b + Math.sqrt(x);
z = -b - Math.sqrt(x);
j= 2 * a;
k = y / j;
l = z / j;
JOptionPane.showMessageDialog(null, "The solutions are x = " + k + " and x = " + l + ".", "Quadratic Solver", JOptionPane.PLAIN_MESSAGE);
} else { //Imaginary Solution Output
double j;
double v;
double w;
double y;
double z;
y = Math.abs(x);
w = Math.sqrt(y);
j = 2 * a;
v = w / j;
z = -b / j;
JOptionPane.showMessageDialog(null, "The solutions are x = " + z + " + " + v + "i and x = " + z + " - " + v + "i.", "Quadratic Solver", JOptionPane.PLAIN_MESSAGE);
}
}
public static void main(String[] args) {
String a = JOptionPane.showInputDialog("Enter a:");
String b = JOptionPane.showInputDialog("Enter b:");
String c = JOptionPane.showInputDialog("Enter c:");
double num1 = Double.parseDouble(a);
double num2 = Double.parseDouble(b);
double num3 = Double.parseDouble(b);
Solve(num1,num2,num3);
}
}
当我运行三个数字给出解决方案的虚数时,程序运行正常。但是,对于类似a = 1,b = 2和c = 1的问题,解决方案应该是x = -1,x = -1。只有真正的解决方相反,输出给我“x = -1.0 + 1.0i,x = -1.0 - 1.0i。我目前正在NetBeans IDE 8.2(Build 201609300101)中编码,并使用Java更新1.8.0_144和JavaVM 25.144-b01。帮助将不胜感激。
答案 0 :(得分:2)
代码中的问题位于以下行(来自main
方法):
double num3 = Double.parseDouble (b);
应该是:
double num3 = Double.parseDouble (c);