shanky singh
shanky singh

Reputation: 1141

BufferedReader read() not working

I am trying to take input from an array and want to display, but for some reason, values are not getting displayed correctly.

Can anybody help me whats went wrong here?

package BufferBuilder;

import java.io.*;

public class MyArray {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter n");
        int n = Integer.parseInt(br.readLine());
        int[] input  = new int[n];
        System.out.println("Enter input element");
        for(int i=0; i<n; i++){
            input[i] = br.read();
            System.out.println(input[i]);
        }
        //System.out.println(input[n]);
    }

}

In Output : I enter n - 4 And then array value 3 ,5, 7, 9 and output I am getting 51 32 53 32

Upvotes: 1

Views: 1025

Answers (2)

Vasu
Vasu

Reputation: 22452

br.read() from BufferedReader (look below/here for Java doc) reads a single character, so you get character codes instead of integers that they represent, along with codes of any punctuation in between.

You need to use br.readLine() and convert it to an int value as shown below:

input[i] = Integer.parseInt(br.readLine());

public int read() throws IOException : Reads a single character.

UPDATE:

I got java.lang.NumberFormatException error You need to ensure that you are entering only numeric values and NOT entering spaces or else you can use the below code to trim the spaces:

input[i] = Integer.parseInt(br.readLine());

Upvotes: 4

JGC
JGC

Reputation: 12997

You should use readline instead of read in following part:

for(int i=0; i<n; i++){
     input[i] = Integer.parseInt(br.readline());
     System.out.println(input[i]);
}

Upvotes: 1

Related Questions