2015-05-05 45 views
0

我使用bufferedFileReaderlineScanner通過csv文件的讀取,在逗號定界和分配在該行的第一個標記到Team類的對象。在此之後的每個標記被分配給變量Team分配對象的實例爲數組

我有這部分工作正常。接下來的部分是把這些對象放到一個Array中,我不知道該怎麼做。我假設我需要在while循環的底部放置更多代碼(也許是for循環),但我不確定。

代碼的類是:

public class Pool 
{ 
    /* instance variables */ 
    private String poolName; // the name of the pool 
    private Team[] teams; // the teams in the pool 
    private final static int NOOFTEAMS = 5; // number of teams in each pool 

    /** 
    * Constructor for objects of class Pool 
    */ 
    public Pool(String aName) 
    { 
     super(); 
     this.poolName = aName; 
     this.teams = new Team[NOOFTEAMS]; 
    } 

    /** 
    * Prompts the user for the name of the text file that 
    * contains the results of the teams in this pool. The 
    * method uses this file to set the results of the teams. 
    */ 
    public void loadTeams() 
    { 
     String fileName; 
     OUDialog.alert("Select input file for " + this.getPoolName()); 
     fileName = OUFileChooser.getFilename(); 
     File aFile = new File(fileName); 
     BufferedReader bufferedFileReader = null; 

     try 
     { 
     Scanner lineScanner; 
     bufferedFileReader = new BufferedReader(new FileReader(aFile)); 
     String correctPool = bufferedFileReader.readLine(); 

     if (!poolName.equals(correctPool)) 
     { 
      OUDialog.alert("Wrong File Selected");   
     } 
     else 
     { 
      String currentLine = bufferedFileReader.readLine(); 
      while (currentLine != null) 
      { 
       lineScanner = new Scanner(currentLine); 
       lineScanner.useDelimiter(","); 
       Team aTeam = new Team(lineScanner.next()); 
       aTeam.setWon(lineScanner.nextInt()); 
       aTeam.setDrawn(lineScanner.nextInt()); 
       aTeam.setLost(lineScanner.nextInt()); 
       aTeam.setFourOrMoreTries(lineScanner.nextInt()); 
       aTeam.setSevenPointsOrLess(lineScanner.nextInt()); 
       currentLine = bufferedFileReader.readLine(); 
       aTeam.setTotalPoints(aTeam.calculateTotalPoints()); 
       //somewhere here I need to add the aTeam object to the array 

      } 
     } 
+3

'隊[someCounter ++] = ATEAM;'? –

+1

如果'Pool'沒有擴展任何東西,'super()'會做什麼? – moarCoffee

+0

@moarCoffee除了'Object'之外,所有東西都有所擴展。所以它像普通的那樣調用父構造器 – Kon

回答

0
public class Pool 
{ 
    private int teamCounter; 
    ... 

    public Pool(String aName) 
    { 
     super(); 
     this.poolName = aName; 
     this.teams = new Team[NOOFTEAMS]; 
     teamCounter=0; 
    } 

    ... 

    public void loadTeams() 
    { 
     ... 
     //somewhere here I need to add the aTeam object to the array 
     this.teams[teamCounter++]=aTeam; 

    } 
} 
+0

'teamCounter'需要在'loadTeams()'中初​​始化,而不是構造函數。 – moarCoffee

2

添加到您的屬性:

private List<Team> myTeam=new ArrayList<Team>(); 

然後在循環中加入這一行結尾:

myTeam.add(aTeam); 

如果絕對它必須是array而不是ArrayList然後在循環後執行此操作:

Team[] myArray=new Team[myTeam.size()]; 
myTeam.toArray(myArray); 
相關問題