wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Converting a String to Character Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Converting a String to Character" Watch "Converting a String to Character" New topic
Author

Converting a String to Character

michael bradly
Ranch Hand

Joined: Oct 06, 2000
Posts: 112
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
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
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


Java API Documentation
The Java Tutorial
Eric Fletcher
Ranch Hand

Joined: Oct 26, 2000
Posts: 188
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Converting a String to Character