java代码实现一个简单的逆波兰计算器,逆波兰表达式

public class PolandNotation {
    public static void main(String[] args) {
        //4*5-8+60+8/2
        String suffixExpression = "4,5,*,8,-,60,+,8,2,/,+";

        List listString = getListString(suffixExpression);
        String calc = calc(listString);
        System.out.println("结果是:" + calc);

    }

    public static List getListString(String expression) {

        String[] split = expression.split(",");
        ArrayList list = new ArrayList<>();
        for (String s : split) {
            list.add(s);
        }
        return list;
    }

    public static String calc(List list) {

        Stack stack = new Stack();

        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();

    }
}

 

你可能感兴趣的:(java代码实现一个简单的逆波兰计算器,逆波兰表达式)