![](/img/trans.png)
[英]Java - NullPointerException after initializing array and when testing array with class method
[英]Initializing an array using a method - Java
我有一个文本文件,其中包含n个运动员的名字,每个名字在新行中,并且运动员的人数在文本文件的第一行中写为int。 到目前为止,我编写的代码将读取文本文件,并使用扫描仪并创建一个包含所有数据(运动员名称)的数组。 我想知道的是,是否有可能使用一种方法为每个运动员创建一个单独的数组(我稍后将用分数/表现数据填充这些数组)。 在扫描文本文件之前,我无法初始化这些文件,因为尚不知道运动员的数量。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TextScanner {
private static void readFile(String fileName) {
try {
List<String> distance = new ArrayList<String>();
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
distance.add(scanner.next());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
readFile(args[0]);
}
}
Java的新手,对不起。 我环顾四周,似乎找不到任何信息。 谢谢
是的,这是可能的,但是Array
具有一定的局限性,因为它无法动态扩展和折叠
试试这个
创建一个具有要为运动员保留的属性的集体Athelete
说
Class Athelete{
private String name;
private Integer age;
private String skill;
// then Getters and Setters for each of these
}
并创建一个地图
Map<String,Athelete> // having `name` as Key and `athelete object` as value.
现在,从文件读取并创建Athelete对象,并将其添加到Map
。
Person p=new Person();
p.setName=nameFromFile();
// also set further attributes
map.put(p.getName,p);
您可以创建Athlete
类:
class Athlete{
String name;
int score;
Athlete(String name){
this.name = name;
}
int getScore(){return score;}
void setScore(int score){ this.score = score}
}
并将“ Athlete
实例插入数组或“列表”中:
List<Athlete> distance = new ArrayList<>();
distance.add(new Athlete('Some name'));
UPD:如果您使用Java7,请考虑使用java.nio.file.Files
代替Scanner
读取小文件。 我认为readAllLines方法对您有用。
由于Java是面向对象的语言,因此请考虑对象,在您的情况下,它似乎是运动员,成绩和表现
public class Athlete {
String name;
List<Score> scores = new ArrayList<Score>();
List<Performance> performances = new ArrayList<Performance>();
}
public class Score {
String score
}
public class Performance {
int performnce
}
所以List<String> distance = new ArrayList<String>();
这将成为List<Athlete> Athletes = new ArrayList<Athlete>();
对于文件中的每个记录,创建“运动员”对象并将名称存储在name
实例变量中。 当您获得每个特定运动员的成绩和表现时,就更新了上面已经创建的运动员对象。
更新资料
正如其他评论员所指出的那样,使用Map
而不是List
是合适的。 例如, Map<String, Athlete> athletes = new HashMap<String, Athlete>();
这样,以后在接收到乐谱和表现时进行更新变得更加容易。 同样,得分和表现也列为一名运动员,它可以具有多个得分和表现。
您可以先将所有数据(运动员名称)添加到列表中,然后再调用list.toArray(new Athlete [list.size()]); 这将为您提供所需的阵列
当然,您可以为文件中的每个记录创建一个数组。 方法签名看起来像例如
String[] readAthleteData() {...}
但是,使用诸如ArrayList之类的集合通常比数组更方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.