假设有一个ENUM
enum Operations {
ADD,
SUBTRACT,
MULTIPLY
}
我想使用这个枚举添加两个数字(比如5和3)并将输出设为8 要么 我想用这个枚举减去两个数字(比如9和3)并得到输出为6
问题:
答案 0 :(得分:20)
enum
可以有抽象方法,每个成员都可以用不同的方式实现它。
enum Operations {
ADD {
public double apply(double a, double b) { return a + b; }
},
SUBTRACT {
public double apply(double a, double b) { return a - b; }
},
MULTIPLY {
public double apply(double a, double b) { return a * b; }
},
;
public abstract double apply(double a, double b);
}
允许你这样做
Operations op = ...;
double result = op.apply(3, 5);
答案 1 :(得分:5)
如何使用JAVA 8功能:
enum Operation implements DoubleBinaryOperator {
PLUS ("+", (l, r) -> l + r),
MINUS ("-", (l, r) -> l - r),
MULTIPLY("*", (l, r) -> l * r),
DIVIDE ("/", (l, r) -> l / r);
private final String symbol;
private final DoubleBinaryOperator binaryOperator;
private Operation(final String symbol, final DoubleBinaryOperator binaryOperator) {
this.symbol = symbol;
this.binaryOperator = binaryOperator;
}
public String getSymbol() {
return symbol;
}
@Override
public double applyAsDouble(final double left, final double right) {
return binaryOperator.applyAsDouble(left, right);
}
}
答案 2 :(得分:4)
您可以在枚举值上使用开关:
switch (operator) {
case ADD:
ret = a + b;
break;
case SUBTRACT:
ret = a - b;
break;
case MULTIPLY:
ret = a * b;
break;
}
答案 3 :(得分:1)
您应该使用枚举作为执行操作的标志:
public int computeOperation(int leftOperand, Operation op, int rightOperand) {
switch(op) {
case ADD:
return leftOperand + rightOperand;
case SUBTRACT:
return leftOperand - rightOperand;
case MULTIPLY:
return leftOperand * rightOperand;
}
return null;
由于你为每个案件返回,你不必担心堕落。