数据结构和算法——基于Java——4.2栈实现计算器

理论补充

在这里插入图片描述

代码实现

package com.b0.stack;

public class Calculator {
    public static void main(String[] args) {
        String expression = "70+2*6-4";
        //创建两个栈,数栈,符号栈
        ArrayStack2 numStack = new ArrayStack2(10);
        ArrayStack2 operStack = new ArrayStack2(10);
        //定义需要的变量
        int index = 0;//用于扫描
        int num1 =0;
        int num2 =0;
        int oper = 0;
        int res = 0;
        String keepNum ="";
        char ch = ' ';//将每次扫描得到的char保存到ch
        while (true){
            //依次得到expression的每一个字符
            ch = expression.substring(index,index+1).charAt(0);
            //判断ch是什么,然后做相应的处理
            if (operStack.isOper(ch)){
                if (!operStack.isEmpty()){
                    //若当前操作符优先级小于或者等于栈中的操作符,从数栈pop出两个数,符号栈pop出一个符号运算,运算后将运算结果push进数栈
                    if (operStack.priority(ch) <= operStack.priority(operStack.peek())){
                        num1 = numStack.pop();
                        num2 = numStack.pop();
                        oper = operStack.pop();
                        //运算,将结果放入数栈
                        res = operStack.cal(num1,num2,oper);
                        numStack.push(res);
                        //当前操作符入符号栈
                        operStack.push(ch);
                    }else {
                        //若当前操作符的优先级大于栈中的操作符,直接入符号栈
                        operStack.push(ch);
                    }
                }else {
                    //若为空,直接入符号栈
                    operStack.push(ch);
                }
            }else {
                //若为数,直接入数栈
//                numStack.push(ch - 48);//此处由于ASCII码,与值相差48,因此需要减
                //1.若处理多位数时,不能发现时一个数就立即入栈,
                //2.在处理数时,需要向expression后面的index向后面再看一位,若为数字才入栈
                //3.因此需要定义一个字符串变量用于拼接

                //处理多位数
                keepNum += ch;
                //如果ch已经是expression的最后以为,就直接入栈
                if (index == expression.length()-1){
                    numStack.push(Integer.parseInt(keepNum));
                }else {
                    //判断下一个字符为数字就继续扫描;若是运算符,则入栈
                    if (operStack.isOper(expression.substring(index+1,index+2).charAt(0))){
                        //若后一位是运算符,则入栈
                        numStack.push(Integer.parseInt(keepNum));
                        //重要!!!keepNum清空
                        keepNum = "";
                    }
                }
            }
            //让index+1,并验证是否扫描到expression最后
            index++;
            if (index >= expression.length()){
                break;
            }
        }
        //当扫描完毕后,顺序从数栈和符号栈中pop出相应的数和符号,并运行
        while (true){
            //若符号栈为空,计算到最后的结果,数栈中只有一个数字
            if (operStack.isEmpty()){
                break;
            }
            num1 = numStack.pop();
            num2 = numStack.pop();
            oper = operStack.pop();
            //运算,将结果放入数栈
            res = operStack.cal(num1,num2,oper);
            numStack.push(res);//入栈
        }
        //将数栈的最后数,pop出,就是结果
        int res2 = numStack.pop();
        System.out.printf("表达式%s = %d",expression,res2);
    }
}
//创建一个栈
class ArrayStack2{
    private int maxSize;//栈的大小
    private int[] stack;//数组模拟栈
    private int top = -1;//栈顶,初始化为-1
    //构造器
    public ArrayStack2(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }
    //1.判断数字 和 运符号
    public boolean isOper(char val){
        return val == '+' || val == '-' || val == '*' || val =='/';
    }
    //2.判断符号优先级(下方以数字越大优先级越高;)
    public int priority(int oper){
        if (oper == '*' || oper == '/'){
            return 1;
        } else if (oper == '+' || oper =='-') {
            return 0;
        }else {
            return -1;//假定现在只判断+ - * /
        }
    }
    //3.计算方法
    public int cal(int num1,int num2,int oper){
        int res = 0;//存放计算的结果
        switch (oper){
            case '+':
                res = num1 + num2;
            break;
            case '-':
                res = num2 - num1;
                break;
            case '*':
                res = num1 * num2;
                break;
            case '/':
                res = num2 / num1;
                break;
        }
        return res;
    }
    //增加一个方法可以返回当前栈顶的值(不出栈)
    public int peek(){
        return stack[top];
    }
    //判断栈满
    public boolean isFull(){
        return top == maxSize-1;
    }
    //栈空
    public boolean isEmpty(){
        return top == -1;
    }
    //入栈
    public void push(int num){
        //判断是否栈满
        if (isFull()){
            System.out.println("栈满");
            return;
        }
        top++;
        stack[top] = num;
    }
    //出栈
    public int pop(){
        //判断是否栈空
        if (isEmpty()){
            //抛出异常
            throw new RuntimeException("栈空,没有数据!");
        }
        int value = stack[top];
        top--;
        return value;
    }
    //遍历栈
    public void list(){
        if (isEmpty()){
            System.out.println("栈空!");
            return;
        }
        while (top != -1){
            //从栈顶开始遍历
            System.out.println(stack[top]);
            top--;
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值