For completeness¸I would like to add that there already exists a lot of code for this. I know you asked a very specific question, but the general answer would be to look at existing solutions how that is done.
Example:
Built-in method for evaluating math expressions in Java