Another solution from J. Selva's response:
Improvements
- single class
- static block
- better abstraction
import java.util.HashMap;
import java.util.Map;
/**
* Created by SEA-HAWK on 23/8/15.
*/
public abstract class Expr {
public static Map<String,Object> op;
static{
op=new HashMap<>();
op.put("+", new Expr() {
@Override
public int evaluate(int a, int b) {
return a + b;
}
});
op.put("-", new Expr() {
@Override
public int evaluate(int a, int b) {
return a - b;
}
});
op.put("*", new Expr() {
@Override
public int evaluate(int a, int b) {
return a * b;
}
});
op.put("/", new Expr() {
@Override
public int evaluate(int a, int b) {
return a / b; // decimal point loss
}
});
}
abstract public int evaluate(int a, int b);
public static int exprEval(String expr){
String a[]=expr.split(",");
a[2]=a[2].replaceAll("\"","");
return ((Expr)op.get(a[2])).evaluate(Integer.parseInt(a[0]),Integer.parseInt(a[1]));
}
}
Main function:
public static void main(String[] args) {
String x="20,10,\"*\"";
System.out.println(x+"="+Expr.exprEval(x));
x="20,10,\"+\"";
System.out.println(x+"="+Expr.exprEval(x));
x="20,10,\"-\"";
System.out.println(x+"="+Expr.exprEval(x));
x="20,10,\"/\"";
System.out.println(x+"="+Expr.exprEval(x));
}
Output:
20,10,"*"=200
20,10,"+"=30
20,10,"-"=10
20,10,"/"=2
Note: change datatype for float/decimal value computation.