Получил ошибку, когда пытаюсь вывести информацию про детей. Мне понятно, что у детей "нет детей". Но честно говоря непонятно, почему так происходит. Есть мысли?
package com.javarush.task.jdk13.task08.task0824;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/*
Вся семья в сборе
*/
public class Solution {
public static void main(String[] args) {
//напишите тут ваш код
ArrayList<Human> chilrden = new ArrayList<Human>();
Human child1 = new Human("Mike",true,25);
Human child2 = new Human ("Alice",false,22);
Human child3 = new Human("Kevin",true,17);
chilrden.add(child1);
chilrden.add(child2);
chilrden.add(child3);
ArrayList<Human> parents = new ArrayList<>();
Human parent1 = new Human("Andrew",true,48,chilrden);
Human parent2 = new Human("Ira",false,45,chilrden);
parents.add(parent1);
parents.add(parent2);
Human granfa1 = new Human("Grisha",true,75,parents);
Human grandma1 = new Human("Anna",false,73,parents);
Human granfa2 = new Human("Vasya",true,74,parents);
Human grandma2 = new Human("Luda",false,69,parents);
System.out.println(granfa1.toString());
System.out.println(grandma1.toString());
System.out.println(granfa2.toString());
System.out.println(grandma2.toString());
System.out.println(parent1.toString());
System.out.println(parent2.toString());
System.out.println(child1.toString());
System.out.println(child2.toString());
System.out.println(child3.toString());
}
public static class Human {
//напишите тут ваш код
public String name;
public Boolean sex;
public int age;
public ArrayList<Human> children;
public Human (String name, boolean sex, int age, ArrayList<Human> children){
this.name = name;
this.sex = sex;
this.age = age;
Collections.addAll(this.children = children);
}
public Human(String name, boolean sex, int age) {
this.name = name;
this.sex = sex;
this.age = age;
}
public String toString() {
String text = "";
text += "Имя: " + this.name;
text += ", пол: " + (this.sex ? "мужской" : "женский");
text += ", возраст: " + this.age;
int childCount = this.children.size();
if (childCount > 0) {
text += ", дети: " + this.children.get(0).name;
for (int i = 1; i < childCount; i++) {
Human child = this.children.get(i);
text += ", " + child.name;
}
}
return text;
}
}
}