Reputation: 898
I am learning Java and while studying try catch loop, I encountered this weird behaviour.
Whatever number I supply to the below code, it returns something between 49 - 53.
public class demo{
public static void main(String[] args) {
System.out.println("Enter a number");
try{
int num = System.in.read();
System.out.println(num);
}catch(Exception e){
e.printStackTrace();
}
}
}
Upvotes: 2
Views: 307
Reputation: 1043
InputStream.read() reads only the next byte of data:
http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read()
If you'll need to read more than 1 byte of data at a time, try using a BufferedInputStream: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedInputStream.html or a reader: https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html
Beware of simply casting an int produced by InputStream.read to char - it will only work if your character set is ISO-8859-1. Hence, a Reader with appropriate Charset is a good option.
Upvotes: 0
Reputation: 178243
You must have entered numbers 1-5. The read()
method of InputStream
(System.in
is an InputStream
) returns the byte value as an int
, but the value is the Unicode code. The characters '1'
through '5'
are represented by the codes 49-53. In fact, '0'
through '9'
are represented by the codes 48-57.
Don't call read
directly on the InputStream
. It's meant for low-level stream processing. Instead, wrap the InputStream
in a Scanner
and call nextInt()
.
Upvotes: 7
Reputation: 35011
InputStream.read() returns an integer. You should do char c = (char) myInt; to convert it to a character if that's what you want
Upvotes: 1