Reputation:
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!
Upvotes: 2
Views: 1811
Reputation: 154
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));
}
}
Upvotes: 5