程序代吗运行结果如图所示:我运行了,完全正确,老师也讲过了.说明我写的很清楚.希望你们能看得懂.
import java.awt.*;
import java.awt.event.*;
public class Calculator2 extends Frame implements ActionListener{
private double result=0,data1=0,pointDepth=1;
private boolean ifPoint=false,ifResult=false;//设小数点初始值为假,最终结果的初始值为假。
private char oper='+';
private Frame f;
private TextField tf;
private Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16;
private Panel p;
Calculator2(String title)
{
super(title);
p=new Panel();
p.setLayout(new GridLayout(4,4));
tf=new TextField(30);
String[] names={"7","8","9","+","4","5","6","-","1","2","3","*","0",".","=","/"};
Button[] buttons=new Button[16];
for(int i=0;i<buttons.length;i++)
{
buttons[i]=new Button(names[i]);
buttons[i].addActionListener(this);
p.add(buttons[i]);
}
this.add(tf,"North");
this.add(p,"Center");
this.addWindowListener(new WindowAdapter()//是个内部类,作用为关闭窗口
{
public void windowClosing(WindowEvent evt)
{System.exit(0);}
});
this.setSize(300,200);
this.setVisible(true);
this.pack();
}
public static void main(String args[]){
new Calculator2("大功告成,哈哈");
}
public void actionPerformed(ActionEvent e){
String s;
s=e.getActionCommand(); //事件(也就是各个按钮)的显示赋给s
switch(s.charAt(0)){ //返回s的第一个字符,返回类型为字符型
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
if(ifResult){ //当ifresult为真时 清空result和data1,oper置+
result=0;
data1=0;
oper='+';
}
Integer Int1=new Integer(s); //s赋给Int1
if(ifPoint){ //当ifpoint时,转换为相应的小数
pointDepth=pointDepth/10;
data1=data1+(Int1.intValue())*pointDepth;
}
else{ //整数部分的处理
data1=data1*10+(Int1.intValue());
}
Double displayNumber=new Double(data1); //显示data1
tf.setText(displayNumber.toString());
ifResult=false; //ifresult置为假
System.out.println("pressed:"+s+" result:"+result+" data1:"+data1+" oper:"+oper+" ifresult:"+ifResult);
break;
case '+': case '-':case '*':case '/':case '=': //可能连续运算,所以加、减、乘、除和=都在此编写
if(s.charAt(0)!='='&&ifResult){ //按下加、减、乘、除号且前面为计算结果,则不做运算
oper=s.charAt(0);
ifResult=false; //把结果标志位设为假
System.out.println("case 1");
}
else{ //按下加、减、乘、除、=号
switch(oper){ //根据前一次输入的加、减、乘、除号做运算
case '+':
result=result+data1;
break;
case '-':
result=result-data1;
break;
case '*':
result=result*data1;
break;
case '/':
result=result/data1;
break;
}
System.out.println("case 2");
}
if(s.charAt(0)!='='){ //data1置0,置操作符,等待输入data1
data1=0;
oper=s.charAt(0);
}
else{ //按的是等号,置ifresult为真
ifResult=true;
}
ifPoint=false;
pointDepth=1;
displayNumber=new Double(result); //直接按加、减、乘、除显示result的值,为0
tf.setText(displayNumber.toString());
System.out.println("pressed:"+s+"result:"+result+" data1:"+data1+" oper:"+oper+" ifresult:"+ifResult);
break;
case '.':
ifPoint=true; //按下 . 时,是否小数为真
System.out.println("pressed:"+s+"result:"+result+" data1:"+data1+" oper:"+oper+" ifresult:"+ifResult);
break;
}
}
public void windowClosing(WindowEvent e){
System.exit(0);
}
}