0

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 
3
  • 1
    What is your writeFile() and where do you call fillArray()? Commented Feb 14, 2013 at 3:21
  • Why are you stopping when count < 3? That block will only execute 3 times with the current coding. Commented Feb 14, 2013 at 3:22
  • am sure you are doing something extra index value in while printing ! Commented Feb 14, 2013 at 3:26

1 Answer 1

2

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

1 Comment

Thanks for your input. That fixed it perfectly! I tend to over think sometimes.

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.