从txt文件读取到单个数组 - Java

时间:2022-10-28 21:54:00

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.

我有一个包含40个名字的txt文件。每个名字都有自己的名字。此方法应该采用每个名称并将其放入一个包含4个元素的数组中,然后使用该数组并使用另一个方法将这些文件写入另一个txt文件。

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.

我的问题是列表中的每个名称都以某种方式结束为空,我的输出txt文件以10行结尾,并且每行的第四个元素为null。

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

我在下面提供了代码和示例I / O.提前致谢!

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 

1 个解决方案

#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:

你的逻辑不正确。播放器[3]永远不会被设置,下一个循环最终会读取一行而不将其存储到数组中。用这个:

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

#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:

你的逻辑不正确。播放器[3]永远不会被设置,下一个循环最终会读取一行而不将其存储到数组中。用这个:

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