billabrian6
billabrian6

Reputation: 431

Reading from a txt file into a single array - Java

I have a txt file that contains 40 names. Each name is on its own line. This method should take each name and place it into an array of 4 elements and then take that array and write those files to another txt file with use of another method.

My issue is every forth name in the list somehow ends up being null and my output txt file ends up with 10 rows and a null as the forth element in each row.

I have provided code and sample I/O below. Thanks in advance!

Sample Input

Emily
Reba
Emma
Abigail
Jeannie
Isabella
Hannah
Samantha

My method

public static void fillArray(String[] player ,String[] team, BufferedReader br) throws IOException{
  String line;
  int count = 0;

  while((line = br.readLine()) != null){
    if(count < 3){
       player[count] = line;
       count++;
    }
    else{
       count = 0;
       writeFile(player);
    }
  }
  br.close();

}

Sample Output

Emily Reba Emma null 
Jeannie Isabella Hannah null 

Upvotes: 0

Views: 221

Answers (1)

Oleg Vaskevich
Oleg Vaskevich

Reputation: 12682

Your logic is incorrect. player[3] is never set and the next loop you end up reading a line without storing it into the array. Use this:

public static void fillArray(String[] player ,String[] team, BufferedReader br) throws IOException{
  String line;
  int count = 0;

  while((line = br.readLine()) != null){
    player[count] = line;
    count++;
    if (count == 4) {
       count = 0;
       writeFile(player);
    }
  }

Upvotes: 2

Related Questions