使用java书写一个函数,他的功能是中缀表达式转后缀表达式,并且计算最后结果,包含小数
时间: 2024-04-22 22:24:19 浏览: 72
好的,以下是一个使用Java编写的函数,实现中缀表达式转后缀表达式并计算最后结果,包含小数的情况:
```java
import java.util.*;
public class InfixToPostfixCalculator {
public static double calculate(String expression) {
// 定义运算符的优先级
Map<Character, Integer> precedence = new HashMap<>();
precedence.put('+', 1);
precedence.put('-', 1);
precedence.put('*', 2);
precedence.put('/', 2);
List<String> postfix = new ArrayList<>(); // 存储后缀表达式
Stack<Character> stack = new Stack<>(); // 运算符栈
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
if (Character.isDigit(c) || c == '.') {
StringBuilder num = new StringBuilder();
while (i < expression.length() && (Character.isDigit(expression.charAt(i)) || expression.charAt(i) == '.')) {
num.append(expression.charAt(i));
i++;
}
postfix.add(num.toString());
i--;
} else if (c == '(') {
stack.push(c);
} else if (c == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
postfix.add(stack.pop().toString());
}
stack.pop(); // 弹出左括号
} else if (c == '+' || c == '-' || c == '*' || c == '/') {
while (!stack.isEmpty() && stack.peek() != '(' && precedence.get(c) <= precedence.get(stack.peek())) {
postfix.add(stack.pop().toString());
}
stack.push(c);
}
}
while (!stack.isEmpty()) {
postfix.add(stack.pop().toString());
}
Stack<Double> operandStack = new Stack<>();
for (String token : postfix) {
if (token.matches("\\d+(\\.\\d+)?")) {
operandStack.push(Double.parseDouble(token));
} else {
double num2 = operandStack.pop();
double num1 = operandStack.pop();
if (token.equals("+")) {
operandStack.push(num1 + num2);
} else if (token.equals("-")) {
operandStack.push(num1 - num2);
} else if (token.equals("*")) {
operandStack.push(num1 * num2);
} else if (token.equals("/")) {
operandStack.push(num1 / num2);
}
}
}
return operandStack.pop();
}
}
```
您可以调用 `calculate` 方法,并将中缀表达式作为参数传入。方法将返回计算结果。例如:
```java
String expression = "3 + 4 * 2 / ( 1 - 5 )";
double result = InfixToPostfixCalculator.calculate(expression);
System.out.println(result); // 输出结果为 1.0
```
请注意,以上代码只支持单个数字的计算,如果需要支持多位数的计算,需要对输入表达式进行解析和拼接。
阅读全文