Search code examples
javamatheval

How to assign value to a variable using string in Java (not evaluation)


Let's say I have,

  1. A string String foo = "a+b"
  2. Variable a and b, Integer a = 2 Integer b = 3

I want to somehow assign new Integer, c which should be calculated from a and b using the String foo.

The eval didn't work as it can only compute things with absolute values not values of variables.


Solution

  • You can use the JEP Java expression parser libary (or another expression parser).

    For example:

    String foo = "a+b";
    Jep jep = new Jep();
    try {
        jep.addVariable("a", a);
        jep.addVariable("b", b);
        jep.parse(foo);
        Object result = jep.evaluate();     
        System.out.println("foo = " + result);
    } catch (JepException e) {
        System.out.println("An error occurred: " + e.getMessage());
    }
    

    EDIT:

    It turns out that JEP (here: http://www.singularsys.com/jep/) is licensed software so you will have to pay, but there is another option.

    There are many other similar libraries including JEPLite (http://jeplite.sourceforge.net/index.html) which seems (as far as I can tell) to be a free version and should be compatible.