File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Executing calculation of an expression within a string

 
Jan Coff
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 547
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm using the Stringtokenizer and I think I've found a way to do what I need to.

Thanks
 
Ulf Dittmer
Rancher
Pie
Posts: 42966
73
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I keep an old piece of code around that evaluates expressions (even with variables) by employing a recursive-descent parser.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic