在这里插入代码片
import java.util.Stack;
public class ExpressionCalculator {
public static double calculateExpression(String expression) {
// 创建运算符栈和操作数栈
Stack operatorStack = new Stack<>();
Stack operandStack = new Stack<>();
for (int i = 0; i < expression.length(); i++) {
char ch = expression.charAt(i);
// 忽略空格
if (ch == ' ') {
continue;
}
// 如果是数字,则解析整个数字并将结果入操作数栈
if (Character.isDigit(ch) || ch == '.') {
StringBuilder sb = new StringBuilder();
while (i < expression.length() && (Character.isDigit(expression.charAt(i)) || expression.charAt(i) == '.')) {
sb.append(expression.charAt(i));
i++;
}
i--;
double num = Double.parseDouble(sb.toString());
operandStack.push(num);
} else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
// 如果是运算符,则判断运算符栈是否为空
if (!operatorStack.isEmpty()) {
char topOperator = operatorStack.peek();
// 当前运算符的优先级小于等于栈顶运算符的优先级时,进行计算
while (isOperator(topOperator) && comparePrecedence(ch, topOperator) <= 0) {
operatorStack.pop();
double operand2 = operandStack.pop();
double operand1 = operandStack.pop();
double result = applyOperator(topOperator, operand1, operand2);
operandStack.push(result);
if (!operatorStack.isEmpty()) {
topOperator = operatorStack.peek();
} else {
break;
}
}
}
// 将当前运算符入运算符栈
operatorStack.push(ch);
}
}
// 处理剩余的运算符
while (!operatorStack.isEmpty()) {
char operator = operatorStack.pop();
double operand2 = operandStack.pop();
double operand1 = operandStack.pop();
double result = applyOperator(operator, operand1, operand2);
operandStack.push(result);
}
// 返回最终结果
return operandStack.pop();
}
// 判断字符是否为运算符
private static boolean isOperator(char ch) {
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
// 比较两个运算符的优先级
private static int comparePrecedence(char op1, char op2) {
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) {
return 1;
} else if ((op1 == '+' || op1 == '-') && (op2 == '*' || op2 == '/')) {
return -1;
} else {
return 0;
}
}
// 应用运算符到操作数上
private static double applyOperator(char operator, double operand1, double operand2) {
switch (operator) {
case '+':
return operand1 + operand2;
case '-':
return operand1 - operand2;
case '*':
return operand1 * operand2;
case '/':
return operand1 / operand2;
default