本文介绍了java的代数方程解析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个库来解析一个等式,给我一个给出输入的结果。

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

例如这样的东西:

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);

并评估为:
6

And evaluates to:6

是否有任何类型的java库可以为我做这件事?

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

谢谢

推荐答案

您可以使用Java 1.6的脚本功能:

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)));
    }
}

产生:

result = 6.0

了解更多复杂的表达方式,是一个不错的选择。

For more complex expressions, JEP is a good choice.

这篇关于java的代数方程解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 01:49