输入一个表达式,没有括号,数字小于0-9之间,输出计算结果,所有的中间结果化为整形。 例如: 输入:3+8×2/9-2 输出:2

输入一个表达式,没有括号,数字小于0-9之间,输出计算结果,所有的中间结果化为整形。

    例如:  输入:3+8×2/9-2  

             输出:2

菜鸟初试,还请大神指教。

import java.util.Stack;


public class Calequ {

public int getRet(String str){

char[] arr = str.toCharArray();
Stack<Character> stack1 = new Stack<Character>(); //存储数字
Stack<Character> stack2 = new Stack<Character>(); //存储+-符号

int temp = 0,temp1,temp2;
char tempstr;
for(int i=0;i<arr.length;i++){

switch(arr[i]){
case '×':
temp1 = (int)(stack1.pop())-48;   //ASCII转换
temp = temp1*((int)(arr[i+1])-48);
stack1.push((char)(temp+48));
i++;
break;
case '/':
temp1 = (int)(stack1.pop())-48;
temp = temp1/((int)(arr[i+1])-48);
stack1.push((char)(temp+48));
i++;
break;
case '+':
if(stack2.size()!=0){
temp2 = (int)(stack1.pop())-48;
temp1 = (int)(stack1.pop())-48;
tempstr = stack2.pop();
if(tempstr=='+'){
temp = temp1+temp2;
}else{
temp = temp1-temp2;
}

stack1.push((char)(temp+48));

}
stack2.push(arr[i]);
break;
case '-':
if(stack2.size()!=0){
temp2 = (int)(stack1.pop())-48;
temp1 = (int)(stack1.pop())-48;
tempstr = stack2.pop();
if(tempstr=='+'){
temp = temp1+temp2;
}else{
temp = temp1-temp2;
}
stack1.push((char)(temp+48));

}
stack2.push(arr[i]);
break;
default:
stack1.push(arr[i]);
}

}
tempstr = stack2.pop();
temp2 = (int)(stack1.pop())-48;
temp1 = (int)(stack1.pop())-48;
if(tempstr=='+'){
temp = temp1+temp2;
}else{
temp = temp1-temp2;
}


return temp;
}

public static void main(String[] args){
String str = "3+8×2/9-2";
Calequ cal = new Calequ();
int result = cal.getRet(str);
System.out.println(result);
}
}  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值