双栈实现基本计算器

双栈实现基本计算器

public class StackCalculator {
    public static void main(String[] args) {
        StackCalculatorTest stackCalculatorTest = new StackCalculatorTest();
        System.out.println(stackCalculatorTest.calculation("7*2*2-5+1-5+3-4"));
    }
}

class StackCalculatorTest {
    private Stack<Integer> stack1;  //数据栈
    private Stack<Character> stack2;  //符号栈

    public StackCalculatorTest() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }

    public int priority(char c) {     //优先级判断
        if (c == '+' || c == '-') {  // + -为1
            return 1;
        }
        if (c == '*' || c == '/') {  // * / 为2
            return 2;
        }
        return 0;
    }

    public int switch_(char c1, int num2, int num1) {  //因为栈是先进后出---所以在栈里先出的是符号后面的数
        int temp = 0;
        switch (c1) {
            case '*':
                temp = num1 * num2;
                break;
            case '-':
                temp = num1 - num2;
                break;
            case '+':
                temp = num1 + num2;
                break;
            case '/':
                temp = num1 / num2;
                break;
        }
        return temp;
    }

    public int calculation(String s) {
        char[] chars = s.toCharArray();
        for (char c : chars) {
            if (c == '+' || c == '-' || c == '*' || c == '/') {
                if (stack2.size() != 0) {    //当符号栈不为空是才进行 优先级判断
                    if (priority(c) <= priority(stack2.peek())) {  //每次都和顶栈元素比
                        int num1 = stack1.pop();  //弹出两个数栈元素
                        int num2 = stack1.pop();
                        char c1 = stack2.pop();   //弹出一个符号栈元素
                        stack1.push(switch_(c1, num1, num2));  //运算的结果在进入数栈
                    }
                }
                stack2.push(c);  //符号入栈
            }
                if (c >= '0' && c <= '9') {
                    Integer num = Integer.parseInt(String.valueOf(c));  //将字符转化为数字
                    stack1.push(num);
                }
            }
        while (!stack2.isEmpty()){   //如果符号栈不为空则循环计算

                int num1 = stack1.pop();  //弹出两个元素
                int num2 = stack1.pop();
                char c1 = stack2.pop();   //弹出一个元素
                stack1.push(switch_(c1,num1,num2));  //运算的结果
        }
            return stack1.peek();  //返回数栈的顶栈数据
        }
    }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值