Почему выбивает
java.lang.NullPointerException
at com.javarush.task.task08.task0824.Solution$Human.toString(Solution.java:62)
at java.lang.String.valueOf(String.java:2994)
at java.io.PrintStream.println(PrintStream.java:821)
at com.javarush.task.task08.task0824.Solution.main(Solution.java:36)
и почему не выводит детей?
package com.javarush.task.task08.task0824;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
/*
Собираем семейство
*/
public class Solution {
public static void main(String[] args) {
Human child1 = new Human("Микита", true, 10, null);
Human child2 = new Human("Оксана", false, 8, null);
Human child3 = new Human("Серьго", true, 5, null);
ArrayList<Human> children = new ArrayList<>(3);
children.add(child1);
children.add(child2);
children.add(child3);
ArrayList<Human> childrenDad = new ArrayList<>(2);
ArrayList<Human> childrenMom = new ArrayList<>(2);
Human father = new Human("Грицько", true, 40, children);
childrenDad.add(father);
Human mother = new Human("Света", false, 38, children);
childrenMom.add(mother);
Human ded1 = new Human("Панас", true, 73, childrenDad);
Human ded2 = new Human("Михайло", true, 70, childrenMom);
Human baba1 = new Human("Стася", false, 71, childrenDad);
Human baba2 = new Human("Люба", false, 69, childrenMom);
System.out.println(ded1);
System.out.println(ded2);
System.out.println(baba1);
System.out.println(baba2);
System.out.println(father);
System.out.println(mother);
System.out.println(child1);
System.out.println(child2);
System.out.println(child3);
}
public static class Human {
String name;
boolean sex;
int age;
ArrayList<Human> children;
public Human(String name, boolean sex, int age, ArrayList<Human> children) {
this.name = name;
this.sex = sex;
this.age = age;
this.children = children;
}
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;
}
}
}