是的,你可以使用Java的Stack
类来实现表达式求值。这里是一个简单的例子,展示了如何使用Stack
类实现中缀表达式到后缀表达式(逆波兰表示法)的转换以及计算后缀表达式的值:
import java.util.Stack;
import java.util.StringTokenizer;
public class ExpressionEvaluator {
public static void main(String[] args) {
String expression = "3 + 4 * 2 / ( 1 - 5 ) ^ 2";
String postfix = convertToPostfix(expression);
int result = evaluatePostfix(postfix);
System.out.println("Result: " + result);
}
public static String convertToPostfix(String expression) {
Stack<String> stack = new Stack<>();
StringTokenizer tokenizer = new StringTokenizer(expression);
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (isOperator(token)) {
String topOperand = stack.pop();
String secondOperand = stack.pop();
String result = performOperation(topOperand, secondOperand, token);
stack.push(result);
} else {
stack.push(token);
}
}
return stack.pop();
}
public static int evaluatePostfix(String postfix) {
Stack<Integer> stack = new Stack<>();
for (String token : postfix.split(" ")) {
int operand = Integer.parseInt(token);
stack.push(operand);
}
return stack.pop();
}
public static boolean isOperator(String token) {
return token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/") || token.equals("^");
}
public static String performOperation(String operand1, String operand2, String operator) {
int num1 = Integer.parseInt(operand1);
int num2 = Integer.parseInt(operand2);
switch (operator) {
case "+":
return String.valueOf(num1 + num2);
case "-":
return String.valueOf(num1 - num2);
case "*":
return String.valueOf(num1 * num2);
case "/":
return String.valueOf(num1 / num2);
case "^":
return String.valueOf(Math.pow(num1, num2));
default:
throw new IllegalArgumentException("Invalid operator: " + operator);
}
}
}
这个例子中,我们首先将中缀表达式转换为后缀表达式,然后计算后缀表达式的值。注意,这个例子仅支持整数运算,如果你需要支持浮点数运算,可以将Integer.parseInt()
替换为Double.parseDouble()
,并在计算时进行相应的类型转换。