gpt4 book ai didi

java - 应用在 java 中作为字符串找到的运算符的最优雅方法?

转载 作者:搜寻专家 更新时间:2023-10-31 08:05:04 25 4
gpt4 key购买 nike

潜在的愚蠢:假设我有一个包含运算符的字符串,应用此运算符的最佳方法是什么?

我倾向于做的是:

if(n.getString(1).equals("<<")) {
result = tmp1 << tmp2;
}

对于我拥有的每种运算符(operator)。有没有更好的办法 ?

最佳答案

不确定你是否会称之为优雅,但这是一种方式:

interface Operation {
int apply(int a, int b);
}

Map<String, Operation> operations = new HashMap<String, Operation>() {{
put("+", new Operation() { public int apply(int a, int b) { return a + b; }});
put("-", new Operation() { public int apply(int a, int b) { return a - b; }});
put("*", new Operation() { public int apply(int a, int b) { return a * b; }});
put("<<", new Operation() { public int apply(int a, int b) { return a << b; }});
// some more operations here
}};

然后您可以将 if 语句替换为:

result = operations.get(n.getString(1)).apply(tmp1, tmp2);

关于java - 应用在 java 中作为字符串找到的运算符的最优雅方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2960826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com