Java 从字符串中获取x值

Java 从字符串中获取x值,java,string,function,Java,String,Function,我正在尝试用Java制作一个绘图仪。我已经完成了graph函数,但是我必须在源代码中手动插入该函数。我试图得到类似于x=5*y-2的东西。这就是我希望我的代码看起来的样子: String y = "2*y+1"; int x = y; drawgraph(x); 如果这还不够,我也可以发送源代码。如果您想动态地为代码提供任何函数公式,您需要实现一个表达式树,并对其参数的不同值进行求值。我认为,你需要自己实现这一点 只需在谷歌上搜索“表达式树java”或“抽象语法树java”,就会得到很多结果

我正在尝试用Java制作一个绘图仪。我已经完成了graph函数,但是我必须在源代码中手动插入该函数。我试图得到类似于
x=5*y-2
的东西。这就是我希望我的代码看起来的样子:

String y = "2*y+1";
int x = y;
drawgraph(x);

如果这还不够,我也可以发送源代码。

如果您想动态地为代码提供任何函数公式,您需要实现一个表达式树,并对其参数的不同值进行求值。我认为,你需要自己实现这一点


只需在谷歌上搜索“表达式树java”或“抽象语法树java”,就会得到很多结果

一种快速的方法是使用Java的JavaScript引擎。例如:

import javax.script.*;

interface GraphFunction {
    double eval(double x);

    public static GraphFunction createFromString(String expression) {
        try {
            ScriptEngine engine = new ScriptEngineManager()
                .getEngineByName("JavaScript");
            engine.eval("function graphFunc(x) { return " + expression + "; }");
            final Invocable inv = (Invocable)engine;
            return new GraphFunction() {
                @Override
                public double eval(double x) {
                    try {
                        return (double)inv.invokeFunction("graphFunc", x);
                    } catch (NoSuchMethodException | ScriptException e) {
                        throw new RuntimeException(e);
                    }
                }
            };
        } catch (ScriptException e) {
            throw new RuntimeException(e);
        }
    }
}
现在,要使用它:

class Test {
    public static void main(String[] args) {
        GraphFunction f = GraphFunction.createFromString("2*x+1");

        for (int x = -5; x <= +5; x++) {
            double y = f.eval(x);
            System.out.println(x + " => " + y);
        }
    }
}

好吧,这是我想要的,但对我来说太难了。它看起来很中级。我没有那么多知识
-5 => -9.0
-4 => -7.0
-3 => -5.0
-2 => -3.0
-1 => -1.0
0 => 1.0
1 => 3.0
2 => 5.0
3 => 7.0
4 => 9.0
5 => 11.0