这是我初学Java时用Java编写的小型计算器,现在看来,确实有点幼稚,不过,毕竟是自己写的,放在这里,权作纪念吧,嘿嘿。
代码如下:
import java.awt.*;
import java.awt.event.*;
public class Calculator extends Frame
{
TextField text = new TextField(20);
Panel p=new Panel();
double num; //存放操作数
String op;
double result; //存放计算结果
int idx=0; //用于退格键
boolean flag=false;//用于追加数字还是重新显示
boolean dbClick=false;//是否连按"="号
public Calculator()
{
super("简易计算器");
String[] name ={"退格","CE","C","/","7","8","9","*","4","5","6","-",
"1","2","3","+","0","+/-",".","="};
Button[] button= new Button[name.length];
add(text,"North");
text.setFont(new Font("宋体",Font.BOLD,20));
text.setText("0.0");
text.setEditable(false);
text.setFocusable(false);
p.setLayout(new GridLayout(5,4,2,2));
for (int i=0;i<name.length;i++)
{
button[i]=new Button(name[i]);
if(i<=3||i==7||i==11||i==15||i==19)
{//设置按钮前景色
button[i].setForeground(Color.red);
}
else
{
button[i].setForeground(Color.blue);
}
button[i].setFont(new Font("宋体",Font.BOLD,15));
button[i].addActionListener(new MyActionListener());//添加监听器
p.add(button[i]);
}
add(p,"South");
setSize(250,200);
this.setLocation(300,300);
this.setResizable(false);//窗体不可改变大小
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
this.setVisible(true);
}
class MyActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String input=text.getText();
String str=e.getActionCommand();
if(isNum(str))
{
if(!flag)
{
if(input!=""&&!input.equals("0.0")&&!input.equals("0"))
{
text.setText(input+str);
}
else
{
text.setText(str);
}
}
else
{
text.setText(str);
}
flag=false;
}
else if(str.equals("+")||str.equals("-")||str.equals("*")||str.equals("/"))
{
result=Double.parseDouble(input);
op=str;
flag=true;
dbClick=false;
}
if(str.equals("="))
{
if(dbClick==false)
{
num=Double.parseDouble(input);
}
if(op.equals("+"))
{
result+=num;
}
if(op.equals("-"))
{
result-=num;
}
if(op.equals("*"))
{
result*=num;
}
if(op.equals("/"))
{
if(num!=0.0)
{
result/=num;
}
}
text.setText(""+result);
flag=false;
dbClick=true;
}
if(str.equals("CE"))
{
text.setText("0.0");
num=0;
}
if(str.equals(".")&&input.indexOf(".")<0)
{
text.setText(input+".");
}
if(str.equals("+/-"))
{
double m = Double.parseDouble(input);
if(m!=0.0)
{
text.setText(m*(-1)+"");
}
}
if(str.equals("C"))
{
text.setText("0.0");
flag=false;
dbClick=false;
result=0;
num=0;
}
if(str.equals("退格"))
{
idx=input.length()-1;
if(idx<0)
{
return;
}
text.setText(input.substring(0,idx));
}
}
}
public boolean isNum(String str)
{
if(str.equals("0")||str.equals("1")||str.equals("2")||str.equals("3")||str.equals("4")
||str.equals("5")||str.equals("6")||str.equals("7")||str.equals("8")||str.equals("9"))
{
return true;
}
else
{
return false;
}
}
public static void main(String[] args)
{
new Calculator();
}
}
posted on 2006-04-15 00:52
南一郎 阅读(956)
评论(1) 编辑 收藏