我有一个非常简单的二次公式代码我前一段时间写过并回过头来。它运行正常,但它输出了我的最终其他声明,即使它不应该!
import javax.swing.JOptionPane;
public class quadFormGUI {
public void quadForm(){
String aNumI = JOptionPane.showInputDialog("What is your 'A' variable?");
String bNumI = JOptionPane.showInputDialog("What is your 'B' variable?");
String cNumI = JOptionPane.showInputDialog("What is your 'C' variable?");
double aNum = Double.parseDouble(aNumI);
double bNum = Double.parseDouble(bNumI);
double cNum = Double.parseDouble(cNumI);
double oneAns = (bNum * bNum) + (-aNum * cNum * 4);
if (oneAns < 0){
JOptionPane.showMessageDialog(null,"The equation does not have a solution", "Quadratic Formula" , JOptionPane.PLAIN_MESSAGE);
}else{
double twoAns = (double) Math.sqrt(oneAns);
double threeAns = -bNum + twoAns;
double xOne = threeAns/(2*aNum);
double fourAns = (bNum * bNum) + (-aNum * cNum * 4);
double fiveAns = (double) Math.sqrt(fourAns);
double sixAns = -bNum - fiveAns;
double xTwo = sixAns/(2*aNum);
JOptionPane.showMessageDialog(null,"X1 is " + xOne + " & X2 is " +xTwo, "Quadratic Formula" , JOptionPane.PLAIN_MESSAGE);
xOne = xOne * -1;
xTwo = xTwo * -1;
if (xOne < 0 && xTwo < 0){
JOptionPane.showMessageDialog(null,aNum +"(X " + xOne + ") (X " + xTwo + ")", "Quadratic Formula" , JOptionPane.PLAIN_MESSAGE);
}else if (xOne < 0 && xTwo > 0){
JOptionPane.showMessageDialog(null,aNum +"(X " + xOne + ") (X + " + xTwo + ")", "Quadratic Formula" , JOptionPane.PLAIN_MESSAGE);
}else if (xOne > 0 && xTwo < 0){
JOptionPane.showMessageDialog(null,aNum +"(X + " + xOne + ") (X " + xTwo + ")", "Quadratic Formula" , JOptionPane.PLAIN_MESSAGE);
}else if (xOne > 0 && xTwo > 0){
JOptionPane.showMessageDialog(null,aNum +"(X + " + xOne + ") (X + " + xTwo + ")", "Quadratic Formula" , JOptionPane.PLAIN_MESSAGE);
}else{
System.out.println("Wrong");
}
}
}
}
它总是输出&#34;错误&#34;无论如何!
答案 0 :(得分:0)
如果你看到&#34;错误&#34;在控制台上,你的程序流程将转到最后一个&#34; else&#34;部分。这意味着 xOne或xTwo或两者都为0 。 xOne或xTwo可以为零的唯一方法是为a和c输入0。还有另一种可能性,在你的JOptionPane showInputBox中,你输入一个值后没有按下Ok按钮;您可能按下取消按钮,在这种情况下,将返回空值并将其存储在您的字符串变量aNumI,bNumI和cNumI中。除了这2个案例,你的程序不能转到else部分。我在一个在线IDE中执行了你的程序,它没有进入其他部分。唯一的区别是我没有使用JOptionPane。
尝试在输入框关闭后立即打印或调试aNumI,bNumI和cNumI的值。我确信它们将为null或者为&#39; 0&#39;。让我知道你发现了什么。
答案 1 :(得分:0)
是的,对不起,我错了。现在回想一下,为什么我要检查X为0?无论如何,该程序工作正常,我只是总是输入A = 0,B = -3,C = 0.我修复它,它现在工作。