有一个任务从文件中逐行读取姓名和年龄,实现一个静态方法来创建该类的对象Human并将其写入List<Human>.
我已经实现了一个单独的年龄和名字的“集合”,但我不知道如何动态地实现新对象的初始化。我对newInstanse()我找到的文档中的方法一无所知。
List<Human> people = new ArrayList<>();
List<Integer> numbers = new ArrayList<>();
List<String> names = new ArrayList<>();
try (Scanner sc = new Scanner(file)) {
while (sc.hasNextLine()) {
String[] nums = sc.nextLine().replaceAll("[^\\d-]+", " ").split(" ");
for (String n : nums) {
if (!n.isEmpty()) {
numbers.add(Integer.valueOf(n));
}
}
}
while (sc.hasNextLine()) {
String[] name = sc.nextLine().replaceAll("[^A-Za-zА-Яа-я]", "").split(" ");
for (String nm : name) {
if (!nm.isEmpty()) {
names.add(nm);
}
}
}
if (!isPos(numbers)) {
try {
throw new IOException();
}
catch (IOException e){
System.out.println("Некорректный входной файл");
}
}
else {
for (int i = 0; i < names.size(); i++) {
people.add(new Human(names.get(i), numbers.get(i)));
}
}
}
catch (FileNotFoundException e) {
System.out.println("Файл не найден.");
}
System.out.println(people);
请不要留下注释try/catch,它们是根据任务条件需要的!
输出列表时,people会得到空括号 []。怎么了?
文件中的列表示例
Амир 18
Тагир 18
Хамид 18
Усман 26
Нурадил 17