This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I'm curious what is the most efficient means of converting from a String to Charcter and if I'm even doing it correctly. I'm reading a line of input and then trying to determine whether or not a specific Character is a digit or not. Assuming the user inputs 3*5+3, I'm trying to determine what is a digit and what is an operator to convert the String into an infix expression.
Is this not a correct way of converting the String to extract a given Character? I keep getting a compiler error when trying this code. Is there a better/simpler or in my case a correct way of doing this? Regards, Michael
Well, by default, StringTokenizer creates tokens separated by white space (space, new line, or tab). So in the example given, the first, and only token given, will be the whole expression, 3*5+3, not just a single character. In order to separate the string into individual numbers, you can use a different StringTokenizer constructor that takes a string of delimiters as the second parameter. In this case, your dilimiters will probably be "+-*/" at the very least. Add any other operators you wish to use. Since you are using StringTokenizer in this manner, you should convert the "digit" into an Integer, rather than a Character. This will allow more than just the numbers 0 through 9 in your expression. If you wish to continue with reading a single character at a time, StringTokenizer is probably the least efficient way to do it. Instead, you should write your own for loop and use the String.charAt() method. However, I think using StringTokenizer and Integer, rather than Character, is a much more flexible way to go. Layne
I don't think I'd use a tokenizer for this. You could, but I agree with Layne, it would be inefficient. I think the simplest way would be to loop through the String with the chatAt() method and use Character.isDigit() method. The method is one of the static methods of the wrapper and returns false if the character passed to it is not a digit. So you can find all the chars in the string that aren't digits, assuming in this case that they will be the operators. HTH E
My theory of evolution is that Darwin was adopted. - Steven Wright