要求解一个算术表达式的值,可以使用栈来实现。具体步骤如下:
以下是一个示例代码:
import java.util.Stack;
public class ExpressionEvaluation {
public static double evaluateExpression(String expression) {
Stack<Character> operatorStack = new Stack<>();
Stack<Double> numberStack = new Stack<>();
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
if (c == ' ') {
continue;
} else if (Character.isDigit(c)) {
StringBuilder sb = new StringBuilder();
while (i < expression.length() && (Character.isDigit(expression.charAt(i)) || expression.charAt(i) == '.')) {
sb.append(expression.charAt(i));
i++;
}
i--;
double number = Double.parseDouble(sb.toString());
numberStack.push(number);
} else if (c == '(') {
operatorStack.push(c);
} else if (c == ')') {
while (!operatorStack.isEmpty() && operatorStack.peek() != '(') {
char operator = operatorStack.pop();
double operand2 = numberStack.pop();
double operand1 = numberStack.pop();
double result = applyOperator(operator, operand1, operand2);
numberStack.push(result);
}
operatorStack.pop(); // 弹出左括号
} else if (isOperator(c)) {
while (!operatorStack.isEmpty() && operatorStack.peek() != '(' && getPrecedence(c) <= getPrecedence(operatorStack.peek())) {
char operator = operatorStack.pop();
double operand2 = numberStack.pop();
double operand1 = numberStack.pop();
double result = applyOperator(operator, operand1, operand2);
numberStack.push(result);
}
operatorStack.push(c);
}
}
while (!operatorStack.isEmpty()) {
char operator = operatorStack.pop();
double operand2 = numberStack.pop();
double operand1 = numberStack.pop();
double result = applyOperator(operator, operand1, operand2);
numberStack.push(result);
}
return numberStack.pop();
}
private static boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
private static int getPrecedence(char operator) {
if (operator == '+' || operator == '-') {
return 1;
} else if (operator == '*' || operator == '/') {
return 2;
} 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 operand