Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Executing calculation of an expression within a string

 
Jan Coff
Greenhorn
Posts: 5
  • 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
  • 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
  • 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
Posts: 42967
73
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic