2

I am creating a Graphing Calculator as our project in Calculus. The only thing left in my program is the input from the user.

For example, the user placed an input in the text field named 'userInput':

y=sin(x)

Next, converting it to string will have

String equation = userInput.getText();

And the string variable 'equation' will have a value which is:

"y=sin(x)"

Is there a way to read a String as a Java code?

Bon Javier
  • 23
  • 3

3 Answers3

0

Janino can do that for you, assuming that you want these expressions to be valid Java, I think the ExpressionDemo would be a good starting point for what you want.

The basic code will look +- like this (quickly adapted from the basic example):

// Compile the expression once; relatively slow.
ExpressionEvaluator ee = new ExpressionEvaluator(
    "sin(x)",                    // expression
    double.class,                // expressionType
    new String[] { "x" },        // parameterNames
    new Class[] { double.class } // parameterTypes
);

// Evaluate it with varying parameter values; very fast.
Double res = (Integer) ee.evaluate(
    new Object[] {          // parameterValues
        new Double(12.34)
    }
);
System.out.println("result = " + res);
fvu
  • 32,488
  • 6
  • 61
  • 79
0

I had the same problem before (while creating a graphing calculator in C). I converted the expression in its Reverse Polish notation and then parsed it using Shunting-yard algorithm. You can also check this GeeksForGeeks tutorial on expression evaluation.

Rafi Kamal
  • 4,522
  • 8
  • 36
  • 50
0

This does not exactly answers your question, but is probably a much better way to achieve your goal. See Javaluator.

Elist
  • 5,313
  • 3
  • 35
  • 73