How to evaluate string math expression in java

1.3k views Asked by At

I want to evaluate a sting math expression in java. This string should contain functions (avg, max, min, ...) applied to vectors or simple numbers. I already use ScriptEngineManager with javasript engine but it just use numbers. I also see symja lib but it look too complicated et not documented. How to do? Thanks

2

There are 2 answers

0
grey00 On

Take a look at the Math and String classes of the javadoc. If you know the format of the string, you should be able to search through it to find the specific numbers and functions you're using. If you are only using one of the avg/max/min per input, it should be pretty easy.

Here's an example, lets say you want it formatted like so (it's easy if theres a comma after every value):

"FUNCTION(a, b, c,)" -> "MIN(3,6,8,)"

The first thing you want to do is have it figure out which function you're doing. Using the indexOf method, we can figure out if it contains MIN or MAX or whatever.

 if(expression.indexOf("MIN" != -1){
      //calculate min value
 }

You'll also need to create a list of all the numbers you're using.

 int lastIndex = exression.indexOf("(");
 while(lastIndex < expression.lastIndexOf(","){
      listOfNums.add(Integer.parseInt(expression.subString(lastIndex + 1, expression.indexOf(",", lastIndex + 1)));
      lastIndex = expression.indexOf(",", lastIndex + 1);
  }
0
Michael Couck On

There are two very good expression parsers, JEP(paid now unfortunately - http://www.singularsys.com/jep/) and Jexl(much more than just an expression parser - http://commons.apache.org/proper/commons-jexl/).

I prefer Jexl, so here is an example:

JexlEngine jexl = new JexlEngine();
// The expression to evaluate
Expression e = jexl.createExpression("((a || b) || !c) && !(d && e)");

// Populate the context
JexlContext context = new MapContext();
context.set("a", true);
context.set("b", true);
context.set("c", true);
context.set("d", true);
context.set("e", true);

// Work it out
Object result = e.evaluate(context);

More examples - http://commons.apache.org/proper/commons-jexl/reference/examples.html