要求解一個算術表達式的值,可以使用棧來實現。具體步驟如下:
以下是一個示例代碼:
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