从网上看到过很多计算器编写的方法,但是万变不离其宗,基本上大致的思路如下:
1、定义2个数,用来储存第一个按下的数和第二个按下的数(当然定义一个也行)
2、定义一个字符,用来储存运算符号
3、显示第一个按下的数
4、储存运算符,不显示或显示
5、显示第二个按下的数
6、“=”作为计算
新手代码片段:
double firNum=-1,secNum=0; //分别储存第一个按下的数和第二个按下的数
char c; //储存运算符号
Button num1=(Button)findViewById(R.id.num1);
num1.setOnClickListener(
new View.OnClickListener() {
EditText editText=(EditText)findViewById(R.id.editText);
@Override
public void onClick(View v)
{
editText.setText(editText.getText()+"1");
}
}
);
Button divide=(Button)findViewById(R.id.divide);
divide.setOnClickListener(
new View.OnClickListener() {
EditText editText=(EditText)findViewById(R.id.editText);
@Override
public void onClick(View v)
{
c='/';
firNum=Double.parseDouble(editText.getText().toString());
editText.setText("");
}
}
);
Button equal=(Button)findViewById(R.id.equal);
equal.setOnClickListener(
new View.OnClickListener() {
EditText editText=(EditText)findViewById(R.id.editText);
@Override
public void onClick(View v)
{
double result=0;
secNum=Double.parseDouble(editText.getText().toString());
switch (c)
{
case '+':result=firNum+secNum; editText.setText(result+""); break;
case '-':result=firNum-secNum; editText.setText(result+""); break;
case '*':result=firNum*secNum; editText.setText(result+""); break;
case '/':
if(secNum==0){
Toast.makeText(null, "除数不能为零!", c).show();
editText.setText("");
}else{
result=firNum/secNum;
editText.setText(result+"");
};
break;
}
}
}
网上有很多例子,有的通过把0-9个数字作为一个数组,运算符作为另一个数组处理,也有的通过switch去实现,我们可以去尝试下