Using the JEP package of classes in your project is simple! The following steps will get you started quickly.
org.nfunk.jep.JEP myParser = new org.nfunk.jep.JEP();
myParser.addStandardFunctions(); myParser.addStandardConstants();
myParser.addVariable("x", 0);
myParser.parseExpression(ExpressionString); result = myParser.getValue();
The code of the sample applets provide more extensive look at how the parser methods are used.
Errors can occur both while parsing an expression and while evaluating an
expression. The hasError()
method reports whether an error has occurred during the most recent action
(either parsing or evaluation). If the result is true
, you can
then use getErrorInfo()
to obtain further information on the errors that have occurred.
Four methods for evaluating an expression are available:
The first two methods call getValueAsObject()
internally, and perform the necessary conversions into either a double
value, or a Complex
object.
There is an alternative method to parsing and evaluating expression which allows a little more flexibility in applications especially when working with a set of related equations. These are:
public Node parse(String expression) throws ParseExceptionwhich parse and evaluate the expression. These can be used like
public Object evaluate(Node node) throws Exception
try
{
// Alternative syntax
Node node1 = j.parse("z=i*pi");
j.evaluate(node1);
Node node2 = j.parse("exp(z)");
Object val2 = j.evaluate(node2);
System.out.println("Value: "+val2);
}
catch(ParseException e) {
System.out.println("Error with parsing");
}
catch(Exception e) {
System.out.println("Error with evaluation");
}
Hence its a bit easier to keep track of a number of equations. Note that using this syntax Exceptions need to be caught and the getTopNode() method will not return meaningful results.
You can enable the implicit multiplication option with setImplicitMul(true). The default setting is false (no implicit multiplication).
Implicit multiplication allows expressions such as "2 x" to be interpreted as "2*x". Note that a space is required between two variables for them to be interpreted as being multiplied. The same holds for a variable followed by a number. For example "y 3" is interpreted as "y*3", but "y3" is interpreted as a single variable with the name y3. If a variable is preceded by a number, no space is required between them for implicit multiplication to come in effect.