Using java language to calculate the value of an expression(or equation) dynamically

644 views Asked by At

I have to write a method that accepts three arguments and an arithmetic expression(or equation).Based on the equation the result has to be returned.But the problem is that the equation is given as a string that has to be converted to do the arithmetic (I am confused how to do it).How we can solve this problem effectively in java.The code for the same is given below.

public static void main(String[] args) {
    System.out.println(getResult(2,3,5,"(a+b)*c/(a+c)"));
}
static double getResult(int a,int b,int c,String expr)
{
    //double result=(a+b)*c/(a+c);
    double result=expr;
    return result;
}

Here the getResult method has to accept three integers and the equation as a string.It would be great if someone can suggest the solution or an alternative way to effectively solve this problem.

Thanks everyone for your suggestions.Rewritten code that makes use of Javaluator library.

    StaticVariableSet<Double> variablelist = new StaticVariableSet<Double>();
    variablelist.set("a", 2.0);
    variablelist.set("b", 3.0);
    variablelist.set("c", 5.0);

    System.out.println(new DoubleEvaluator().evaluate("(a+b)*c/(a+c)",variablelist));
1

There are 1 answers

3
a_pradhan On

You need to parse the string into a valid expression and then find the value. Have a look at recursive descent parser to start with. You can use 3rd party librares (if you are allowed to do so)