java后缀表达式求值
时间: 2023-11-20 12:59:05 浏览: 83
Java中求后缀表达式的值可以通过栈来实现。具体步骤如下:
1.将后缀表达式转换为字符串数组。
2.遍历字符串数组,如果当前元素是数字,则将其压入栈中;如果当前元素是运算符,则从栈中弹出两个元素进行运算,并将结果压入栈中。
3.遍历完字符串数组后,栈中只剩下一个元素,即为后缀表达式的值。
下面是一个Java求后缀表达式的例子:
```java
import java.util.Stack;
public class PostfixExpression {
public static void main(String[] args) {
String[] postfix = {"3", "4", "5", "*", "+"};
float result = evaluatePostfix(postfix);
System.out.println("The value of the postfix expression is: " + result);
}
public static float evaluatePostfix(String[] postfix) {
Stack<Float> stack = new Stack<Float>();
for (int i = 0; i < postfix.length; i++) {
String token = postfix[i];
if (isOperator(token)) {
float operand2 = stack.pop();
float operand1 = stack.pop();
float result = applyOperator(token, operand1, operand2);
stack.push(result);
} else {
float operand = Float.parseFloat(token);
stack.push(operand);
}
}
return stack.pop();
}
public static boolean isOperator(String token) {
return token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/");
}
public static float applyOperator(String operator, float operand1, float operand2) {
if (operator.equals("+")) {
return operand1 + operand2;
} else if (operator.equals("-")) {
return operand1 - operand2;
} else if (operator.equals("*")) {
return operand1 * operand2;
} else {
return operand1 / operand2;
}
}
}
```
阅读全文