Evaluating mathematical expression given as String

98 Views Asked by At

I have List of class Data as dataList, Data contains two variable a and b.

public class Data {

int a,b;

public Data(int a, int b){
    this.a=a;
    this.b=b;
}

//also contains getter and setter method
}



List<Data> dataList=new ArrayList<>();

dataList.add(new Data(2,3));
dataList.add(new Data(6,2));

Also, I have mathematical expression in the form of string for eg. 3*a+5*b;

I want to apply above expression to data list, to get output as 21 and 28.

dataList.forEach(v1 ->System.out.println(//some code to evaluate the expression));

Thanks in advance

1

There are 1 best solutions below

0
On

You can use ScriptEngineManager. With scriptEngine.eval(expression) the expression script will be executed.

Then you can do:

    List<Data> dataList = new ArrayList<>();

    dataList.add(new Data(2, 3));
    dataList.add(new Data(6, 2));

    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
    dataList.forEach(data -> {
        try {
            System.out.println(scriptEngine.eval(data.getExpression("3*a+5*b")));
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    });

With Data class:

public class Data {

    int a, b;

    public Data(int a, int b) {
        this.a = a;
        this.b = b;
    }

    public String getExpression(String expression) {
        return expression.replaceAll("a", "" + a).replaceAll("b", "" + b);
    }

}