java - 从文件读取到数组但最后一行覆盖所有其他行
问题描述
所以我希望这是我最后的手段,因为我在编写主要代码方面取得了足够的进展,如果没有其他办法,我只会来这里。
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
问题是当我测试程序时,两个球杆被添加到数组中,但是第一行的值被第二行覆盖。我一直在尝试先添加一行,然后再添加第二行,直到没有行,但我似乎很幸运。我一直在到处寻找尝试修复它,但没有运气,它看起来确实很容易修复,但我筋疲力尽,找不到它。任何指针和建议将不胜感激。
解决方案
您需要在每次迭代时创建该类的新实例,否则您会一直在同一对象上设置属性,因此只会存储最后一行。
while ((line = br.readLine()) != null){
String[] FC = line.split(",");
FootballClub club = new FootballClub();
//...
}
推荐阅读
- regex - 上下文无关语法的正则表达式
- java - 最后如何修复 toArray 方法?
- animation - setState 不更新wiget UI
- angular - ngModel errors.pattern 属性在 Angular 模板中始终为 true
- python - 如何使用正则表达式(Python)匹配必须是字母、数字和斜线的单词?
- php - Laravel 私人频道未授权:错误 404
- nginx - 使用代理通行证时如何保留请求的端口?
- html - 提交表单后更改按钮的颜色,特别是 html 表的 tr
- r - 如何使用 quanteda::tokens_select() 删除单字符和双字符标记
- shell - 将文本粘贴为击键