Domanda

I notice that the following line of code exists a lot. (For example on this website.)

char ch = (char) System.in.read();  // uses a char, and requires a cast.

Now to test for a particular character keystroke, or an ASCII value, or an escape sequence, etc..

if (ch == 'a' || ch == 65 || ch == '\n' || ch == 13) System.out.print("true");

Does using a char above provide any benefits over the following line of code below, which uses an int?

int i = System.in.read();  // uses an int, which requires no cast.

The int variable "i" can be used in the same if statement as previously shown, above.

È stato utile?

Soluzione

Neither approach is correct. The correct way to read characters from System.in is to use an InputStreamReader (or a Scanner if that provides the right functionality). The reason is that InputStream.read() reads a single byte, not characters, and some characters require reading more than one byte. You can also specify the character encoding to be used when converting bytes to characters.

Reader rdr = new InputStreamReader(System.in);
int i = rdr.next();
if (i == -1) {
    // end of input
} else {
    // normal processing; safe to cast i to char if convenient
}

Altri suggerimenti

There is no reason for the cast at all. This is fine

int i = System.in.read();
if(i == 'a'){
   // do something
}

You can do this, because 'a' is a value within the range of an int.

Also, be aware that doing the cast directly to a char may be problematic when reading files and such, because what InputStream.read() does is read a byte not a char. A char is two bytes wide.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top