java计算表达式值 使用栈
时间: 2024-02-07 16:39:23 浏览: 19
在Java中,可以使用栈来计算表达式的值。具体步骤如下:
1. 创建一个操作数栈和一个操作符栈。
2. 将表达式字符串转换为字符数组,并遍历每个字符。
3. 如果当前字符是数字,则将它转换为一个操作数,并将其压入操作数栈。
4. 如果当前字符是操作符,则将其压入操作符栈。
5. 如果当前字符是右括号,则弹出操作符栈顶的操作符和操作数栈顶的两个操作数,计算它们的值,将结果压入操作数栈。
6. 最后,当表达式遍历完毕后,将操作符栈和操作数栈中的元素依次弹出,按照操作符的优先级计算表达式的值。
下面是一个示例代码:
```java
import java.util.Stack;
public class Calculator {
public static int calculate(String expression) {
Stack<Integer> operandStack = new Stack<>();
Stack<Character> operatorStack = new Stack<>();
char[] tokens = expression.toCharArray();
for (int i = 0; i < tokens.length; i++) {
if (Character.isDigit(tokens[i])) {
StringBuilder sb = new StringBuilder();
while (i < tokens.length && Character.isDigit(tokens[i])) {
sb.append(tokens[i++]);
}
i--;
operandStack.push(Integer.parseInt(sb.toString()));
} else if (tokens[i] == '(') {
operatorStack.push(tokens[i]);
} else if (tokens[i] == ')') {
while (operatorStack.peek() != '(') {
char operator = operatorStack.pop();
int operand2 = operandStack.pop();
int operand1 = operandStack.pop();
operandStack.push(applyOperator(operator, operand1, operand2));
}
operatorStack.pop(); // Pop the left parenthesis.
} else if (isOperator(tokens[i])) {
while (!operatorStack.isEmpty() && hasPrecedence(tokens[i], operatorStack.peek())) {
char operator = operatorStack.pop();
int operand2 = operandStack.pop();
int operand1 = operandStack.pop();
operandStack.push(applyOperator(operator, operand1, operand2));
}
operatorStack.push(tokens[i]);
}
}
while (!operatorStack.isEmpty()) {
char operator = operatorStack.pop();
int operand2 = operandStack.pop();
int operand1 = operandStack.pop();
operandStack.push(applyOperator(operator, operand1, operand2));
}
return operandStack.pop();
}
private static boolean isOperator(char ch) {
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
private static int applyOperator(char operator, int operand1, int operand2) {
switch (operator) {
case '+':
return operand1 + operand2;
case '-':
return operand1 - operand2;
case '*':
return operand1 * operand2;
case '/':
return operand1 / operand2;
default:
throw new IllegalArgumentException("Unknown operator: " + operator);
}
}
private static boolean hasPrecedence(char operator1, char operator2) {
if (operator2 == '(' || operator2 == ')') {
return false;
}
if ((operator1 == '*' || operator1 == '/') && (operator2 == '+' || operator2 == '-')) {
return false;
}
return true;
}
}
```
可以使用以下代码测试:
```java
String expression = "2 * (3 + 4) - 5 / 2";
int result = Calculator.calculate(expression);
System.out.println(expression + " = " + result); // Output: 2 * (3 + 4) - 5 / 2 = 12
```