【Java】栈·用栈实现综合计算器(中缀表达式)

使用栈来实现综合计算器

在这里插入图片描述

思路分析

使用栈完成表达式的计算 思路

  1. 通过一个 index 值(索引),来遍历我们的表达式
  2. 如果我们发现是一个数字, 就直接入数栈
  3. 如果发现扫描到是一个符号, 就分如下情况
    3.1 如果发现当前的符号栈为 空,就直接入栈
    3.2 如果符号栈有操作符,就进行比较,如果当前的操作符的优先级小于或者等于栈中的操作符, 就需要从数栈中pop出两个数,在从符号栈中pop出一个符号,进行运算,将得到结果,入数栈,然后将当前的操作符入符号栈, 如果当前的操作符的优先级大于栈中的操作符, 就直接入符号栈.
  4. 当表达式扫描完毕,就顺序的从 数栈和符号栈中pop出相应的数和符号,并运行.
  5. 最后在数栈只有一个数字,就是表达式的结果

代码实现

第一版:实现一位数的运算

package com.atguigu.stack;

public class Calculator {
    public static void main(String[] args) {
        //根据思路完成运算
        String expression = "7+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 = ' ';//将每次扫描的char保存到ch
        //开始while循环的扫描expression
        while (true) {
            //一次得到 expression 的每一个字符
            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 = numStack.cal(num1, num2, oper);
                        //把运算的结果入数栈
                        numStack.push(res);
                        //然后把当前的操作符入符号栈
                        operStack.push(ch);
                    } else {
                        //如果为空,入栈
                        operStack.push(ch);
                    }
                } else {
                    //如果为空,直接入符号栈...
                    operStack.push(ch); //1+3
                }
            } else { //如果是数,直接入数栈
                numStack.push(ch - 48); //? "1+3" '1' =》 1
            }
            //让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 = numStack.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;//top表示栈顶

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

    //增加一个方法,可以返回当前栈顶的值,但是不是真正的pop
    public int peek() {
        return stack[top];
    }

    //栈满
    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 pop() {
        //先判断栈是否空
        if (isEmpty()) {
            throw new RuntimeException("栈空,没有数据~");
        }
        int value = stack[top];
        top--;
        return value;
    }
    //显示栈的情况[遍历栈],遍历时需要从栈顶开始显示数据
    public void list() {
        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;//res用于存放计算结果
        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 class Calculator {
    public static void main(String[] args) {
        //根据思路完成运算
        String expression = "70+20*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 = ' ';//将每次扫描的char保存到ch
        String keepNum = "";//用于拼接 多位数
        //开始while循环的扫描expression
        while (true) {
            //一次得到 expression 的每一个字符
            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 = numStack.cal(num1, num2, oper);
                        //把运算的结果入数栈
                        numStack.push(res);
                        //然后把当前的操作符入符号栈
                        operStack.push(ch);
                    } else {
                        //如果为空,入栈
                        operStack.push(ch);
                    }
                } else {
                    //如果为空,直接入符号栈...
                    operStack.push(ch); //1+3
                }
            } else { //如果是数,直接入数栈

                //numStack.push(ch - 48); //? "1+3" '1' =》 1
                //分析思路
                //1、当处理多位数时,不能发现是一个数就立即入栈,因为它可能是多位数
                //2、在处理数时,需要向expression的表达式的index,后再看一位,如果是数就扫描,如果是符号才入栈
                //因此我们要定义一个字符串变量用于拼接

                //处理多位数
                keepNum += ch;

                //如果ch已经是expression的最后一位,就直接入栈
                if (index == expression.length() - 1) {
                    numStack.push(Integer.parseInt(keepNum));
                } else {
                //判断下一个字符是不是数字,如果是数字,就继续扫描,如果是运算符,则入栈
                //注意是看后一位,不是index++
                    if (operStack.isOper(expression.substring(index+1,index+2).charAt(0))) {
                        //如果后一位是运算符,则入栈 keepNum = "1" 或者 "123"
                        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 = numStack.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;//top表示栈顶

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

    //增加一个方法,可以返回当前栈顶的值,但是不是真正的pop
    public int peek() {
        return stack[top];
    }

    //栈满
    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 pop() {
        //先判断栈是否空
        if (isEmpty()) {
            throw new RuntimeException("栈空,没有数据~");
        }
        int value = stack[top];
        top--;
        return value;
    }
    //显示栈的情况[遍历栈],遍历时需要从栈顶开始显示数据
    public void list() {
        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;//res用于存放计算结果
        switch (oper) {
            case '+' :
                res = num1 + num2;
                break;
            case '-' :
                res = num2 - num1;//注意顺序
                break;
            case '*' :
                res = num1 * num2;
                break;
            case '/' :
                res = num2 / num1;//注意顺序
                break;
        }
        return res;
    }
}

小小的作业

带小括号的运算

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Java 中的 Map 来实现计算器计算。具体思路如下: 1. 将所有操作符和对应的操作方法存储在 Map 中。 2. 将表达式转换为后缀表达式,并使用来计算后缀表达式。 下面是示例代码: ```java import java.util.*; public class Calculator { private static final Map<String, BiFunction<Double, Double, Double>> OPERATIONS = new HashMap<>(); static { OPERATIONS.put("+", (a, b) -> a + b); OPERATIONS.put("-", (a, b) -> a - b); OPERATIONS.put("*", (a, b) -> a * b); OPERATIONS.put("/", (a, b) -> a / b); } public static void main(String[] args) { String expression = "2 + 3 * 4 - 5 / 2"; List<String> postfix = toPostfix(expression); double result = evaluatePostfix(postfix); System.out.println(result); } // 将中缀表达式转换为后缀表达式 private static List<String> toPostfix(String expression) { List<String> postfix = new ArrayList<>(); Stack<String> stack = new Stack<>(); String[] tokens = expression.split("\\s+"); for (String token : tokens) { if (isNumber(token)) { postfix.add(token); } else if (OPERATIONS.containsKey(token)) { while (!stack.isEmpty() && !stack.peek().equals("(") && hasHigherPrecedence(stack.peek(), token)) { postfix.add(stack.pop()); } stack.push(token); } else if (token.equals("(")) { stack.push(token); } else if (token.equals(")")) { while (!stack.isEmpty() && !stack.peek().equals("(")) { postfix.add(stack.pop()); } stack.pop(); } } while (!stack.isEmpty()) { postfix.add(stack.pop()); } return postfix; } // 判断是否为数字 private static boolean isNumber(String token) { try { Double.parseDouble(token); return true; } catch (NumberFormatException e) { return false; } } // 判断操作符优先级 private static boolean hasHigherPrecedence(String op1, String op2) { return !op1.equals("(") && !op2.equals(")") && (op1.equals("*") || op1.equals("/")) && (op2.equals("+") || op2.equals("-")); } // 计算后缀表达式 private static double evaluatePostfix(List<String> postfix) { Stack<Double> stack = new Stack<>(); for (String token : postfix) { if (isNumber(token)) { stack.push(Double.parseDouble(token)); } else if (OPERATIONS.containsKey(token)) { double b = stack.pop(); double a = stack.pop(); stack.push(OPERATIONS.get(token).apply(a, b)); } } return stack.pop(); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值