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

前端 未结 9 2252
萌比男神i
萌比男神i 2021-02-06 15:39

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 rea

9条回答
  •  无人共我
    2021-02-06 16:21

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

提交回复
热议问题