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

oewdyzsn  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(257)

这个问题在这里已经有答案了

为什么我的arraylist包含添加到列表中的最后一项的n个副本(5个答案)
上个月关门了。
所以我希望这是我的最后手段,因为我做了足够的进展与主要代码,我只是来这里,如果没有其他工作。

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

问题是,当我测试程序时,两个梅花被添加到数组中,但是第一行的值被第二行覆盖。我一直在尝试先加一行,然后再加第二行,直到没有行,但我似乎很幸运。我一直在到处寻找,试图解决它,但没有运气,这似乎是一个简单的解决办法,但我烧毁了,找不到它。任何指点和建议将不胜感激。

2uluyalo

2uluyalo1#

您需要在每次迭代中创建一个新的类示例,否则您将在同一对象上设置属性,因此只存储最后一行。

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

相关问题