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 licences: GPL or commercial. Depending on the environment you plan on using it in, the licence 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 website to get complete documentation and plenty of sample code.

Interpreting Java This was published in Interpreting Java, check every Tuesday for more stories

Related links

Leave a comment

You must read and type the 6 chars within 0..9 and A..F

* indicates mandatory fields.

Log in


Sign up | Forgot your password?

  • Staff Aussies to pay more for Win 7

    If you are looking to make some money in these troubled times, perhaps importing copies of Windows 7 could be for you. Read more »

    -- posted by Staff

  • Staff Firefox: Greens want it, 3.5rc2 not up to par

    This week's roundup looks at the situation surrounding a campaign to change Outlook HTML renderer, a Greens MP wants to install Firefox but is restricted and all the photos from the iPhone 3GS launch. Read more »

    -- posted by Staff

  • Chris Duckett Microsoft misses the Outlook point

    Ask designers which mail program is the bane of their existence, and you'll find that Outlook tops the list. The reason why the most popular email reader is also the most painful is simple: it uses Word to render HTML emails. Read more »

    -- posted by Chris Duckett

What's on?