views:

91

answers:

4

Hello i often develop JTableModels in which some cells must contain the result of apliying a certain simple mathematical formula. This formulas can have:

  • Operators (+,-,*,/)
  • Number constants
  • Other cell references (which contains numbers)
  • Parameters (numbers with a reference name like "INTEREST_RATE")

I often resolve it making a little calculator class which parses the formula, which syntax i define. The calculator class uses a stack for the calcs, and the syntax uses allways a Polish notation.

But the Polish notation is unnatural for me and for my users. So my question is...

Is there a lib which runs in 1.5 jvm's and can handle my requeriments and use normal notation (with brackets, i don't know the name of this notation style) for formulas?

P.D it's supposed that the formulas are allways syntax correct and i can preprocess the numbers that are not constants to provide their values

+1  A: 

Have you thought about the benefits of JSR-223 ? in a few words, this spec allows Java developers to integrate with great ease dynamic languages and their parsers. Using such parser, your need for defining a parser transforms into the need for defining an internal DSL, which resolves into creating simply a good API, and letting your user choose wether they prefer Javascript/Groovy/Scala/WTF syntax they happen to prefer.

Riduidel
This seems a good aproach, i will investigate it, but sadly i need it to run in jvm 1.5. I will update my question
Telcontar
This really works, but i can't use it because the 1.5 restriction. If nobody offers a better answer for java 1.5 i will change the question to the original an accept your answer
Telcontar
Finally, as i read in the second link you provide, the ScriptingEngine can be used in 1.5 if you download the reference implementation from http://jcp.org/aboutJava/communityprocess/final/jsr223/index.html
Telcontar
+1  A: 

@Riduidel link to the JSR has an extra "." and leads to 404. Correct link should be http://jcp.org/en/jsr/detail?id=223

Ck-
Thanks, I will fix it.
Riduidel
A: 

Try JEP.

You can define new variables to the parser hence it can contain reference names like "INTEREST_RATE".But you have to define it before hand.

As for cell references you will have to extract the number's and edit the expression accordingly or probably there might be some options which I'm not yet aware of.

Emil
A: 

If you can't use Java 6 and its scripting support then have a look at the Apache Bean Scripting Framework (BSF). From that page:

... BSF 3.x will run on Java 1.4+, allowing access to JSR-223 scripting for Java 1.4 and Java 1.5.

Jesper
I can use int from 1.5 using the reference implementation JSR-223, but thanks for the answer
Telcontar