Algebra equation parser for java

Alfredo Osorio picture Alfredo Osorio · Jan 13, 2011 · Viewed 31.3k times · Source

I need a library to be able to parse an equation an give me the result giving the inputs.

For example something like this:

String equation = "x + y + z";
Map<String, Integer> vars = new HashMap<String, Integer>();
vars.add("x", 2);
vars.add("y", 1),
vars.add("z", 3);
EquationSolver solver = new EquationSolver(equation, vars);
int result = solver.getResult();
System.out.println("result: " + result);

And evaluates to: 6

Is there any kind of library for java that can do that for me?

Thanks

Answer

Bart Kiers picture Bart Kiers · Jan 13, 2011

You could make use of Java 1.6's scripting capabilities:

import javax.script.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
        Map<String, Object> vars = new HashMap<String, Object>();
        vars.put("x", 2);
        vars.put("y", 1);
        vars.put("z", 3);
        System.out.println("result = "+engine.eval("x + y + z", new SimpleBindings(vars)));
    }
}

which produces:

result = 6.0

For more complex expressions, JEP is a good choice.