【发布时间】:2015-07-15 09:12:08
【问题描述】:
我正在使用bufferedFileReader 和lineScanner 读取csv 文件,以逗号分隔并将行中的第一个标记分配给Team 类的对象。在此之后的每个标记都分配给Team 的变量。
这部分工作正常。下一部分是将这些对象放入一个数组中,我不知道该怎么做。我假设我需要在 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
}
}
【问题讨论】:
-
teams[someCounter++] = aTeam;? -
如果
Pool没有扩展任何东西,super()会做什么? -
@moarCoffee 除了
Object,一切都扩展了一些东西。所以它像正常一样调用父构造函数 -
@Jyr 类似于 'List
= new ArrayList();'在 while 循环之前,然后是 'ArrayListName.add(aTeam);?'在while循环结束时? -
将变量 (
someCounter) 初始化为 0 并按照 @DaveNewton 的建议进行操作。
标签: java arrays bufferedreader java-io