import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class test {
static String s1="",s2="";//第一个运算数和第二个运算数
static TextField tf=new TextField(30);
static boolean flag=false;//是否满足运算条件
static String op="";
public static void main(String[] args){
Frame f=new Frame("java计算器 by紫色");
Panel p1=new Panel();
Panel p2=new Panel();
p1.add(tf);
f.add(p1,BorderLayout.NORTH);
p2.setLayout(new GridLayout(3,5,4,4));//按钮布局
String[] name={"0","1","2","3","4","5","6","7","8","9",".","+","-","*","/","√","AC","="};//计算器按钮
for(int i=0;i<name.length;i++){
final Button b=new Button(name[i]);//添加按钮
p2.add(b);
if(i<11)//按下数字符号
{b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(!flag){//取第一个数值
s1+=b.getLabel();
tf.setText(s1);
}
else{//取第二个数值
s2+=b.getLabel();
tf.setText(s2);
}
}
});}
else if(i==name.length-2){//按下清除符号
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
s1="";s2="";
flag=false;
tf.setText("0");
}
});
}
else if(i==name.length-3){//按下根号
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
double d=Double.parseDouble(s1);
s1=String.valueOf(Math.sqrt(d));
tf.setText(s1);
}
});
}
else if(i==name.length-1){//按下等号
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(s2=="");
else{
flag=false;
double d1,d2;
d1=Double.parseDouble(s1);//将字符转换为数字类型计算,计算完后转换为字符型输出
d2=Double.parseDouble(s2);
s2="";//reset the s2
switch(op){//运算
case "+":s1=String.valueOf(d1+d2);//String.valueOf(d1+d2)将d1+d2的结果转换为字符
tf.setText(s1);
break;
case "-":s1=String.valueOf(d1-d2);
tf.setText(s1);
break;
case "*":s1=String.valueOf(d1*d2);
tf.setText(s1);
break;
case "/":if(d2==0)JOptionPane.showMessageDialog
(null, "除数不能为0,非法运算", "错误", JOptionPane.ERROR_MESSAGE);
else {
s1=String.valueOf(d1/d2);
tf.setText(s1);
break;
}
default:break;
}
}}
});
}
else{//按下运算符
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
op=b.getLabel();
flag=true;
}
});
}
}
f.add(p2);
f.pack();
f.setVisible(true);
}
}
|
|