import java.util.Stack; /** * 目标:实现后缀表达式的基本运算 * 运算规则:1.建立栈 从左到右数字依次入栈 * 2.如果遇到符号,取出栈顶,和次栈顶的数字进行运算(次栈顶数字在操作符前) * 3.直到最后计算出最终结果 */ public class SuffixTest { public static void main(String[] args) { //后缀表达式:4 5 * 8 - 60 + 8 2 / + String suffix = "4 5 * 8 - 60 + 8 2 / +"; String[] arrString = suffix.split(" "); Stack<Integer> stack = new Stack<Integer>(); for (String ele:arrString){ if(ele.matches("\d+")){ stack.push(Integer.parseInt(ele)); }else{ Integer num1 = stack.pop(); Integer num2 = stack.pop(); stack.push(getResult(num1,num2,ele)); } } System.out.println("最后结果:"+stack.pop()); } /** * 根据运算符运算结果 * @param num1 * @param num2 * @param operate * @return */ public static Integer getResult(Integer num1,Integer num2,String operate){ if("+".equals(operate)) return num2+num1; if("-".equals(operate)) return num2-num1; if("*".equals(operate)) return num2*num1; if("/".equals(operate)) return num2/num1; else return 0; } }