File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/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
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: 42929
    
  68
I keep an old piece of code around that evaluates expressions (even with variables) by employing a recursive-descent parser.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Executing calculation of an expression within a string