I'm trying to write a Java routine to evaluate simple math expressions from String
values like:
"5+3"
"10-40"
"10*3"
I want to avoid a lot of if-then-else statements. How can I do this?
I'm trying to write a Java routine to evaluate simple math expressions from String
values like:
"5+3"
"10-40"
"10*3"
I want to avoid a lot of if-then-else statements. How can I do this?
This article points to 3 different approaches, one which is JEXL from Apache and allows for scripts that include references to java objects.
HERE is another open source library on GitHub named EvalEx.
Unlike the JavaScript engine this library is focused in evaluating mathematical expressions only. Moreover, the library is extensible and supports use of boolean operators as well as parentheses.
External library like RHINO or NASHORN can be used to run javascript. And javascript can evaluate simple formula without parcing the string. No performance impact as well if code is written well. Below is an example with RHINO -
You can evaluate expressions easily if your Java application already accesses a database, without using any other JARs.
Some databases require you to use a dummy table (eg, Oracle's "dual" table) and others will allow you to evaluate expressions without "selecting" from any table.
For example, in Sql Server or Sqlite
and in Oracle
The advantage of using a DB is that you can evaluate many expressions at the same time. Also most DB's will allow you to use highly complex expressions and will also have a number of extra functions that can be called as necessary.
However performance may suffer if many single expressions need to be evaluated individually, particularly when the DB is located on a network server.
The following addresses the performance problem to some extent, by using a Sqlite in-memory database.
Here's a full working example in Java
Of course you could extend the above code to handle multiple calculations at the same time.
For my university project, I was looking for a parser / evaluator supporting both basic formulas and more complicated equations (especially iterated operators). I found very nice open source library for JAVA and .NET called mXparser. I will give a few examples to make some feeling on the syntax, for further instructions please visit project website (especially tutorial section).
http://mathparser.org/
http://mathparser.org/mxparser-tutorial/
http://mathparser.org/api/
And few examples
1 - Simple furmula
2 - User defined arguments and constants
3 - User defined functions
4 - Iteration
Best regards
}