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?
I 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..
switch (op.charAt(0)) {
case '+': return first + second;
case '-': return first - second;
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With