![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7e03c7394453cb8fd7504bf481a17f92.png)
package logic;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
import static java.lang.System.in;
public class LISPLikeOperation {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
String str = bf.readLine();
bf.close();
Deque<String> operationStack = new LinkedList<>();
Deque<Integer> numsStack = new LinkedList<>();
String res = "";
for (int i = 0; i < str.length(); ) {
if ('(' == str.charAt(i)) {
i = i + 1;
String opera = str.substring(i, i + 3);
operationStack.push(opera);
i = i + 3;
} else if (')' == str.charAt(i)) {
i = i + 1;
res = cal(operationStack, numsStack);
if ("error".equals(res)) {
break;
}
} else {
if (' ' == str.charAt(i)) {
i = i + 1;
} else {
int temp = i;
while (Character.isDigit(str.charAt(i)) || '-' == str.charAt(i)) {
i = i + 1;
}
String num = str.substring(temp, i);
numsStack.push(Integer.parseInt(num));
}
}
}
if ("success".equals(res)) {
System.out.println(numsStack.pop());
} else {
System.out.println(res);
}
}
public static String cal(Deque<String> operationStack, Deque<Integer> numsStack) {
Integer popLast = numsStack.pop();
Integer popFirst = numsStack.pop();
String operation = operationStack.pop();
if ("add".equals(operation)) {
numsStack.push(popFirst + popLast);
} else if ("sub".equals(operation)) {
numsStack.push(popFirst - popLast);
} else if ("mul".equals(operation)) {
numsStack.push(popFirst * popLast);
} else if ("div".equals(operation)) {
if (popLast == 0) {
return "error";
}
numsStack.push(popFirst / popLast);
}
return "success";
}
}