If it's only a simple math expression like what you showed above, it's pretty simple to roll out your own parsing algorithm. But if you deal with a more complex math expression, you are better off using JEP
SCJP 5.0, SCWCD 1.4, SCBCD 1.3, SCDJWS 1.4
Joined: Sep 09, 2008
Thanks a lot. Do you have any resources that you can point me to so that I can do this conversion?
Sorry, I just realized that JEP has been commercialized. Besides, the older version of JEP uses GPL license may not be suitable if you're doing any commercial project. Try to Google for any other free Java math expression libraries.
You will need to get a compiler book, eg Aho Sethi Lam and Ullman. That explains how strings can be parsed, and shows how to convert arithmetic to postfix. There are lots of tools available; you usually use a scanner (eg lex, flex, JFlex) and a parser eg yacc, ANTLR, CUP.
The problem is similar to the first stages in writing a compiler.
However, I still have a question (I am new to Java).
What I want to do is simply get operands (with and without fractional part) and operators separated. Code below only gives me operands. For simplicity I am considering +,-,*,/ as the candidate operators. Off course you can give me a direct expression to use, but I would appreciate if you can give an Idea of the approach to build it. I am finally trying to solve expression (infix notation) given as a String. I think, constructing a tree with operator as Non-Leaf Nodes and operand as leaf nodes and then traversing the tree would help me (Not an issue now).