# Convert A String To Math Problem

• 07-04-2011, 11:52 PM
anthropamorphic
Convert A String To Math Problem
I figured it out thanks!
• 07-04-2011, 11:59 PM
Dark
Are the spaces there in every string? If there was you could string.split your string into an array. Then you would just have to figure out which ones were numbers and which ones were symbols.

Take a look at the api: String (Java Platform SE 6)
• 07-05-2011, 12:08 AM
Fubarable
You could use Java's ability to run scripts and allow JavaScript to parse the equation for you. Please have a look here: scripting-for-java-platform

and here: formula-expression-to-result
• 07-05-2011, 12:15 AM
Dark
Hmm, that is definitely a more simple approach. I guess I learned something today :P:
• 07-05-2011, 12:19 AM
Jodokus
• 07-05-2011, 01:07 AM
Junky
If you cannot use Javascript, what you need to do is convert your infix (2 + 3) expression into a postfix (2 3 +) expression. Then you can evaluate the expression using a Stack. For each operand (number) push onto Stack. For each operator (+-*/etc) pop off 2 values from the Stack, perform operation, push result back onto Stack. Once you are done the only value left on the Stack should be the result. If you Google you should find plenty of info on how to do this.
• 07-05-2011, 01:32 AM
Jodokus
Quote:

what you need to do is convert your infix (2 + 3) expression into a postfix (2 3 +) expression.
If you need to make a parser this is A possibility (and probably the easiest to program). But you can also make other (prefix I guess) parsers. I did it myself, is was quite a project but it works great, and is far easier for the users (including me).
It is one of the projects I still borrow from the most in other projects (currently a matrixcalculator: I can just use sin2pi or sin(2pi) in my matrix which is much more palatable then 2 pi * sin (or something like that)).
• 07-05-2011, 03:24 AM
anthropamorphic
Thanks for all the suggestions I'll try them out and hopefully I will be able to figure it all out. (I'm not the best at java yet)