java模拟计算器实现后缀表达式(逆波兰表达式)

后缀表达式思路:
首先定义一个栈,遍历每个数据
1)遇到数字直接入栈;
2)遇到字符串就pop();两个值;
3)根据当前扫描到的运算符进行计算;
4)将结果入栈,栈内最后一个值就是结果;

public class Suffix {
    public static void main(String[] args) {
        // 定义一个后缀表达式
        String str = "3 4 + 5 * 6 -";

        List<String> list = getListString(str);
        int calculate = calculate(list);
        System.out.println(calculate);
    }


    // 获取集合
    public static List<String> getListString(String str) {
        List<String> list = new ArrayList<String>();
        String[] split = str.split(" ");
        for (String s : split) {
            list.add(s);
        }
        return list;
    }


    /**
     * 完成比波兰表达式算法
     * 1)从左到右扫描,将3和4入栈;
     * 2)遇到+运算符,因此弹出4和3(4为栈顶,3为次栈顶),计算3+4的值,得到7,再将7入栈;
     * 3)将5入栈;
     * 4)接下来是*运算符,因此弹出5和7,计算5*7=35,将35入栈;
     * 5)将6入栈;
     * 6)最后是-运算符,计算35-6=29,由此得出最后结果;
     *
     * @return
     */
    public static int calculate(List<String> list) {
        Stack<String> stack = new Stack<String>();
        for (String s : list) {
            if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")) {
                int num = Integer.parseInt(stack.pop());
                int num2 = Integer.parseInt(stack.pop());
                int res = 0;    //结果
                // 根据运算符计算
                if (s.equals("+")) {
                    res = num + num2;
                } else if (s.equals("-")) {
                    res = num2 - num;
                } else if (s.equals("*")) {
                    res = num * num2;
                } else if (s.equals("/")) {
                    res = num2 / num;
                }
                // 把结果入栈
                stack.push("" + res);
            } else {
                // 如果是数字直接入栈
                stack.push(s);
            }
        }
        // 最后一个数字就是结果
        return Integer.parseInt(stack.pop());
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值