Вообще не очень понял задание и соответственно не очень понял, что сделал.
При компиляции выдает какую то ошибку про валидацию я вообще молчу.
Что не так?
package com.javarush.task.task08.task0824;
import java.util.ArrayList;
import java.util.List;
/*
1. Создай класс Human с полями имя (String), пол (boolean), возраст (int), дети (ArrayList<Human>).
2. Создай объекты и заполни их так, чтобы получилось: два дедушки, две бабушки, отец, мать, трое детей.
3. Выведи все объекты Human на экран (Подсказка: используй метод toString() класса Human).*/
public class Solution {
public static void main(String[] args) {
Human child1 = new Human("Child1", true, 12);
Human child2 = new Human("Child2", true, 14);
Human child3 = new Human("Child3", false, 16);
ArrayList<Human> children = new ArrayList<>();
children.add(child1);
children.add(child2);
children.add(child3);
Human father = new Human("father", true, 35, children);
ArrayList<Human> fatherArray = new ArrayList<>();
fatherArray.add(father);
Human mother = new Human("Mother", false, 35, children);
ArrayList<Human> motherArray = new ArrayList<>();
motherArray.add(mother);
Human grandpa1= new Human("grandpa1", true, 62, fatherArray);
Human grandpa2= new Human("grandpa1", true, 65, motherArray);
Human grandma1= new Human("grandma1", false, 64, fatherArray);
Human grandma2= new Human("grandma2", false, 67, motherArray);
ArrayList<Human>all=new ArrayList<>();
all.addAll(children);
all.addAll(fatherArray);
all.addAll(motherArray);
all.add(grandma1);
all.add(grandma2);
all.add(grandpa1);
all.add(grandpa2);
for (Human human:all) {
System.out.println(human.toString());
}
}
public static class Human {
String name;
boolean sex;
int age;
ArrayList<Human> children;
public Human(String name, boolean sex, int age) { //для детей
this.name = name;
this.sex = sex;
this.age = age;
this.children = null;
}
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;
}
}
}
ГогаNPE) - исключение нулевого указателя, (возникает, когда ссылочная переменная есть, а объект ей не присвоен, и пытаемся обратиться к методу объекта). и ниже - название функции, и номер строки, где исключение возникло. Т.е. у переменной children значение null. Изучаем конструкторы - бинго! Виноват конструктор //для детей. Вот как-то так решаются проблемы с кодом - сообщения об ошибках надо читать, гуглить, пытаться понять, о чем они говорят.