Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Converting int --> char

 
Nevris
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<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>
 
Nevris
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic