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
}
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.
The readLine() method of BufferedReader class in Java is used to read one line text at a time.
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.
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]);
}
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();
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