Enum as an arithmetic operation

Suppose ENUM exists

enum Operations { 
  ADD, 
  SUBTRACT, 
  MULTIPLY
}

I want to use this enumeration to add two numbers (say, 5 and 3) and get the output as 8 or I want to use this enumeration to subtract two numbers (for example, 9 and 3) and get the result as 6

Question:

  • Is it possible?
  • if so, what changes should be made to this listing?
+5
source share
4 answers

enum 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);
}

let you perform

Operations op = ...;
double result = op.apply(3, 5);
+17
source

You can use the switch for the enumeration value:

switch (operator) {
case ADD:
    ret = a + b;
    break;
case SUBTRACT:
    ret = a - b;
    break;
case MULTIPLY:
    ret = a * b;
    break;
}
+4
source

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);
    }
}
+4

- :

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;

, , .

+1
source

All Articles