java实现逆波兰计算器

java实现逆波兰计算器

代码实现

public class PolandDemo {
    public static void main(String[] args) {
        // 定义一个逆波兰表达式
        // (3+4)*5-6 => 3 4 + 5 * 6 -
        String suffixExpression = "3 4 + 5 * 6 -";
        // 1. 先将表达式放入ArrayList
        // 2. 讲ArrayList传递一个方法,遍历ArrayList配合栈完成计算
        List<String> list = getList(suffixExpression);
        int result = calculate(list);
        System.out.println(suffixExpression + "表达式的值为 ==> " + result);
    }

    public static int calculate(List<String> list) {
        // 创建一个栈
        Stack<String> stack = new Stack<>();
        // 遍历
        for (String s : list) {
            // 使用正则表达式取出数
            // 匹配的是多位数
            if (s.matches("\\d+")) {
                // 入栈
                stack.push(s);
            } else {
                // 如果是运算符
                // 预算
                int num2 = Integer.parseInt(stack.pop());
                int num1 = Integer.parseInt(stack.pop());
                int result = 0;

                switch (s) {
                    case "+":
                        result = num1 + num2;
                        break;
                    case "-":
                        result = num1 - num2;
                        break;
                    case "*":
                        result = num1 * num2;
                        break;
                    case "/":
                        result = num1 / num2;
                        break;
                    default:
                        throw new RuntimeException("表达式运算符错误");
                }
                stack.push(result + "");
            }
        }
        // 最后留在stack中的就是结果
        return Integer.parseInt(stack.pop());
    }

    public static List<String> getList(String Expression) {
        // 按照空格来分割
        String[] split = Expression.split(" ");

        List<String> list = new ArrayList<>();
        for (String s : split) {
            list.add(s);
        }
        return list;
    }
}
posted @ 2022-03-28 15:16  CoderCatIce  阅读(57)  评论(0编辑  收藏  举报