public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String next = sc.next();
//转成中缀表达式
List<String> list = toZhongZhui(next);
//转成后缀表达式
List<String> list1 = toHouZhui(list);
//计算结果
int result = getResult(list1);
System.out.println(result);
}
/**
* 功能描述:将输入的字符串转化为中缀表达式
*
* @param str
* @return java.util.List<java.lang.String>
* @Author zl
* @Date 2022/3/17
**/
public static List<String> toZhongZhui(String str) {
List<String> list = new ArrayList<>();
int i = 0;
StringBuilder sb;
char ch;
do {
if ((ch = str.charAt(i)) < '0' || (ch = str.charAt(i)) > '9') {
list.add(String.valueOf(ch));
i++;
} else {
//若为数字考虑两位或者三位数字
sb = new StringBuilder();
while (i < str.length() && (ch = str.charAt(i)) >= '0' && (ch = str.charAt(i)) <= '9') {
sb.append(ch);
i++;
}
list.add(sb.toString());
}
} while (i < str.length());
return list;
}
/**
* 功能描述:将中缀表达式转化为后缀表达式
* @Author zl
* @Date 2022/3/18
* @param list
* @return java.util.List<java.lang.String>
**/
public static List<String> toHouZhui(List<String> list) {
Stack<String> stack = new Stack<>();
List<String> res = new ArrayList<>();
for (String s : list) {
if (s.matches("\\d+")) {
res.add(s);
} else if (s.equals("(")) {
stack.push(s);
} else if (s.equals(")")) {
//当是“)”时2弹出“(”前的所有符号
while (!stack.peek().equals("(")) {
res.add(stack.pop());
}
stack.pop();
} else {
//根据运算符与栈顶的运算符作比较栈顶的优先级高则输出
while (!stack.isEmpty() && Operation.getValue(stack.peek()) >= Operation.getValue(s)) {
res.add(stack.pop());
}
stack.push(s);
}
}
while (!stack.isEmpty()) {
res.add(stack.pop());
}
return res;
}
/**
* 功能描述:根据后缀表达式计算数值
*
* @param list
* @return int
* @Author zl
* @Date 2022/3/18
**/
public static int getResult(List<String> list) {
Stack<Integer> stack = new Stack<>();
int a, b;
for (String s : list) {
if (s.matches("\\d+")) {
stack.push(Integer.valueOf(s));
} else {
if (s.equals("+")) {
a = stack.pop();
b = stack.pop();
stack.push(b + a);
} else if (s.equals("-")) {
a = stack.pop();
b = stack.pop();
stack.push(b - a);
} else if (s.equals("*")) {
a = stack.pop();
b = stack.pop();
stack.push(b * a);
} else {
a = stack.pop();
b = stack.pop();
stack.push(b / a);
}
}
}
return stack.pop();
}
/**
* @Author zl
* @Date 2022/3/18
* @Description 运算符的有限级
*/
public class Operation {
private static final int ADD = 1;
private static final int SUB = 1;
private static final int MuL = 2;
private static final int DIV = 2;
public static int getValue(String operation) {
int result = 0;
switch (operation) {
case "+":
result = ADD;
break;
case "-":
result = SUB;
break;
case "*":
result = MuL;
break;
case "/":
result = DIV;
break;
}
return result;
}
}