java用map实现计算器计算
时间: 2023-07-12 08:33:54 浏览: 49
可以使用 Java 中的 Map 来实现计算器计算。具体思路如下:
1. 将所有操作符和对应的操作方法存储在 Map 中。
2. 将表达式转换为后缀表达式,并使用栈来计算后缀表达式。
下面是示例代码:
```java
import java.util.*;
public class Calculator {
private static final Map<String, BiFunction<Double, Double, Double>> OPERATIONS = new HashMap<>();
static {
OPERATIONS.put("+", (a, b) -> a + b);
OPERATIONS.put("-", (a, b) -> a - b);
OPERATIONS.put("*", (a, b) -> a * b);
OPERATIONS.put("/", (a, b) -> a / b);
}
public static void main(String[] args) {
String expression = "2 + 3 * 4 - 5 / 2";
List<String> postfix = toPostfix(expression);
double result = evaluatePostfix(postfix);
System.out.println(result);
}
// 将中缀表达式转换为后缀表达式
private static List<String> toPostfix(String expression) {
List<String> postfix = new ArrayList<>();
Stack<String> stack = new Stack<>();
String[] tokens = expression.split("\\s+");
for (String token : tokens) {
if (isNumber(token)) {
postfix.add(token);
} else if (OPERATIONS.containsKey(token)) {
while (!stack.isEmpty() &&
!stack.peek().equals("(") &&
hasHigherPrecedence(stack.peek(), token)) {
postfix.add(stack.pop());
}
stack.push(token);
} else if (token.equals("(")) {
stack.push(token);
} else if (token.equals(")")) {
while (!stack.isEmpty() && !stack.peek().equals("(")) {
postfix.add(stack.pop());
}
stack.pop();
}
}
while (!stack.isEmpty()) {
postfix.add(stack.pop());
}
return postfix;
}
// 判断是否为数字
private static boolean isNumber(String token) {
try {
Double.parseDouble(token);
return true;
} catch (NumberFormatException e) {
return false;
}
}
// 判断操作符优先级
private static boolean hasHigherPrecedence(String op1, String op2) {
return !op1.equals("(") && !op2.equals(")") &&
(op1.equals("*") || op1.equals("/")) &&
(op2.equals("+") || op2.equals("-"));
}
// 计算后缀表达式
private static double evaluatePostfix(List<String> postfix) {
Stack<Double> stack = new Stack<>();
for (String token : postfix) {
if (isNumber(token)) {
stack.push(Double.parseDouble(token));
} else if (OPERATIONS.containsKey(token)) {
double b = stack.pop();
double a = stack.pop();
stack.push(OPERATIONS.get(token).apply(a, b));
}
}
return stack.pop();
}
}
```