Search code examples
javaarraysbufferedreader

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


So I wanted this to be my last resort because I did enough progress with doing the main code and I was only to come here if nothing else worked.

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

This is my code from reading from a text file into array. The text file is as follows:

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

The problem is that when I test the program, two clubs get added to the array however the values for the first line get overridden by the second line. I have been trying to get one line added first then the second until there is no line but I seem to be lucking out. I have been looking everywhere to try and fix it but no luck and it does seem like an easy fix but I'm burned out and can't find it. Any pointers and suggestions would be appreciated.


Solution

  • You need to create a new instance of the class on each iteration, otherwise you keep setting properties on the same object, so only the last line will be stored.

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