Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

need to calculate formulae given as string expression.

 
john sal
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have two String expression of a formulae like

String s = "max(1, 5)" ;

and
int a=2;
int b=2
String s2 = "a * b";

Is there any API in java which takes these string and calculate it as a mathematical expression?
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Search the FAQ pages for a library named JEP; it does this.
 
john sal
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is not a freeware ...
 
Rob Spoor
Sheriff
Pie
Posts: 20608
63
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the formulas are not too complex you could try to use a JavaScript engine. See http://download.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html for more information.

Edit: I just tried it, and it can handle a * b just fine:
The max function is undefined in JavaScript however. You can solve that by adding it as a function after line 8:
You may want to add a few similar functions like that, like min.

Also, the eval method returns a Double, but the cast to Number and then calling its intValue() method is a bit safer to get the int result.
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
john sal wrote:It is not a freeware ...

It is, if you use the version linked in the JavaRanch FAQ (which is GPLed).
 
john sal
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can you please guide me to the link for GPLed as I am not able to find it..

Thanks.
 
john sal
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rob thanks a lot it worked fine and is vry helpful ..... Just have a doubt how can we make it work for the following expression?

"max(a,b)/c"

The only way i found is to send the c as well as an argument and do all the calculations in the method itself..is there any other possible and better way of doing this?

 
john sal
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Rob thanks ... It is working fine for this expression as well.....I was executing it in a wrong way hence was not getting the expected result....

Thanks a lot
 
Rob Spoor
Sheriff
Pie
Posts: 20608
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic