8

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
}
1

9 Answers 9

24

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]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

@LalitChoudhary You're welcome. Do not forget that if an answer solves your question satisfactorily, you can accept it.
11

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();

Comments

5

If you want to read integers and you didn't know number of integers

String[] integersInString = br.readLine().split(" ");
int a[] = new int[integersInString.length];
for (int i = 0; i < integersInString.length; i++) {
    a[i] = Integer.parseInt(integersInString[i]);
}

Comments

2

Integer.parseInt(br.readLine()) -> Reads a whole line and then converts it to Integers.

scanner.nextInt() -> Reads every single token one by one within a single line then tries to convert it to integer.

String[] in = br.readLine().trim().split("\\s+"); 
// above code reads the whole line, trims the extra spaces 
// before or after each element until one space left, 
// splits each token according to the space and store each token as an element of the string array.


for(int i = 0; i < n; i++)
    arr[i] = Integer.parseInt(in[i]);

// Converts each element in the string array as an integer and stores it in an integer array.

Comments

1
import java.io.*;
public class HelloWorld{

     public static void main(String []args){
        int i;
        System.out.println("enter the array element");
        InputStreamReader isr= new InputStreamReader();
        BufferedReader ib= new BufferedReader(isr);
        int a[]=new int [5];
        for(i=0;i<5;i++)
        {
            a[i]= Integer.parseInt(ib.readLine(a[i]));

        }
        for(i=0;i<5;i++)
        {
            System.out.println(a[i]);
        }

     }
}

1 Comment

Please add some explanation. The answer should be useful to a broader public, not just to the OP.
1

I use this code for List:

List<Integer> numbers = Stream.of(reader.readLine().split("\\s+")).map(Integer::valueOf).collect(Collectors.toList());

And it is almost the same for array:

int[] numbersArray = Arrays.stream(reader.readLine().split("\\s+")).mapToInt(Integer::valueOf).toArray(); 

Comments

0

You can use StringTokenizer class of java.util package. The StringTokenizer class allows an application to break a string into tokens. You can use this tokens using nextToken() method of StringTokenizer class.

You can use following constructor of StringTokenizer:

StringTokenizer(String str, String delimiter);

you can use space(" ") as delemeter.

int a[] = new int[N];
StringTokenizer st = new StringTokenizer(br.readLine() , " ");
for(int i=0 ; i<N ; i++) {
    a[i] = Integer.parseInt(st.nextToken());
}

Comments

0

Well as you mentioned there are two lines- First line takes number of integers and second takes that many number

INPUT: 5 2 456 43 21 12

So to address this and covert it into array -

String[] strs = inputData.trim().split("\\s+");  //String with all inputs 5 2 456 43 21 12

int n= Integer.parseInt(strs[0]);    //As you said first string contains the length

int a[] = new int[n];               //Initializing array of that length

for (int i = 0; i < n; i++)         
{

a[i] = Integer.parseInt(strs[i+1]);     // a[0] will be equal to a[1] and so on....

}


     
        

Comments

0

i/p:34 54

 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                                                                        
 StringTokenizer st = new StringTokenizer(br.readLine()," ");
 for(int i=0;i<st.countTokens();i++){
   a=Integer.parseInt(st.nextToken());
   b=Integer.parseInt(st.nextToken());
 }

//For fast input output for one line

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.