我正在尝试构建一个与 JButtons 一起用于数字和算术操作数的计算器。每次单击 JButton 时,都会更新一个字符串变量(textin)并作为不可编辑的 JTextField 的参数传递。JTextField 显示将作为计算参数传入的数字。单击操作数时,下一个数字应该重置 JTextField(即“678+”,当单击 4 时,JTextField 应该重置为“4”)。问题是它每次都会这样做,无论是否存在“+”。代码如下。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Gui extends JFrame {
private JButton but1;
private JButton but6;
private JButton plus;
private JButton equal;
private JTextField text;
public static String textin;
public double num1;
public double num2;
public String operand;
public Gui() {
super("Calculator");
setLayout(new FlowLayout());
textin = "";
num1 = 0;
num2 = 0;
but1 = new JButton("1");
but6 = new JButton("6");
plus = new JButton("+");
equal = new JButton("=");
operand = "";
text = new JTextField(20);
text.setEditable(false);
add(text);
add(but6);
add(but1);
add(equal);
add(plus);
but1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
textin += "1";
text.setText(textin);
}
});
but6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if(textin.length()!=0&&textin.substring(textin.length()-1)!="+"){
textin += "6";
text.setText(textin);
textin = "6";
text.setText(textin);
} else {
textin = "6";
text.setText(textin);
}
}
});
plus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
num2 = Double.parseDouble(textin);
num1 = num1 + num2;
textin += "+";
text.setText(textin);
operand = "+";
}
});
equal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if(tel == "+") {
num2 = Double.parseDouble(textin);
num1 = num1+num2;
JOptionPane.showMessageDialog(null,String.format("%f",num1));
} else {
JOptionPane.showMessageDialog(null,String.format("error"));
}
}
});
}
}
but1 是一个普通按钮,而 but6 是一个按钮,它应该只在 + 之后重置 JTextField。不幸的是,它每次都会重置它。为简单起见,我删除了其余代码。问题可能出在 but6 JButton 的 if 语句中。仅执行 else 中存在的内容。它实际上并不检查“+”是否存在。有人能解释一下为什么发生?