为什么我的按钮不能执行正确的操作?
我使用GUI创建了一个“计算器”。但是当我使用我的输入按钮时,无论我按哪个操作员,它总是打印出两个数字的产品。为什么我的按钮不能执行正确的操作?
class Calculator extends JFrame implements ActionListener{
JTextfield firstN, secondN;
JButton addButton, subButton, divButton, mulButton, enter;
JLabel result;
Calculator(){
// here I initialized all the components and added buttons/ActionListeners
}
public void actionPerformed(ActionEvent e) {
int first = Integer.parseInt(firstN.getText());
int second = Integer.parseInt(secondN.getText());
int value = 0;
if(e.getSource() == addButton){
value = first + second;
}else if(e.getSource() == subButton){
value = first - second;
}else if(e.getSource() == divButton){
value = first/second;
}else{
value = first*second;
}
if(e.getSource() == enter)
result.setText(value + "");
}
没有输入按钮,计算器工作正常。我尝试了一个do-while循环,但结果是无限的..
我想我得到了错误的if/else语句,但其中一个前4个语句总是被执行,所以最后一个也应该工作尽我所知...
的value
变量不应该actionPerformed
方法内部声明。这样,每次单击按钮时都会重置。输入按钮也会重置它。你得到了两个数字的结果,因为它是第一个if语句的缺省分支。目前应该只有一个if语句,和值应该是一个一流水平场,而不是局部变量:
class Calculator extends JFrame implements ActionListener{
JTextfield firstN, secondN;
JButton addButton, subButton, divButton, mulButton, enter;
JLabel result;
int value;
Calculator(){
// here I initialized all the components and added buttons/ActionListeners
}
public void actionPerformed(ActionEvent e) {
int first = Integer.parseInt(firstN.getText());
int second = Integer.parseInt(secondN.getText());
if(e.getSource() == addButton){
value = first + second;
}else if(e.getSource() == subButton){
value = first - second;
}else if(e.getSource() == divButton){
value = first/second;
}else if (e.getSource() == mulButton){
value = first*second;
}else if(e.getSource() == enter)
result.setText(value + "");
}
}
它因为你的else子句将被调用时(e.getSource()==输入),因为if和else if语句将为false。你可以把它更像是这样的:
if(e.getSource() == addButton){
value = first + second;
}else if(e.getSource() == subButton){
value = first - second;
}else if(e.getSource() == divButton){
value = first/second;
}else if(e.getSource() == mulButton){
value = first*second;
}else if(e.getSource() == enter)
result.setText(value + "");
}
这个解决方案的进入将设置结果为零 –
我同意这一点,我真的不关心他是如何实现他的价值计算作为问题意味着产品在输入被按下时总是被计算。 – LanfeaR
自从上次else块{值=第一*第二; }没有if条件,它不仅会在执行e.getSource == mulButton时执行,还会在e.getSource ==输入时执行。
一个解决办法是使用此代码替换最后一个else语句:
} else if(e.getSource == mulButton) {
value = first*second;
}
完美运作!快速偏离主题:为什么每次单击按钮时都会重置“值”?为什么变量应该是一个类级别的字段? –
@ marie.ellaZ发生这种情况是因为每次单击按钮时,actionPerformed()方法都会从乞讨执行到结束。所以如果它包含'int value = 0'这一行,每次点击都会将它设置为零。如果您想保留点击次数之间的值,则必须将其存储在此方法之外的某个位置,并且类级别字段对此非常明显。 –