您是否坚持将操作应用于参数?
最简单的方法:
if ("+".equals(operator)) {
result = arg1 + arg2;
} else if ...
System.out.println("See, " + arg1 + operator + arg2 " = " + result);
一种使用哈希表而不是无限的更可扩展的方式if
:
import java.util.*;
// Poor man's first-class function
interface BinaryOp {
int apply(int arg1, int arg2);
}
final static BinaryOp ADD = new BinaryOp() {
public int apply(int arg1, int arg2) { return arg1 + arg2; }
}
final static BinaryOp SUBTRACT = new BinaryOp() {
public int apply(int arg1, int arg2) { return arg1 - arg2; }
}
final static BinaryOp MULTIPLY = new BinaryOp() {
public int apply(int arg1, int arg2) { return arg1 * arg2; }
}
static final Map<String, BinaryOp> OPERATIONS = new HashMap<String, BinaryOp>();
// This replaces the 'if', easier to extend.
static {
OPERATIONS.put("+", ADD);
OPERATIONS.put("-", SUBTRACT);
OPERATIONS.put("*", MULTIPLY);
}
public static void main(String[] args) {
...
BinaryOp operation = OPERATIONS.get(operation_name);
int result = operation.apply(arg1, arg2);
...
}
如果您认为这是不必要的长,那就是。类似这样的东西仍然是 Java 领域的典型模式。(这就是 Scala 存在的原因,但这是另一回事。)
这甚至不涉及操作优先级或括号。