Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: Converting String to int
|
Posted: Nov 7, 2002 5:53 PM
|
|
Look at the answer I just posted in the C# forum here (http://www.artima.com/forums/flat.jsp?forum=76&thread=2151). It is in C#, of course, but amazingly (!) similar to what you'd do in Java. There are two additional things (besides changing the language, and API calls, which is pretty easy) you need to do to support the mathematical syntax in your examles: * First, it looks like you don't require spaces between the operators and operands (which I was using to split them up), so you would need to split things up based on the operators. You could do that with StringTokenizer as you mentioned, or even "manually." * Second, you are also performing multiple operations per string, which means you need to consider precendence. The the Calculator class in my example can already easily handle a series of operatations instead of just one, since it is using the RPN technique; you could queue up all the values then perform the operations, or perform the operations as you go, since the result of the last operation always remains at the top of the stack. The RPN implementation also makes handling of grouping and precedence a snap, should you choose to add those features.
By the way, use Integer.parseInt() to get an int out of a String, Double.parseDouble() to get a double and so on.
|
|