Reputation: 48091
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?
Upvotes: 9
Views: 42458
Reputation: 1632
switch (op.charAt(0)) {
case '+': return first + second;
case '-': return first - second;
// ...
}
Upvotes: 6
Reputation: 4347
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);
}
Upvotes: 3
Reputation:
switch(string){
}
(switch on strings)will be allowed in Java7. Now you can switch with char
switch(string.charAt(0)){
case '+' : ...
}
as mentioned above
Upvotes: 0
Reputation: 5853
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..
Upvotes: 14
Reputation: 11071
public double doMath(int first, int second, char op ){
switch(op){
case '+':
return first + second;
break;
case '-':
return first - second;
break;
case '*':
return first * second;
break;
case '/':
return first / second;
break;
default:
return 0;
}
}
Upvotes: 1