主要思路就是把数放进栈中,如果遇见符号我们就计算,计算后数还是要放入栈,不保存符号
在这里插入代码片package a;
import java.util.Stack;
public class CalDemo {
public static void main(String[] args) {
String expr = "3 4 + 5 * 6 -";//(3+4)x5-6这个是源表达式。逆波兰
String[] strs = expr.split(" ");
System.out.println("strs = " + strs);
int res = calculate(strs);
System.out.println("res = " + res);
}
private static int calculate(String[] strs) {
Stack<String> sta = new Stack<>();
for (String s : strs) {
if(s.matches("\\d+")){
sta.push(s);
}else {
int n1 = Integer.parseInt(sta.pop());
int n2 = Integer.parseInt(sta.pop());
int res = 0;
switch (s) {
case "+":res = n2+n1;
break;
case "-":res = n2-n1;
break;
case "*":res = n2*n1;
break;
case "/":res = n2/n1;
break;
default:break;
}
sta.push(""+res);
}
}
return Integer.parseInt(sta.pop());
}
}