代码如下:
public class Calculator { public static void main(String[] args) { String expression = "7*2-5*2"; int length = expression.length(); CalcuStack numStack = new CalcuStack(length); CalcuStack operStack = new CalcuStack(length); char[] chars = expression.toCharArray(); String keepNum = ""; int num1 = 0; int num2 = 0; int oper = 0; int res = 0; for (int i = 0; i < chars.length; i ++) { if (operStack.isOper(chars[i])) { operStack.list(); if (!operStack.isEmpty()) { if (operStack.priority(chars[i]) <= operStack.priority(operStack.peek())) { num1 = numStack.pop(); num2 = numStack.pop(); oper = operStack.pop(); res = numStack.cal(num1, num2, oper); numStack.push(res); operStack.push(chars[i]); } else { operStack.push(chars[i]); } } else { operStack.push(chars[i]); } } else { int count = 0; for (int a = i; a + count < chars.length; count ++) { if (operStack.isOper(chars[a + count])) { i = i + count - 1; break; } keepNum += chars[a + count]; } numStack.push(Integer.parseInt(keepNum)); keepNum = ""; } } numStack.list(); operStack.list(); while (true) { if (operStack.isEmpty()) { break; } num1 = numStack.pop(); num2 = numStack.pop(); oper = operStack.pop(); res = numStack.cal(num1, num2, oper); numStack.push(res); } int res2 = numStack.pop(); System.out.printf("%s=%d\n", expression, res2); } } class CalcuStack { private int maxSize; private int[] stack; private int top = -1; // 构造函数 public CalcuStack(int maxSize) { this.maxSize = maxSize; this.stack = new int[maxSize]; } // 判断是否栈满 public boolean isFull() { return top == maxSize - 1; } // 判断是否栈空 public boolean isEmpty() { return top == -1; } // 获取栈顶数据,不出栈 public int peek() { return stack[top]; } // 入栈 public void push(int data) { if (isFull()) { System.out.println("栈满"); return; } top ++; stack[top] = data; } // 出栈 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; switch (oper) { case ‘+‘: res = num1 + num2; break; case ‘-‘: res = num2 - num1; break; case ‘*‘: res = num1 * num2; break; case ‘/‘: res = num1 / num2; break; default: break; } return res; } }