Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read multiple integer values from one line in Java using BufferedReader object?

I am using BufferedReader class to read inputs in my Java program. I want to read inputs from a user who can enter multiple integer data in single line with space. I want to read all these data in an integer array.

Input format- the user first enters how many numbers he/she want to enter

And then multiple integer values in the next single line-

INPUT:

5

2 456 43 21 12

Now, I read input using an object (br) of BufferedReader

int numberOfInputs = Integer.parseInt(br.readLine());

Next, I want to read next line inputs in an array

int a[] = new int[n];

But we cannot read using this technique

for(int i=0;i<n;i++)
{
   a[i]=Integer.parseInt(br.readLine()); //won't work
}

So, is there any solution to my problem or we can't just read multiple integers from one line using BufferedReader objects

Because using Scanner object we can read this type of input

for(int i=0;i<n;i++)
{
   a[i]=in.nextInt(); //will work..... 'in' is object of Scanner class
}
like image 245
Lalit Kumar Avatar asked Aug 25 '14 18:08

Lalit Kumar


People also ask

Can BufferedReader read integer?

The BufferedReader class doesn't provide any direct method to read an integer from the user you need to rely on the readLine() method to read integers too. i.e. Initially you need to read the integers in string format.

Which method is used for reading a line of text in BufferedReader?

The readLine() method of BufferedReader class in Java is used to read one line text at a time.

Which of this method is used with BufferedReader object to read a single?

1. The read() method of BufferedReader class in Java is used to read a single character from the given buffered reader. This read() method reads one character at a time from the buffered stream and return it as an integer value.


2 Answers

Try the next:

int a[] = new int[n];
String line = br.readLine(); // to read multiple integers line
String[] strs = line.trim().split("\\s+");
for (int i = 0; i < n; i++) {
    a[i] = Integer.parseInt(strs[i]);
}
like image 159
Paul Vargas Avatar answered Nov 15 '22 08:11

Paul Vargas


Late to the party but you can do this in one liner in Java 8 using streams.

InputStreamReader isr= new InputStreamReader();
BufferedReader br= new BufferedReader(isr);

int[] input = Arrays.stream(br.readLine().split("\\s+")).mapToInt(Integer::parseInt).toArray();
like image 44
Pramod Avatar answered Nov 15 '22 09:11

Pramod