I am facing this requirements wherein I need to evaluate math expressions at runtime.
Say for example, I have this:
But I think I cannot do these in pure J2SE. Do you know any free expression evaluator or library that I can use to accomplish this?
Or should I fall back to Scripting.
While googling I found some post that is related to scripting but I am not sure yet If that is the right tool for the job at hand. Thanks
Sean Clark ---> I love this place!!!
Me ------> I definitely love this place!!!
Joined: Oct 13, 2005
Try using a regular expression to match the operator. You can also use the String#split (and possibly trim) methods to divide the String into operands around the operator. You can try multiple if-elses, or create an Operator enum, then you can have pairs in a Map, eg ">=" --- Operator.GREATER_OR_EQUAL, and use the enum member as the key in a switch-case.
That will work if you only ever have one operator in each String, and you will have to change it if you use uinary operators.
I'm concerned about the "Get from DB" comment. That would mean you have to get involved with JDBC and in that case you have some configuration to do first.
The regular expressions Campbell mentions would be useful if you need to parse a string of the form "operand1 operator operand2", but the way you've laid it out, you just have to figure out which which operator you have, and then apply it. I don't see any way to do that except with a bunch of if-else if tests. One nice thing is that all your possible operators result in a boolean value (i.e., true or false). You're assigning that result to a String (called expression), but then immediately treating expression like it's a boolean value anyway. You need to change that.
Joined: Jul 09, 2007
Hi Greg And Campbell,
Thanks for your valuable inputs.
But while coding it, it leads me to lots of If and Else statements and logic handling for two or more operands.
Fortunately while googling, I found post related to Java SE 6 support for scripting.
I modified a little code to fit my needs. Here's what I am using now.
Thanks though for your inputs. They are very higly regarded.
I am actually not a fan of this... the expression is really simple, and hence, the parser should be really simple.
While the parser code will likely be longer than the code presented, I can't imagine it being less efficient than bringing in a scripting engine, and a different language, to process such a simple expression.