Reputation: 5664
Suppose there is an ENUM
enum Operations {
ADD,
SUBTRACT,
MULTIPLY
}
I want to use this enum to add two numbers(say 5 and 3) and get the output as 8 or I want to use this enum to subtract two numbers(say 9 and 3) and get the output as 6
Question:
Upvotes: 5
Views: 13756
Reputation: 2652
How about using JAVA 8 features:
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);
}
}
Upvotes: 8
Reputation: 4350
You should use the enum as a flag for what operation to perform:
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;
Since you're returning for each case, you don't need to worry about fall through.
Upvotes: 1
Reputation: 120586
enum
s can have abstract methods, and each member can implement it differently.
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);
}
will allow you to do
Operations op = ...;
double result = op.apply(3, 5);
Upvotes: 24
Reputation: 15028
You can use a switch on the enum value:
switch (operator) {
case ADD:
ret = a + b;
break;
case SUBTRACT:
ret = a - b;
break;
case MULTIPLY:
ret = a * b;
break;
}
Upvotes: 4