永发信息网

java简单计算器的程序

答案:2  悬赏:30  手机版
解决时间 2021-04-23 01:27
  • 提问者网友:抽煙菂渘情少年
  • 2021-04-22 06:09

‘+’的结果错了,别的没错,不知道什么问题。

class SimpleCal2 {
private int operand1,operand2;
private char operator;

SimpleCal2(){}

SimpleCal2(int operand1,char operator,int operand2){
this.operand1=operand1;

this.operator=operator;
this.operand2=operand2;
}

private int cal() throws ArithmeticException,Exception{
int result=Integer.MIN_VALUE;
if(operator=='+')
result=operand1+operand2;
else if(operator=='-'){
result=operand1-operand2;
}
else if(operator=='*'){
result=operand1*operand2;
}
else if(operator=='/'){
result=operand1/operand2;
}
else {
throw new Exception("输入的运算符错误!");
}
return result;
}

public void showResult() throws ArithmeticException,Exception{
System.out.println("运算结果:"+operand1+operator+operand2+"="+cal());
}

public static void main(String[] args){
int p1,p2;
try{
p1=Integer.parseInt(args[0]);
char op=args[1].charAt(0);
p2=Integer.parseInt(args[2]);
SimpleCal2 exp=new SimpleCal2(p1,op,p2);
exp.showResult();
}
catch(NumberFormatException e1){
System.out.println("输入的运算数不是整数!");
}
catch(ArrayIndexOutOfBoundsException e2){
System.out.println("输入的运算式不完整!");
}
catch(ArithmeticException e3){
System.out.println("除数为0,不能进行除法运算!");
}
catch(Exception e4){
e4.printStackTrace();
}
}
}

最佳答案
  • 五星知识达人网友:舍身薄凉客
  • 2021-04-22 07:28

我做了测试你的程序没有问题.


class SimpleCal2 {
private int operand1, operand2;
private char operator;


SimpleCal2() {
}


SimpleCal2(int operand1, char operator, int operand2) {
this.operand1 = operand1;


this.operator = operator;
this.operand2 = operand2;
}


private int cal() throws ArithmeticException, Exception {
int result = Integer.MIN_VALUE;
if (operator == '+')
result = operand1 + operand2;
else if (operator == '-') {
result = operand1 - operand2;
} else if (operator == '*') {
result = operand1 * operand2;
} else if (operator == '/') {
result = operand1 / operand2;
} else {
throw new Exception("输入的运算符错误!");
}
return result;
}


public void showResult() throws ArithmeticException, Exception {
System.out.println("运算结果:" + operand1 + operator + operand2 + "="
+ cal());
}


public static void main(String[] args) {
int p1, p2;char op;
try {
//p1 = Integer.parseInt(args[0]);
p1=3;
//char op = args[1].charAt(0);
op='+';
//p2 = Integer.parseInt(args[2]);
p2=2;
SimpleCal2 exp = new SimpleCal2(p1, op, p2);
exp.showResult();
} catch (NumberFormatException e1) {
System.out.println("输入的运算数不是整数!");
} catch (ArrayIndexOutOfBoundsException e2) {
System.out.println("输入的运算式不完整!");
} catch (ArithmeticException e3) {
System.out.println("除数为0,不能进行除法运算!");
} catch (Exception e4) {
e4.printStackTrace();
}
}
}


运算结果:3+2=5


你的程序没有错.

全部回答
  • 1楼网友:老鼠爱大米
  • 2021-04-22 08:27

错误时什么?计算结果错了,还是输出的信息有误

我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯