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
}
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]);
}