java程序,要求做一个简单的计算器,请高手帮忙,能不能把帮我改下,实在不行就给个能实现加减乘除的,谢

2024-11-23 17:20:23
推荐回答(2个)
回答1:

public class Calculator{
private String result = "0";
private int op = 0,add = 1,sub = 2,mul = 3,div = 4;

private double stringToDouble(String x){
double y = Double.parseDouble(x);
return y;
}
private void operate(String x){
double x1 = stringToDouble(x);
double y = stringToDouble(result);
switch (op){
case 0:
result = x;
break;
case 1:
result = String.valueOf(y+x1);
break;
case 2:
result = String.valueOf(y-x1);
break;
case 3:
result = String.valueOf(y*x1);
break;
case 4:
if(x1!=0){
result = String.valueOf(y/x1);
}else{
result = "The divisor can't be zero!";
}
break;
}
}

public String opAdd(String x){
operate(x);
op = add;
return result;
}
public String opSubtract(String x){
operate(x);
op = sub;
return result;
}
public String opMultiply(String x){
operate(x);
op = mul;
return result;
}
public String opDivide(String x){
operate(x);
op = div;
return result;
}
public String opEquals(String x){
operate(x);
op = 0;
return result;
}
public void opClean(){
op = 0;
result = "0";
}
}

回答2:

http://hi.baidu.com/shy2850/blog/item/8967dd62de14576d0c33fac9.html

貌似我以前的练习题也可以吧!