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".
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With