我试图通过从文件中读取它们来实例化一个对象数组(runners)。有六个不同的变量描述每个人。我试图弄清楚如何创建一个数组,在同一元素中存储这些运行器的所有相同值,同时保持每个运行器的各个部分。
文件如下所示:
{1,Gebre Gebremariam,2:08:00,,Ethiopia,ETH
2,Emmanuel Mutai,2:06:28,,Kenya,KEN
3,Geoffrey Mutai,2:05:06,,Kenya,KEN
4,Tsegaye Kebede,2:07:14,,Ethiopia,ETH
6,Jaouad Gharib,2:08:26,,Morocco,MAR
7,Meb Keflezighi,2:09:13,CA,United States,USA
8,Mathew Kisorio,2:10:58,,Kenya,KEN
10,Viktor Rothlin,2:12:26,,Switzerland,SUI
11,Bobby Curtis,2:16:44,PA,United States,USA
12,Ed Moran,2:11:47,VA,United States,USA
14,Abdellah Falil,2:10:35,,Morocco,MAR
15,Juan Luis Barrios,2:14:10,,Mexico,MEX
18,Stephen Muzhingi,2:29:10,,Zimbabwe,ZIM}
答案 0 :(得分:1)
创建一个类Runner
,其中包含构成各个参与者的六个字段的属性,然后将您的文件读入List<Runner>
或Runner[]
。
// if this is a CSV file
List<Runner> runners = new ArrayList<Runner>();
for (String[] line: csvLines){
Runner r = new Runner();
r.setName(line[0]);
r.setAge(Integer.parseInt(line[1]);
runners.add(r);
}
答案 1 :(得分:0)
以下将Runner的实例添加到ArrayList。您可能希望解析字符串以提供适当的构造函数参数。
List<Runner> runners = new ArrayList<Runner>();
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String currentLine;
for(int index = 0; (currentLine = bufferedReader.readLine()) != null; index++)
{
runners.add(new Runner(currentLine));
}
bufferedReader.close();