输入一个表达式,没有括号,数字小于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);
}
}