java中缀表达式求值
时间: 2023-12-31 16:24:13 浏览: 30
以下是Java中缀表达式求值的示例代码:
```java
import java.util.Stack;
public class InfixExpressionEvaluation {
public static int evaluateInfixExpression(String expression) {
Stack<Integer> operandStack = new Stack<>();
Stack<Character> operatorStack = new Stack<>();
for (int i = 0; i < expression.length(); i++) {
char ch = expression.charAt(i);
if (Character.isDigit(ch)) {
StringBuilder num = new StringBuilder();
while (i < expression.length() && Character.isDigit(expression.charAt(i))) {
num.append(expression.charAt(i));
i++;
}
i--;
operandStack.push(Integer.parseInt(num.toString()));
} else if (ch == '(') {
operatorStack.push(ch);
} else if (ch == ')') {
while (!operatorStack.isEmpty() && operatorStack.peek() != '(') {
int result = performOperation(operatorStack.pop(), operandStack.pop(), operandStack.pop());
operandStack.push(result);
}
operatorStack.pop();
} else if (isOperator(ch)) {
while (!operatorStack.isEmpty() && precedence(ch) <= precedence(operatorStack.peek())) {
int result = performOperation(operatorStack.pop(), operandStack.pop(), operandStack.pop());
operandStack.push(result);
}
operatorStack.push(ch);
}
}
while (!operatorStack.isEmpty()) {
int result = performOperation(operatorStack.pop(), operandStack.pop(), operandStack.pop());
operandStack.push(result);
}
return operandStack.pop();
}
public static boolean isOperator(char ch) {
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
public static int precedence(char ch) {
if (ch == '+' || ch == '-') {
return 1;
} else if (ch == '*' || ch == '/') {
return 2;
}
return 0;
}
public static int performOperation(char operator, int operand2, int operand1) {
switch (operator) {
case '+':
return operand1 + operand2;
case '-':
return operand1 - operand2;
case '*':
return operand1 * operand2;
case '/':
if (operand2 == 0) {
throw new UnsupportedOperationException("Cannot divide by zero");
}
return operand1 / operand2;
}
return 0;
}
public static void main(String[] args) {
String expression = "1 + 2 * 3";
int result = evaluateInfixExpression(expression);
System.out.println("Result: " + result); // 输出:7
}
}
```