JEP is a Java mathematical expression parser.
This means that you can pass JEP a string of mathematical
operations (which may also contain variables) to perform and get
back an answer.
To start using JEP, create an instance of the
parser:
JEP j = new JEP();
Then, if you plan on using functions such as sin or cos, you need to tell JEP
to expect these by calling the parser’s addStandardFunctions
method:
j.addStandardFunctions();
You’re ready to start parsing. Call the
parseExpression method with the expression that needs parsing. In
this case, we’ll parse whatever is passed from the command
line:
j.parseExpression(args[0]);
Now print the result:
System.out.println(j.getValue());
For example, if the expression was “75 * 4 / (3
* 100)”, the output would be:
1.0
If you want to use variables in your
expression, you must tell JEP to expect these variables by calling
the parser’s addVariable method:
j.addVariable(“x”, 0);
One thing to keep in mind if you decide to use
JEP in your code is that JEP comes with one of two licenses: GPL or
commercial. Depending on the environment you plan on using it in,
the license type may be important to you.
Below is a complete example that parses the
expression passed in as a command line argument.
import org.nfunk.jep.JEP;
public class JepTip {
public static void main(String []args)
{
JEP j = new
JEP();
j.addStandardFunctions();
j.parseExpression(args[0]);
System.out.println(j.getValue());
}
}
Visit
the JEP Web site to get complete documentation and plenty of
sample code.
Delivered each Thursday, our free Java newsletter provides insight and hands-on tips you need to unlock the full potential of this programming language. Automatically sign up today!