aspose file tools*
The moose likes Beginning Java and the fly likes Executing calculation of an expression within a string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Executing calculation of an expression within a string" Watch "Executing calculation of an expression within a string" New topic
Author

Executing calculation of an expression within a string

Jan Coff
Greenhorn

Joined: Dec 04, 2005
Posts: 5
I've got a string containing a mathematical expression. How can I calculate the value of the expression in the string?
Example: stringExp = "4*8";
How can I get the value of 32? I can't figure out how to parse the operator properly.

Thanks
pascal betz
Ranch Hand

Joined: Jun 19, 2001
Posts: 547
depends on how complicate your expressions are (e.g. order of operators: 1 + 2 * 3).

you could work with the indexOf() method of String, or the StringTokenizer class or the regular expressions for simple stuff (e.g. just the 4 basic operators without precedence rules).


p
Jan Coff
Greenhorn

Joined: Dec 04, 2005
Posts: 5
I'm using the Stringtokenizer and I think I've found a way to do what I need to.

Thanks
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 39529
    
  27
I keep an old piece of code around that evaluates expressions (even with variables) by employing a recursive-descent parser.


Ping & DNS - updated with new look and Ping home screen widget
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Executing calculation of an expression within a string
 
Similar Threads
A few clarifications needed please...
Simple RegularExpressions in Ant
switch with Strings
confusion in Expression Language
convert String into Object