Java 1.5: mathematical formula analyzer

Hello, I often develop JTableModels in which some cells must contain the result of a simple, simple mathematical formula. These formulas may have:

  • Operators (+, -, *, /)
  • Numeric constants
  • Other cell references (containing numbers)
  • Parameters (numbers with a reference name of type "INTEREST_RATE")

I often allow this to be done by a small class of calculator that analyzes the formula, which syntax I define. The calculator class uses the stack for calculations, and the syntax always uses Polish notation.

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

Is there a lib that works in 1.5 jvm and can handle my requests and use normal notation (with brackets, I don't know the name of this notation style) for formulas?

PD suggested that formulas are always syntactically correct, and I can preprogram numbers that are not constants to provide their values

+4
source share
5 answers

Have you thought about the benefits of the JSR-223 ? in a few words, this specification allows Java developers to easily integrate dynamic languages ​​and their parsers . Using such a parser, your need to define a parser translates into the need to define an internal DSL that allows the creation of a simple API and allows your user to choose whether they prefer the Javascript / Groovy / Scala / WTF syntax that they prefer.

+3
source

Try JEP .

You can define new variables for the parser, therefore, they can contain reference names such as "INTEREST_RATE". But you must identify it before you begin.

As for cell references, you will need to extract the number and edit the expression accordingly, or maybe there may be some parameters that I still don't know about.

+1
source

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

... BSF 3.x will run on Java 1.4+, which will allow access to JSR-223 scripts for Java 1.4 and Java 1.5.

0
source

i released an expression evaluator based on the Dijkstra Shunting Yard algorithm in accordance with the terms of Apache License 2.0 :

http://projects.congrace.de/exp4j/index.html

0
source

There is a commercial tool called formula4j , which may be useful for some.

It does not have direct help for cell references. You will have to process them yourself and translate cell references into values.

0
source

All Articles