简体   繁体   中英

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
}

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

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

     }
}

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

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

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....

}


     
        

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM