图例
代码
package com.Calculator;
import java.util.Stack;
public class Calculator {
public static void main(String[] args) {
String expression = "30+2*6-2";
Stack<Integer> numStack = new Stack<>();
Stack<Character> operStack = new Stack<>();
Calculator cal = new Calculator();
int index = 0 ,a=0,b=0;
char oper ;
String keepNum = "";
while(true){
char c = expression.charAt(index);
if(cal.isOper(c)){
if(!operStack.isEmpty()){
if(cal.priority(c)<=cal.priority(operStack.peek())){
a=numStack.pop();
b=numStack.pop();
oper=operStack.pop();
int res = cal.cal(a, b, oper);
numStack.push(res);
operStack.push(c);
}else{
operStack.push(c);
}
}else{
operStack.push(c);
}
}else{
keepNum+=c;
if(index == expression.length()-1 || cal.isOper(expression.charAt(index+1))){
numStack.push(Integer.parseInt(keepNum));
keepNum="";
}
}
index++;
if(index>=expression.length())
break;
}
while(true){
if(!operStack.isEmpty()){
a=numStack.pop();
b=numStack.pop();
oper = operStack.pop();
int res = cal.cal(a, b, oper);
numStack.push(res);
}else {
break;
}
}
System.out.println(numStack.peek());
}
public int priority(char oper){
if(oper=='*'||oper=='/')
return 1;
else if(oper=='+'||oper=='-')
return 0;
else
return -1;
}
public boolean isOper(char oper){
return oper=='+'||oper=='-'||oper=='*'||oper=='/';
}
public int cal(int a,int b,char oper) {
int res = 0;
switch (oper) {
case '+':
res=a+b;
break;
case '-':
res=b-a;
break;
case '*':
res=a*b;
break;
case '/':
res=b/a;
break;
default:break;
}
return res;
}
}