两个文本字段的数学计算

时间:2013-04-27 16:51:46

标签: java

我有3个测试字段用于输入和计算结果。数学运算的4个按钮和每个按钮的动作监听器。我有一个if语句来检查我正在按哪个按钮但它不起作用,只有分隔才有效。

aa.java

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;


 public class aa extends Applet implements ActionListener
{
int c;


TextField text1,text2,text3;

Button button1,button2,button3,button4;
public void init()
{

text1 = new TextField(20);
add(text1);


text2 = new TextField(20);
add(text2);


text3 = new TextField(20);
add(text3);

button1 = new Button("add");
add(button1);
button1.addActionListener(this);

button2 = new Button("sub");
add(button2);
button2.addActionListener(this);

button3 = new Button("multiply");
add(button3);
button3.addActionListener(this);

button4 = new Button("divide");
add(button4);
button4.addActionListener(this);

}
public void actionPerformed(ActionEvent e)
{
String str=e.getActionCommand();
int a=Integer.parseInt(text1.getText());
int b=Integer.parseInt(text2.getText());
if(str.equals("button1"))
{
c=a+b;
text3.setText(""+c);
}
else if(str.equals("button2"))
{
c=a+b;
text3.setText(""+c);
}
else if(str.equals("button3"))
{
c=a*b;
text3.setText(""+c);
}
else
{
c=a/b;
text3.setText(""+c);
}
}
}

aa.html

<HTML>
<BODY>
<APPLET ALIGN="CENTER" CODE="aa.java" width = "500" height = "500"></APPLET>
</BODY>
</HTML>

1 个答案:

答案 0 :(得分:2)

actionPerformed方法中,您需要检查按钮的actionCommand(默认情况下是构造它的文本),而不是其名称("multiply"而不是{{1} })。您可以使用setActionCommand更改按钮的操作命令。

有关详细信息,请参阅this page