import java.util.Stack;
public class Calculator {
public static void main(String[] args) {
String s = " 11 +2*((30 -6/3- 4)*6) -5";
System.out.println(calculate(s));
}
public static int calculate(String s) {
Stack<String> stack = new Stack<>();
String[] postfix = infixToPostfix(format(s));
for (String element : postfix) {
if (isDigit(element)) stack.push(element);
else {
String num2 = stack.pop();
String num1 = stack.pop();
stack.push(operate(num1, num2, element));
}
}
return Integer.parseInt(stack.pop());
} //计算表达式
public static String operate(String s1, String s2, String operator) {
int num1 = Integer.parseInt(s1);
int num2 = Integer.parseInt(s2);
switch (operator) {
case "+":
return num1 + num2 + "";
case "-":
return num1 - num2 + "";
case "*":
return num1 * num2 + "";
case "/":
return num1 / num2 + "";
}
return null;
} //进行四则运算
public static String[] format(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch >= '0' && ch <= '9') {
sb.append(ch);
} else {
sb.append(' ');
sb.append(ch);
sb.append(' ');
}
}
return sb.toString().split("\\s+");
} //格式化字符串
public static String[] infixToPostfix(String[] infix) {
StringBuilder postfix = new StringBuilder();
Stack<String> opStack = new Stack<>();
for (String s : infix) {
if (isDigit(s)) postfix.append(s).append(" ");
else if (s.equals("(")) opStack.push(s);
else if (s.equals(")")) {
while (!opStack.peek().equals("(")) {
postfix.append(opStack.pop()).append(" ");
}
opStack.pop();
}
else {
while (!opStack.isEmpty() && priority(s) <= priority(opStack.peek())) {
postfix.append(opStack.pop()).append(" ");
}
opStack.push(s);
}
}
return postfix.append(opStack.pop()).toString().split("\\s+");
} //中缀转后缀
public static boolean isDigit(String s) {
try {
Integer.parseInt(s);
return true;
} catch (Exception e) {
return false;
}
} //判断是否为数字
public static int priority(String s) {
switch (s) {
case "+":
case "-":
return 1;
case "*":
case "/":
return 2;
default:
return 0;
}
} //判定运算符优先级
}
栈结构+逆波兰式实现四则运算
最新推荐文章于 2024-07-08 00:01:13 发布