是的,你可以使用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()
,并在計算時進行相應的類型轉換。