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!