lowLatency
lowLatency

Reputation: 5664

enum as arithmetic operation

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

Answers (4)

InsaneBot
InsaneBot

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

smessing
smessing

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

Mike Samuel
Mike Samuel

Reputation: 120586

enums 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

Tyler Treat
Tyler Treat

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

Related Questions