0

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.

  • You can write parser or see this question. [Stackowerflow](https://stackoverflow.com/questions/2605032/is-there-an-eval-function-in-java) – Pavlishin Nikita Dec 05 '19 at 09:55

1 Answers1

0

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.

rghome
  • 8,529
  • 8
  • 43
  • 62