2 编
import java.applet.Applet;
import java.awt.*;
public class Calc extends Applet{
private Button button0,button1,button2,button3,button4,button5,button6,button7,button8,button9,jia,jian,deng,cheng,chu,clear;
TextField show,result;
String s1="",s2,s4,s5,s6;
char s3,ch1;
double num1,num2,num3;
int s11_length,num4;
//*************初始化*****************
public void init()
{
show=new TextField(10);result=new TextField(10);button0=new Button("0"); button1=new Button("1");button2=new Button("2");
button3=new Button("3");button4=new Button("4");button5=new Button("5");button6=new Button("6");button7=new Button("7");
button8=new Button("8");button9=new Button("9");jia=new Button("+");jian=new Button("-");cheng=new Button("×");
chu=new Button("÷");deng=new Button("=");clear=new Button("清除");
add(show);
add(result);
setLayout(null);
add(button0);add(button1);add(button2);add(button3);add(button4);add(button5);add(button6);add(button7);add(button8);
add(button9);add(jia);add(jian);add(cheng);add(chu);add(deng);add(clear);
show.reshape(10,10,130,25);result.reshape(150,10,130,25);
button0.reshape(10,50,45,20);button1.reshape(65,50,45,20);button2.reshape(120,50,45,20);button3.reshape(175,50,45,20);
button4.reshape(10,90,45,20);button5.reshape(65,90,45,20);button6.reshape(120,90,45,20);button7.reshape(175,90,45,20);
button8.reshape(10,130,45,20);button9.reshape(65,130,45,20);jia.reshape(120,130,45,20);jian.reshape(175,130,45,20);
cheng.reshape(10,170,45,20);chu.reshape(65,170,45,20);deng.reshape(120,170,100,20);clear.reshape(230,130,55,60);
}
//************判断事件****************
public boolean action(Event e,Object o)
{
if(e.target instanceof Button)
{
s2=o.toString();
s3=s2.charAt(0);
switch(s3){
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
s1=s1.concat(s2);
show.setText(s1);
break;
case '+': case '-': case '×': case '÷':
s11_length=s1.length();
ch1=s3;
num1=zhuanhua(s1);
s1=s1.concat(s2);
show.setText(s1);
break;
case '=':
s5=s1.substring(s11_length+1);
num2=zhuanhua(s5);
switch(ch1)
{case '+':
num3=num1+num2; break;
case '-':
num3=num1-num2; break;
case '×':
num3=num1*num2;break;
case '÷':
num3=(double)num1/(double)num2; break;
}
num4=(int)num3;
s1=Integer.toString(num4);
result.setText(""+num3);
break;
case '清':
result.setText("");
show.setText("");
num3=0;
s1="";
break;
}
}
return true;
}
//********************字符串转化成数字****************
public int zhuanhua(String s)
{
int num=0,i,element;
char ch;
for(i=0;i<s.length();i++)
{
ch=s.charAt(i);
element=ch-'0';
num+=element*(Math.pow(10,s.length()-i-1));
}
return num;
}
}
温馨提示:内容为网友见解,仅供参考