用Java写出:字符串表达式求值
时间: 2023-08-15 19:29:38 浏览: 53
好的,以下是Java实现字符串表达式求值的代码:
```java
import java.util.Stack;
public class ExpressionEvaluation {
public static int evaluate(String expression) {
Stack<Integer> operands = new Stack<>();
Stack<Character> operators = new Stack<>();
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
if (c == ' ') {
continue;
} else if (Character.isDigit(c)) {
int num = 0;
while (i < expression.length() && Character.isDigit(expression.charAt(i))) {
num = num * 10 + (expression.charAt(i) - '0');
i++;
}
i--;
operands.push(num);
} else if (c == '(') {
operators.push(c);
} else if (c == ')') {
while (operators.peek() != '(') {
int result = applyOperator(operators.pop(), operands.pop(), operands.pop());
operands.push(result);
}
operators.pop();
} else {
while (!operators.isEmpty() && precedence(c) <= precedence(operators.peek())) {
int result = applyOperator(operators.pop(), operands.pop(), operands.pop());
operands.push(result);
}
operators.push(c);
}
}
while (!operators.isEmpty()) {
int result = applyOperator(operators.pop(), operands.pop(), operands.pop());
operands.push(result);
}
return operands.pop();
}
private static int precedence(char operator) {
if (operator == '+' || operator == '-') {
return 1;
} else if (operator == '*' || operator == '/') {
return 2;
} else {
return 0;
}
}
private static int applyOperator(char operator, int b, int a) {
switch (operator) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0) {
throw new ArithmeticException("Division by zero");
}
return a / b;
default:
throw new IllegalArgumentException("Invalid operator: " + operator);
}
}
}
```
以上代码实现了一个静态方法evaluate,接收一个字符串表达式作为参数,返回表达式的计算结果。在方法内部,我们使用两个栈,一个用于存储操作数,一个用于存储运算符。然后遍历表达式中的每个字符,如果是空格,则跳过,如果是数字,则将数字解析出来并压入操作数栈中,如果是左括号,则将其压入运算符栈中,如果是右括号,则不断弹出运算符栈中的运算符,直到遇到左括号,同时将弹出的运算符和操作数进行计算,并将计算结果压入操作数栈中。如果是运算符,则不断弹出运算符栈中的运算符,直到栈顶运算符的优先级低于当前运算符的优先级,同时将弹出的运算符和操作数进行计算,并将计算结果压入操作数栈中。最后,当表达式遍历完成后,不断弹出运算符栈中的运算符,同时将弹出的运算符和操作数进行计算,并将计算结果压入操作数栈中,直到运算符栈为空。最后,操作数栈中只剩一个元素,这个元素就是表达式的计算结果。