Reputation: 55
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("please enter the size of array");
size = br.read();
sarray = new int[size];
for (int i = 0; i < size; i++) {
sarray[i] = i;
}
System.out.println(sarray.length);
When I tried to print the length of the array, it is showing as "51" even though i gave the size as "3".
Upvotes: 4
Views: 56299
Reputation: 1
int size = Character.getNumericValue(br.read());
Reference: https://www.tutorialspoint.com/java/lang/character_getnumericvalue_codepoint.htm
Upvotes: 0
Reputation: 3785
Use readLine() method instead of read() method .
int size = Integer.parseInt(br.readLine());
read() method doesnt return the exact int value of input.
public int read() throws IOException Reads a single character. Overrides: read in class Reader Returns: The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached Throws: IOException - If an I/O error occurse
Ref : http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#read()
Upvotes: 10
Reputation: 137084
BufferedReader.read()
reads a single character and returns it as an integer (i.e. returns the ASCII code of the character).
When you input 3
to your BufferedReader
, read()
will read it as a character, i.e. as '3'
, which corresponds to the ASCII code 51.
You can verify this by executing the following code:
System.out.println((int) '3'); // prints 51
Upvotes: 6