Using System.in
directly is probably the wrong thing to do. You'll see that if your character is changed from q
to something in Russian, Arabic or Chinese. Reading just one byte is never going to match it. You are just lucky that the bytes read from console in UTF-8 match the character codes for the plain English characters.
The way you are doing it, you are looking at the input as a stream of bytes. And then, as @Sergey Grinev said, you get three characters - the actual character you entered, and the carriage return and line feed that were produce by pressing Enter.
If you want to treat your input as characters, rather than bytes, you should create a BufferedReader
or a Scanner
backed by System.in
. Then you can read a whole line, and it will dispose of the carriage return and linefeed characters for you.
To use a BufferedReader
you do something like:
BufferedReader reader = new BufferedReader( InputStreamReader( System.in ) );
And then you can use:
String userInput = reader.readLine();
To use a Scanner
, you do something like:
Scanner scanner = new Scanner( System.in );
And then you can use:
String userInput = scanner.nextLine();
In both cases, the result is a String
, not a char
, so you should be careful - don't compare it using ==
but using equals()
. Or make sure its length is greater than 1 and take its first character using charAt(0)
.