aspose file tools*
The moose likes Beginning Java and the fly likes Converting int --> char Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Converting int --> char" Watch "Converting int --> char" New topic
Author

Converting int --> char

Nevris
Greenhorn

Joined: Feb 09, 2000
Posts: 14
How can I convert int to char? .... here's the bit of code I'm working with ....
line = in.readLine();
ch = in.read(); //this is the line of code that i need to convert
if (ch == 1)
countOne++;
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
<code>ch = (char) in.read();</code>
should do it. The only catch is, read() could return a -1, which is outside the range of a char, so you should check for that first:
<code><pre>
int value = in.read();
if (value >= 0) {
ch = (char) value;
} else {
// nothing left to read; do something else
}
</pre></code>

"I'm not back." - Bill Harding, Twister
Nevris
Greenhorn

Joined: Feb 09, 2000
Posts: 14
well that got it to compile but i guess it's not what i was looking for. I'm trying to read in a data file and count up the occurance of each digit, the number of spaces, and the number of other characters. I can't seem to figure out how to do that. Any suggestions? I have all my counters and I know it's reading the file, but it's not reading each character seperately...
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Oops. If "in" is an InputStream, then the read() method will read a single byte, rather than a char. The simplest way around this is to wrap the InputStream in an InputStreamReader, as Readers are designed to work specifically with character-based data, and the read() method in a Reader reads a char, not a byte. It still returns it as an int, since it can also return -1, as I said before.
(In my previous answer, I was thinking you were using a Reader already. Oops.)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Converting int --> char