Java programming: stack application example-simple comprehensive calculator implementation (infix expression)

Stack realization comprehensive calculator (infix expression)

  • Use the stack to implement a comprehensive calculator-custom priority [priority]

Insert picture description here

Thinking analysis

Insert picture description here

Code

important point:

  1. charTypes can be intcompared with types, charessentially int
  2. Find the i-th character of the string can be usedstr.charAt(num)
  3. Intercept the i to j bits of the stringstr.substring(i,j)
  4. String type number to integerInteger.parseInt(str)
package stack;

import java.util.Scanner;

public class Calculator {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        String expression = scanner.nextLine();
        // 创建两个栈:数栈和符号栈
        CalculatorStack numStack = new CalculatorStack(10);
        CalculatorStack opeStack = new CalculatorStack(10);
        // 需要的相关变量
        int index = 0;  // 用于扫描
        int num1 = 0;
        int num2 = 0;
        int ope = 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 (opeStack.isOpe(ch)) {
    
     // 如果是运算法
                // 判断符号栈是否为空
                if (opeStack.isEmpty()) {
    
    
                    // 如果为空,直接入符号栈
                    opeStack.push(ch);
                } else {
    
      // 操作栈不为空
                    // 如果当前的操作符的优先级小于或等于栈中的操作符
                    // 需要从符号栈中pop一个符号,数栈中pop两个数字,进行运算
                    // 得到结果后,入数栈,然后将当前符号入符号栈
                    if (opeStack.priority(ch) <= opeStack.priority(opeStack.peek())) {
    
    
                        num1 = numStack.pop();
                        num2 = numStack.pop();
                        ope = opeStack.pop();
                        res = numStack.cal(num1, num2, ope);
                        numStack.push(res); // 运算结果入数栈
                        opeStack.push(ch);  // 当前操作符入符号栈
                    } else {
    
    
                        // 如果当前的操作符的优先级大于栈中的操作数
                        // 直接入符号栈
                        opeStack.push(ch);
                    }
                }
            } else {
    
    
                // 如果是数字,直接入数栈
                // 减48的原因是在ASIIC表中数字真实值与数字相差48
                // numStack.push(ch - 48);

                // 优化:处理多位数
                // 1. 当处理多位数时候,不能发现是一个数就立即入栈,因为可能是多位数
                // 2. 在处理树时候,需要向expression的表达式的index后再看以为,如果是数就入栈,如果发现是符号就继续扫描
                // 3. 因此需要定义一个字符串变量,用于拼接.
                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清空
                        keepNum = "";
                    }
                }

            }
            // index+1 并判断是否扫描到expression的最后
            index++;
            if (index >= expression.length()) {
    
    
                break;
            }
        }
        // 表达式扫描完毕后,顺序从数栈和符号栈中pop出相应的符号,并运算即可
        while (true) {
    
    
            // 如果符号栈为空,则计算到最后的结果
            // 此时数栈中只有一个数字【结果】
            if (opeStack.isEmpty()) {
    
    
                break;
            }
            num1 = numStack.pop();
            num2 = numStack.pop();
            ope = opeStack.pop();
            res = numStack.cal(num1, num2, ope);
            numStack.push(res);
        }
        System.out.printf("表达式%s = %d", expression, res);
    }
}


// 先创建一个栈
class CalculatorStack {
    
    
    private int maxSize;    // 栈的大小
    private int[] stack;    // 数组模拟栈,数据放在该数组
    private int top = -1;   // top表示栈顶,初始化为-1

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

    // 返回当前栈顶的值,仅查询
    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;
        }
        stack[++top] = value;
    }

    public int pop() {
    
    
        if (isEmpty()) {
    
    
            throw new RuntimeException("栈空,没有数据");
        }
        return stack[top--];
    }

    public void list() {
    
    
        if (isEmpty()) {
    
    
            System.out.println("栈空,没有数据");
            return;
        }
        for (int i = top; i >= 0; i--) {
    
    
            System.out.printf("%d ", stack[i]);
        }
    }

    // 返回运算符的优先级,优先级是程序员确定,优先级使用数字表示
    // 数字越大,优先级越高
    public int priority(int ope) {
    
    
        if (ope == '*' || ope == '/') {
    
    
            return 1;
        } else if (ope == '+' || ope == '-') {
    
    
            return 0;
        } else {
    
    
            return -1;  //假设目前表达式只有+、-、*、/
        }
    }

    // 判断是不是一个运算符
    public boolean isOpe(char val) {
    
    
        return val == '+' || val == '-' || val == '*' || val == '/';
    }

    // 计算方法
    public int cal(int num1, int num2, int ope) {
    
    
        int res = 0;
        switch (ope) {
    
    
            case '+':
                res = num1 + num2;
                break;
            case '-':
                res = num2 - num1;
                break;
            case '*':
                res = num1 * num2;
                break;
            case '/':
                res = num2 / num1;
                break;
            default:
                break;
        }
        return res;
    }

}

Guess you like

Origin blog.csdn.net/KaiSarH/article/details/108733742