Performing math operation when operator is stored in a string

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;
  // ...
}

you can try the following code. It's object oriented, quite generic, and you can easily extend it to add new operators, including operators with a different number of arguments:

public abstract class Operator {
  public abstract Integer compute(Integer...values);
}

public class Plus extends Operator {
  public Integer compute(Integer...values)   {
    return values[0] + values[1];
  }
}

public class Minus extends Operator {
  public Integer compute(Integer...values)   {
    return values[0] - values[1];
  }
}

public class Multiply extends Operator {
  public Integer compute(Integer...values)   {
    return values[0] * values[1];
  }
}


public class Divide extends Operator {
  public Integer compute(Integer...values)   {
    return values[0] / values[1];
  }
}

Map operatorMap = createOperatorMap();

public Map createOperatorMap() {
  Map<String, Operator> map = new HashMap<String, Operator>();
  map.put("+", new Plus());
  map.put("-", new Minus());
  map.put("*", new Multiply());
  map.put("/", new Divide());
  return map;
}

public int compute(int a, int b, String opString) {
  Operator op = operatorMap.get(opString);
  if (op == null)
    throw new IllegalArgumentException("Unknown operator");
  return op.compute(a, b);
}

Tags:

Java