Java 将对象实例指定给数组
我正在使用Java 将对象实例指定给数组,java,arrays,bufferedreader,java-io,Java,Arrays,Bufferedreader,Java Io,我正在使用bufferedFileReader和lineScanner来读取csv文件,在逗号处划界,并将行中的第一个标记分配给类Team的对象。之后的每个标记都分配给Team变量 我这部分工作得很好。下一部分是将这些对象放入一个数组中,我不知道该怎么做。我假设我需要在while循环的底部放置更多的代码(可能是for循环),但我不确定 课程代码为: public class Pool { /* instance variables */ private String poolName
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
}
}
将此添加到您的属性中:
private List<Team> myTeam=new ArrayList<Team>();
如果绝对必须是数组
而不是数组列表
,则在循环后执行此操作:
Team[] myArray=new Team[myTeam.size()];
myTeam.toArray(myArray);
teams[someCounter++]=aTeam
?如果Pool
不扩展任何东西,super()
会做什么?@moarCoffee除了对象
之外,所有东西都扩展了一些东西。所以它调用父构造函数就像normal@Jyr类似于'List=newarraylist();'在while循环之前,然后是“ArrayListName.add(aTeam);?”在while循环结束时,将变量(someCounter
)初始化为0,然后按照@DaveNewton的建议执行。teamCounter
需要在loadTeams()
中初始化,而不是在构造函数中初始化。
Team[] myArray=new Team[myTeam.size()];
myTeam.toArray(myArray);
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;
}
}