public class PolandNotation {
public static void main(String[] args) {
//4*5-8+60+8/2
String suffixExpression = "4,5,*,8,-,60,+,8,2,/,+";
List<String> listString = getListString(suffixExpression);
String calc = calc(listString);
System.out.println("结果是:" + calc);
}
public static List<String> getListString(String expression) {
String[] split = expression.split(",");
ArrayList<String> list = new ArrayList<>();
for (String s : split) {
list.add(s);
}
return list;
}
public static String calc(List<String> list) {
Stack<String> stack = new Stack<String>();
for (String item : list) {
if (item.matches("\\d+")) {
stack.push(item);
} else {
Integer num1 = Integer.parseInt(stack.pop());
Integer num2 = Integer.parseInt(stack.pop());
int res = 0;
switch (item) {
case "+":
res = num1 + num2;
break;
case "-":
res = num2 - num1;
break;
case "*":
res = num2 * num1;
break;
case "/":
res = num2 / num1;
break;
}
stack.push(res + "");
}
}
return stack.pop();
}
}