我使用JFrame制作了一个带有java的计算器,除了除法之外,一切都有效。 以下是计算答案并显示答案的代码:
public void actionPerformed(ActionEvent e) {
try {
num1 = Double.parseDouble(resultl.getText());
num2 = Double.parseDouble(resultl.getText());
if (oper.equals("+")) {
answer = num1 + num2;
resultm.setText("" + answer);
resultl.setText("");
resultr.setText("");
oper = "";
currentNuml = "";
currentNumr = "";
} else if (oper.equals("-")) {
answer = num1 - num2;
resultm.setText("" + answer);
resultl.setText("");
resultr.setText("");
oper = "";
currentNuml = "";
currentNumr = "";
} else if (oper.equals("*")) {
answer = num1 * num2;
resultm.setText("" + answer);
resultl.setText("");
resultr.setText("");
oper = "";
currentNuml = "";
currentNumr = "";
} else if (oper.equals("/")) {
answer = num1 / num2;
resultm.setText("" + answer);
resultl.setText("");
resultr.setText("");
oper = "";
currentNuml = "";
currentNumr = "";
}
} catch (NumberFormatException ex) {
resultl.setText("Unexpected Error, try again.");
}
}
我粘贴了整个产生比较答案的东西,但真正的分区是问题所在。如果我做任何与分裂有关的事情,它总是只说答案是1.0 - 任何帮助将不胜感激。
答案 0 :(得分:4)
您正在为JTextField
的同一num2
阅读,因此值将相同。任何double
除以它将产生1.0
。
num2 = Double.parseDouble(resultl.getText());
你可能想要:
num2 = Double.parseDouble(result2.getText());
答案 1 :(得分:3)
num1 = Double.parseDouble(resultl.getText());
num2 = Double.parseDouble(resultl.getText());
num1和num2是相同的值=>分裂提供1.0