直接上代码
package learn;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class BoLan {
public static List<String> getList(String ex){
List<String> list = new ArrayList<>();
String[] strings= ex.split(" ");
for(String s:strings){
list.add(s);
}
return list;
}
public static int cal(List<String> strings) {
Stack<String> stack = new Stack<>();
for (String s : strings) {
if (s.matches("\\d+")) {
stack.push(s);
} else {
int num2=Integer.parseInt(stack.pop());
int num1=Integer.valueOf(stack.pop());
int res=0;
if(s.equals("+")){
res=num1+num2;
}else if(s.equals("-")){
res=num1-num2;
}else if(s.equals("*")){
res=num1*num2;
}else{
res=num1/num2;
}
stack.push(res+"");
}
}
return Integer.valueOf(stack.pop());
}
public static void main(String[] args) {
String ex="3 4 + 5 * 6 -";
List<String> list = getList(ex);
System.out.println(cal(list));
}
}