package com.aitongji.stack;
public class Calculator {
public static void main(String[] args) {
String expression = "7*21*2-5+1-5+3-42";
// 定义一个数栈一个符号栈
ArrayStackForCal stackfornum = new ArrayStackForCal();
ArrayStackForCal stackforoper = new ArrayStackForCal();
char[] expressionArray = expression.toCharArray();
int keepnums = 0;
for (int i = 0; i < expressionArray.length; i++) {
// System.out.println(expressionArray[i]);
// 如果是操作数
if (stackforoper.isOper(expressionArray[i])) {
if (stackforoper.isEmpty()
|| stackforoper.priority(expressionArray[i]) > stackforoper.priority(stackforoper.peek())) {
stackforoper.push(expressionArray[i]);
} else {
int n1 = stackfornum.pop();
int n2 = stackfornum.pop();
int oper = (int) stackforoper.pop();
int result = stackfornum.cal(n2, n1, oper);
stackfornum.push(result);
stackforoper.push(expressionArray[i]);
}
} else if ((i + 1) < (expressionArray.length - 1) && stackforoper.isOper(expressionArray[i + 1])
|| (i + 1) == expressionArray.length) {
keepnums = keepnums * 10 + (expressionArray[i] - '0');
stackfornum.push(keepnums);
keepnums = 0;
} else {
keepnums = keepnums * 10 + (expressionArray[i] - '0');
}
}
while (true) {
// 如果符号栈为空,则计算到最后的结果, 数栈中只有一个数字【结果】
if (stackforoper.isEmpty()) {
break;
}
int num1 = stackfornum.pop();
int num2 = stackfornum.pop();
int oper = stackforoper.pop();
int res = stackfornum.cal(num2, num1, oper);
stackfornum.push(res);// 入栈
}
System.out.println("计算结果为");
System.out.println(stackfornum.peek());
}
}
class ArrayStackForCal {
private int[] array;
private int top = -1;
private int maxSize;
private static final int DEAFAULT_MAX_SIZE = 10;
public ArrayStackForCal() {
this(DEAFAULT_MAX_SIZE);
}
public ArrayStackForCal(int maxSize) {
this.maxSize = maxSize;
array = new int[maxSize];
}
public int peek() {
if (isEmpty()) {
throw new RuntimeException("栈为空。");
}
return array[top];
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == maxSize - 1;
}
public boolean push(int x) {
if (isFull()) {
System.out.println("栈已满。");
return false;
}
array[++top] = x;
return true;
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈为空。");
}
return array[top--];
}
public void list() {
if (isEmpty()) {
System.out.println("栈为空。");
return;
}
for (int i = 0; i < array.length; i++) {
System.out.printf("array[%d]=%d", i, array[i]);
}
}
public int priority(int oper) {
if (oper == '*' || oper == '/') {
return 1;
} else if (oper == '+' || oper == '-') {
return 0;
} else
return -1;
}
public boolean isOper(char var) {
return var == '+' || var == '-' || var == '*' || var == '/';
}
public int cal(int num1, int num2, int oper) {
int result = 0;
switch (oper) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
return result;
}
}