I have 2 integers:
int first= 10;
int second = 20;
and a string representing the operation (one of +
, -
, /
, or *
):
String op = "+";
How can I get the result of 10 + 20 in this example?
See Question&Answers more detail:osI have 2 integers:
int first= 10;
int second = 20;
and a string representing the operation (one of +
, -
, /
, or *
):
String op = "+";
How can I get the result of 10 + 20 in this example?
See Question&Answers more detail:osI don't recommend this but is funny. in java6
String op = '+';
int first= 10;
int second = 20;
ScriptEngineManager scm = new ScriptEngineManager();
ScriptEngine jsEngine = scm.getEngineByName("JavaScript");
Integer result = (Integer) jsEngine.eval(first+op+second);
go with the switch, but remember to convert the string operator to char as switch don't works with strings yet.
switch(op.charAt(0)){
case '+':
return first + second;
break;
// and so on..