2

I have two variables of type int (called int1 and int2) and a variable type char (which always saves a mathematical operator and is called op). How can I do mathematical operations with these three variables? I have to do it manually, I can not use ScriptEngineManager for teacher's reasons

I can not do int res = int1 + op + int2 because it adds the value that the variable op has in the ascii table. How could I put these three variables together to do a mathematical operation according to the variable op?

The simplest way I have found to do it is the following:

int res = 0;
if (op == '+'){res=int1+int2;}
else if (op == '-'){res = int1-int2;}
else if (op == '*'){res = int1*int2;}
else {res = int1/int2;}

Is there any more elegant way than this? Thank you!

2
  • The answer is No there isn't. You could use a switch statement rather than if/else, but you still need a separate branch for each operator. Commented Apr 17, 2018 at 3:50
  • Looks to me like you are on the right track. Keep going & keep up the good work. Commented Apr 17, 2018 at 4:19

1 Answer 1

5

Create an enumeration that maps the operation character to a function of two ints.

enum Operator {
    ADD('+',(x,y)->x+y),
    SUBTRACT('-',(x,y)->x-y),
    MULTIPLY('*',(x,y)->x*y),
    DIVIDE('/',(x,y)->x/y),
    REMAINDER('%',(x,y)->x%y),
    POW('^',(x,y)->(int)Math.pow(x,y));

    char symbol;
    BiFunction<Integer,Integer,Integer> operation;

    Operator(final char symbol, final BiFunction<Integer,Integer,Integer> operation) {
        this.symbol = symbol;
        this.operation = operation;
    }

    public static Operator representedBy(final char symbol)
    {
        return Stream.of(Operator.values()).filter(operator->operator.symbol==symbol).findFirst().orElse(null);
    }

    public Integer apply(final int x,final int y)
    {
        return operation.apply(x,y);
    }
}

public static void main(final String[] args) {
    final char op = '+';
    final int int1 = 1;
    final int int2 = 2;
    final Operator operator = Operator.representedBy(op);
    if (operator == null)
    {
        // handle bad character
    }
    else
    {
        System.out.println(operator.apply(int1,int2));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.