中缀表达式实现多位数加减乘除
package dataStructure;
public class Calculator {
public static void main(String[] args) {
String express = "30+2*3-2+4/2";
ArrayStack2 numberStack = 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 = express.substring(index, index + 1).charAt(0);
if (operStack.isOper(ch)) {
if (!operStack.isEmpty()) {
if (operStack.priority(ch) <= operStack.priority(operStack.peek())) {
num1 = numberStack.pop();
num2 = numberStack.pop();
oper = operStack.pop();
res = numberStack.cal(num1, num2, oper);
numberStack.push(res);
operStack.push(ch);
} else {
operStack.push(ch);
}
} else {
operStack.push(ch);
}
} else {
keepNum += ch;
if (index == express.length() - 1) {
numberStack.push(Integer.parseInt(keepNum));
} else {
if (operStack.isOper(express.substring(index + 1, index + 2).charAt(0))) {
numberStack.push(Integer.parseInt(keepNum));
keepNum = "";
}
}
}
index++;
if (index == express.length()) {
break;
}
}
while (true) {
if (operStack.isEmpty()) {
break;
}
num1 = numberStack.pop();
num2 = numberStack.pop();
oper = operStack.pop();
res = numberStack.cal(num1, num2, oper);
numberStack.push(res);
}
System.out.printf("表达式 %s = %d", express, numberStack.pop());
}
}
class ArrayStack2 {
private int maxSize;
private int[] myStack;
private int top = -1;
public ArrayStack2(int maxSize) {
this.maxSize = maxSize;
myStack = new int[this.maxSize];
}
public boolean isEmpty() {
return top == -1;
}
public int peek() {
return myStack[top];
}
public boolean isFull() {
return top == maxSize - 1;
}
public void list() {
if (isEmpty()) {
System.out.println("栈空,没有数据~~~~~");
return;
}
for (int i = top; i >= 0; i--) {
System.out.printf("stack[%d]=%d\n", i, myStack[i]);
}
}
public void push(int value) {
if (isFull()) {
System.out.println("栈已满");
return;
}
top++;
myStack[top] = value;
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈空,没有数据~~~~~~~~");
}
int result = myStack[top];
top--;
return result;
}
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;
}
}