计算器 五个键的计算器
五个键的计算器代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class calculator1 implements ActionListener
{
static JFrame f11=new JFrame("计算器");
JPanel p1=new JPanel();
static JTextArea t1=new JTextArea(3,5);
JButton a=new JButton("1");
JButton b=new JButton("2");
JButton c=new JButton("3");
JButton d=new JButton("+");
JButton e=new JButton("=");
String x="",zz="",z="";
double cc=0.0,ss=0.0,xx=0.0,aa=0.0;
void calculator11()
{
f11.setLayout(new BorderLayout(5,5));
p1.setLayout(new GridLayout(1,5,5,5));
p1.add(a);
p1.add(b);
p1.add(c);
p1.add(d);
p1.add(e);
f11.add(t1,"North");
f11.add(p1,"Center");
a.addActionListener(this);
b.addActionListener(this);
c.addActionListener(this);
d.addActionListener(this);
e.addActionListener(this);
f11.setSize(300,150);
p1.setSize(300,100);
f11.setVisible(true);
p1.setVisible(true);
t1.setVisible(true);
}
public void actionPerformed(ActionEvent e11) //实现接口函数
{
if(e11.getActionCommand().equals("1"))
{
x=x+"1";
t1.setText(zz+x);
}
if(e11.getActionCommand().equals("2"))
{
x=x+"2";
t1.setText(zz+x);
}
if(e11.getActionCommand().equals("3"))
{
x=x+"3";
t1.setText(zz+x);
}
if(e11.getActionCommand().equals("+"))
{
if(x==""||zz+x=="")
t1.setText("请先输入第一个加数~");
else
{
ss=Double.parseDouble(x);
aa=aa+ss;
zz=zz+x+"+";
t1.setText(zz);
x="";
z="+";
}
}
if(e11.getActionCommand().equals("="))
{
if(z.equals(""))
{
t1.setText(x+"="+"\n"+x);
}
else
{
xx=Double.parseDouble(x);
cc=aa+xx;
t1.setText(zz+x+'\n'+'='+Double.toString(cc));
}
x="";
zz="";
z="";
aa=0;
}
}
}
public class calculator2
{
public static void main(String args[])
{
calculator1 cc=new calculator1();
cc.calculator11();
}
}
运行结果: