开发者

Java 1.5: mathematical formula parser

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 n开发者_JAVA百科otation 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


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.


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.


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.


i released an expression evaluator based on Dijkstra's Shunting Yard algorithm, under the terms of the Apache License 2.0:

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


There's a commercial tool called formula4j which may be useful to some.

It has no direct help for cell references. You would have to handle those yourself, and translate the cell references into values.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜