Java 1.5: mathematical formula parser

2019-02-23 12:48发布

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

5条回答
放荡不羁爱自由
2楼-- · 2019-02-23 13:07

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.

查看更多
男人必须洒脱
3楼-- · 2019-02-23 13:08

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.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-02-23 13:10

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.

查看更多
仙女界的扛把子
5楼-- · 2019-02-23 13:12

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.

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-02-23 13:25

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

查看更多
登录 后发表回答