给定一个四则运算(带括号表达式)加减乘除由+ - * /表示,求运算结果

import java.util.Scanner;
import java.util.Stack;

public class Main {

/**
* 将数字放入栈中,如果栈顶有乘除,则结算乘除
*
* @param stack
* @param num
*/
private static void pushNumToStack(Stack<String> stack, int num) {
if (!stack.isEmpty() && "*".equals(stack.peek())) {
stack.pop();
stack.push(String.valueOf(Integer.parseInt(stack.pop()) * num));
} else if (!stack.isEmpty() && "/".equals(stack.peek())) {
stack.pop();
stack.push(String.valueOf(Integer.parseInt(stack.pop()) / num));
} else {
stack.push(String.valueOf(num));
}
}

/**
* 由于将数字放入栈时已经结算乘除,所以此时栈中只有加减
*
* @param stack
* @return
*/
private static int calcStack(Stack<String> stack) {
while (stack.size() >= 3) {
int two = Integer.parseInt(stack.pop());
String op = stack.pop();
int one = Integer.parseInt(stack.pop());
if ("-".equals(op)) {
stack.push(String.valueOf(one - two));
} else {
stack.push(String.valueOf(one + two));
}
}
return Integer.parseInt(stack.pop());
}

private static int[] calc(char[] str, int index) {
Stack<String> stack = new Stack<>();

int num = 0;
while (index < str.length && str[index] != ')') {
if (str[index] >= '0' && str[index] <= '9') {
num = num * 10 + str[index++] - '0';
} else if (str[index] == '(') {
int[] next = calc(str, index + 1);
num = next[0];
index = next[1] + 1;
} else {
pushNumToStack(stack, num);
num = 0;
stack.push(String.valueOf(str[index++]));
}
}
pushNumToStack(stack, num);
return new int[]{calcStack(stack), index};
}

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String str = in.next();
System.out.println(calc(str.toCharArray(), 0)[0]);
}
}
}


心之所向,素履以往 生如逆旅,一苇以航