其他分享
首页 > 其他分享> > 栈-实现综合计算器(中缀表达式的计算)

栈-实现综合计算器(中缀表达式的计算)

作者:互联网

综合计算器怎么搞?

思路

在这里插入图片描述

Demo1

package datastructres.stack;

/**
 * @author :Yan Guang
 * @date :Created in 2021/1/11 9:41
 * @description:
 */
public class Calculator {
    public static void main(String[] args) {
        String expression = "3+2*6-2";
        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;    
        char ch = ' ';
        while (true){
            ch = expression.substring(index,index+1).charAt(0);
            //首先判断ch是什么,然后进行操作
            if (operStack.isOper(ch)){
                if (!operStack.isEmpty()){
                    //如果该元素优先级小于等于栈顶的优先级
                    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里面存放的是int类型的,这里存放值的时候需要对照ASCII码表进行对照
                //但是int类型可以与char类型直接进行比较
                numStack.push(ch-48);
            }
            index++;
            if (index>=expression.length()){
                break;
            }
        }
        //现在扫描已经结束,需要继续处理完两个栈中的元素
        while (true){
            if (operStack.isEmpty()){
                break;
            }
            num1 = numStack.pop();
            num2 = numStack.pop();
            oper = operStack.pop();
            res = operStack.cal(num1, num2, oper);
            numStack.push(res);
        }
        //最后存放在numStack里面的元素就是结果了
        System.out.printf("表达式%s = %d",expression,numStack.pop());
    }
}

class ArrayStack2 {
    private int maxSize;
    private int[] stack;
    private int top = -1;

    public ArrayStack2(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }

    public boolean isFull() {
        return top == maxSize - 1;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public void push(int value) {
        if (isFull()) {
            System.out.println("栈满,无法添加~");
            return;
        }
        top++;
        stack[top] = value;
    }

    public int peek(){
        return stack[top];
    }

    public int pop() {
        if (isEmpty()) {
            //throw相当于已经停止了代码,所以不用return
            //当存在返回值的时候(不为void)的时候,我们尽量可以抛出一个异常来代替return
            throw new RuntimeException("栈空,无法取出数据~");
        }
        int value = stack[top];
        top--;
        return value;
    }

    public void showStack() {
        if (isEmpty()) {
            System.out.println("栈已空~");
            return;
        }
        //循环的时候是从栈顶往下循环,也就是从数组的最后开始循环的~
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d]=%d\n", i, stack[i]);
        }
    }

    public int priority(int oper) {
        if (oper == '*' || oper == '/') {
            return 1;
        } else if (oper == '+' || oper == '-') {
            return 0;
        } else {
            return -1;
        }
    }

    public boolean isOper(char val) {
        return val == '+' || val == '-' || val == '*' || val == '/';
    }

    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;
            default:
                break;
        }
        return res;
    }
}

这里存在的问题就是只能进行一位数运算,无法计算大于10的数,而且只有加减乘除四个运算符~

下面是优化之后的代码,具体也就改了一个地方,有很多注释的地方,大家看看吧

Demo2

package datastructres.stack;

/**
 * @author :Yan Guang
 * @date :Created in 2021/1/11 9:41
 * @description:
 */
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;
        char ch = ' ';
        String keepNum="";
        while (true){
            ch = expression.substring(index,index+1).charAt(0);
            //首先判断ch是什么,然后进行操作
            if (operStack.isOper(ch)){
                if (!operStack.isEmpty()){
                    //如果该元素优先级小于等于栈顶的优先级
                    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里面存放的是int类型的,这里存放值的时候需要对照ASCII码表进行对照
                //但是int类型可以与char类型直接进行比较
                //1.
                //1.当处理多位数时,不能发现是一个数就立即入栈,因为他可能是多位数
                //2.在处理数,需要向expression的表达式的index后再看-位,如果是数就进行扫描,如果是符号才入栈
                //3.因此我们需要定义一个变量字符串,用于拼接
                // numStack.push(ch-48);
                keepNum+=ch;
                //如果当此时的数为最后一个数字数,就直接入栈
                if (index==expression.length()-1){
                    numStack.push(Integer.parseInt(keepNum));
                }else {
                    //这里会存在一个越界问题,如果index到了最后一个,就没有index+1了
                    if (operStack.isOper(expression.substring(index + 1, index + 2).charAt(0))) {//判断是否是运算符
                        numStack.push(Integer.parseInt(keepNum));
                        keepNum = "";
                    }
                }
            }
            index++;
            if (index>=expression.length()){
                break;
            }
        }
        //现在扫描已经结束,需要继续处理完两个栈中的元素
        while (true){
            if (operStack.isEmpty()){
                break;
            }
            num1 = numStack.pop();
            num2 = numStack.pop();
            oper = operStack.pop();
            res = operStack.cal(num1, num2, oper);
            numStack.push(res);
        }
        //最后存放在numStack里面的元素就是结果了
        System.out.printf("表达式%s = %d",expression,numStack.pop());
    }
}

class ArrayStack2 {
    private int maxSize;
    private int[] stack;
    private int top = -1;

    public ArrayStack2(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }

    public boolean isFull() {
        return top == maxSize - 1;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public void push(int value) {
        if (isFull()) {
            System.out.println("栈满,无法添加~");
            return;
        }
        top++;
        stack[top] = value;
    }

    public int peek(){
        return stack[top];
    }

    public int pop() {
        if (isEmpty()) {
            //throw相当于已经停止了代码,所以不用return
            //当存在返回值的时候(不为void)的时候,我们尽量可以抛出一个异常来代替return
            throw new RuntimeException("栈空,无法取出数据~");
        }
        int value = stack[top];
        top--;
        return value;
    }

    public void showStack() {
        if (isEmpty()) {
            System.out.println("栈已空~");
            return;
        }
        //循环的时候是从栈顶往下循环,也就是从数组的最后开始循环的~
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d]=%d\n", i, stack[i]);
        }
    }

    public int priority(int oper) {
        if (oper == '*' || oper == '/') {
            return 1;
        } else if (oper == '+' || oper == '-') {
            return 0;
        } else {
            return -1;
        }
    }

    public boolean isOper(char val) {
        return val == '+' || val == '-' || val == '*' || val == '/';
    }

    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;
            default:
                break;
        }
        return res;
    }
}

欢迎大家在评论区讨论哟~

标签:oper,numStack,return,operStack,int,计算器,public,表达式,中缀
来源: https://blog.csdn.net/weixin_46558851/article/details/112461754