Algebra equation parser for java

后端 未结 5 724
渐次进展
渐次进展 2020-12-01 14:43

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          


        
5条回答
  •  情歌与酒
    2020-12-01 14:44

    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 vars = new HashMap();
            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.

提交回复
热议问题