我正在尝试通过BinaryOperator功能接口替换用于算术运算的公共开关.
基本方法是:
private static int computeOne(int res, String operand, String operation) {
int number = Integer.parseInt(operand);
switch (operation) {
case "+":
res += number;
break;
case "-":
res -= number;
break;
case "*":
res *= number;
break;
case "/":
res = (number != 0 ? res / number : Integer.MAX_VALUE);
break;
default:
res = 0;
System.out.println("unknown operation");
}
return res;
}
Run Code Online (Sandbox Code Playgroud)
据我所知,编写类似的内容是必要的:
BinaryOperator<Integer> action = (a,b) -> computeExpression(a + operation + b);
action.apply(res, operand);
Run Code Online (Sandbox Code Playgroud)
但我不明白如何避免switch与computeExpression …