从文件读取到数组但最后一行覆盖所有其他行

Reading from file to array but last line overrides all other lines

所以我希望这是我的最后一招,因为我在编写主要代码方面取得了足够的进展,如果没有其他工作,我只会来这里。

String line = "";
try 
{   
  BufferedReader br = new BufferedReader (new FileReader("league.txt"));
  FootballClub club = new FootballClub();
    
  while ( ( line = br.readLine() ) != null )
  {
    String[] FC = line.split(",");
    club.setName(FC[0]);
    club.setLocation(FC[1]);
    club.setMatchesPlayed(Integer.parseInt(FC[2]));
    club.setWins(Integer.parseInt(FC[3]));
    club.setDraws(Integer.parseInt(FC[4]));
    club.setLosses(Integer.parseInt(FC[5]));
    club.setGoalsScored(Integer.parseInt(FC[6]));
    club.setGoalsAgainst(Integer.parseInt(FC[7]));
    club.setGoalDifference(Integer.parseInt(FC[8]));
    club.setPoints(Integer.parseInt(FC[9]));

    league.add(club);
  } 
    
  br.close(); 
} 
catch (FileNotFoundException e) { } 
catch (IOException e){ }

这是我从文本文件读取到数组的代码。文本文件如下:

Chelsea,London,0,0,0,0,0,0,0,0       
WestHam,London,0,0,0,0,0,0,0,0

问题是,当我测试程序时,两个俱乐部被添加到数组中,但是第一行的值被第二行覆盖。我一直在尝试先添加一行,然后添加第二行,直到没有行为止,但我似乎很幸运。我一直在到处寻找尝试修复它,但没有运气,它看起来确实很容易修复,但我已经筋疲力尽了,找不到它。如有任何指点和建议,我们将不胜感激。

您需要在每次迭代时创建一个 class 的新实例,否则您会一直在同一个对象上设置属性,因此只会存储最后一行。

while ((line = br.readLine()) != null){
     String[] FC = line.split(",");
     FootballClub club = new FootballClub();
     //...
}