2015-05-05 46 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); 
相关问题