用数组模拟栈实现简单计算器的功能

class Calculator

package DataStructures.stack;

import org.junit.jupiter.api.Test;


/**
 * 简单计算器
 * @author coffee
 * @date 2021-03-30 17:28
 */
public class Calculator {
    @Test
    public void test(){
        String expression = "3+6*2-2+1";
        arrStack numStack = new arrStack(10);//数栈
        arrStack opeStack = new arrStack(10);//符号栈
        int index = 0;//扫描器
        int n1 = 0;
        int n2 = 0;
        int ope = 0;
        int result = 0;
        char ch = ' ';//扫描器保存器
        String keepNum = "";//用于拼接多位数
        //扫描expression
        while (true){
            ch = expression.substring(index, index + 1).charAt(0);
            if (opeStack.isOpe(ch)){//如果扫描到是一个符号
                if (!opeStack.isEmpty()){//如果符号栈不为空,则进行比较
                    if (opeStack.priority(ch) <= opeStack.priority(opeStack.peek())){//如果当前操作符的优先级小于或者等于栈顶的操作符
                        //就需要从数栈中pop出两个数,从符号栈中取出一个符号,
                        //进行计算得到结果,结果入数栈,当前符号入符号栈
                        n1 = numStack.pop();
                        n2 = numStack.pop();
                        ope = opeStack.pop();
                        result = numStack.cal(n1, n2, ope);
                        numStack.push(result);
                        opeStack.push(ch);
                    }else {//如果当前符号的优先级大于栈中的操作符,就直接入符号栈
                        opeStack.push(ch);
                    }
                }else{//如果为空,直接入栈
                    opeStack.push(ch);
                }
            }else{//如果扫描到是一个数字,就直接入数栈
                keepNum += ch;//拼串
                //如果ch是expression的最后一位,就直接入栈
                if (index == expression.length() - 1){
                    numStack.push(Integer.parseInt(keepNum));
                }else {
                    //判断下一个字符是不是数字,如果是数字,就继续扫描,如果是运算符,则入栈
                    if (opeStack.isOpe(expression.substring(index + 1,index + 2).charAt(0))){
                        //如果后一位是运算符,则入栈
                        numStack.push(Integer.parseInt(keepNum));
                        keepNum = "";
                    }
                }
            }
            //让index + 1,判断是否扫描到expression最后
            index++;
            if (index == expression.length()){
                break;
            }
        }

        while (true){
            if (opeStack.isEmpty()){
                break;
            }
            n1 = numStack.pop();
            n2 = numStack.pop();
            ope = opeStack.pop();
            result = numStack.cal(n1, n2, ope);
            numStack.push(result);
        }
        int res = numStack.pop();
        System.out.println("表达式" + expression + "=" + res);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值