Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing math operation when operator is stored in a string

Tags:

java

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?

like image 725
dynamic Avatar asked Jan 28 '11 20:01

dynamic


2 Answers

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..
like image 193
Mauricio Avatar answered Nov 05 '22 22:11

Mauricio


switch (op.charAt(0)) {
  case '+': return first + second;
  case '-': return first - second;
  // ...
}
like image 25
rpjohnst Avatar answered Nov 05 '22 21:11

rpjohnst