0

I am trying to make a graph plotter in Java. I have finished the graph function but I have to manually insert the function in the source code. I'm trying to get something like x=5*y-2. This is what I want to my code to look like:

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

If it's not enough I can send source code too.

Boann
  • 48,794
  • 16
  • 117
  • 146
Dogacel
  • 113
  • 1
  • 7

2 Answers2

1

If you want to dynamically give any function formula to your code, you need to implement an expression tree and evaluate it for different values of its parameters. You need to implement this yourself, I think.

Just Google for 'expression tree java' or 'abstract syntax tree java' and lots of results will come up.

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
  • Okay, it is what i want but its too difficult for me.İt looks so intermediate.İ dont have that much knowledge – Dogacel Apr 13 '14 at 12:45
0

A quick 'n dirty way to do this is to use Java's JavaScript engine. An example:

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

Now, to use it:

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

Output:

-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
Boann
  • 48,794
  • 16
  • 117
  • 146