Hello. I try very many possible variants and don't understand what is the problem?
All is good, but the last condition is not completed:
"The program should create objects and fill them with data to get two grandfathers, two grandmothers, one father, one mother, and three children. Then it should display all the Human objects on the screen." :/ ?
package com.codegym.task.task08.task0824;
import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
public static void main(String[] args) {
Human h1 = new Human("Children1", true, 18, null);
Human h2 = new Human("Children2", true, 18, null);
Human h3 = new Human("Children3", true, 18, null);
Human h4 = new Human("Mother", false, 38, new ArrayList<Human>(Arrays.asList(h1,h2)));
Human h5 = new Human("Father", true, 48, new ArrayList<Human>(Arrays.asList(h1,h2,h3)));
Human h6 = new Human("GrandMother1", false, 68, new ArrayList<Human>(Arrays.asList(h4)));
Human h7 = new Human("GrandMother2", false, 68, new ArrayList<Human>(Arrays.asList(h5)));
Human h8 = new Human("GrandFather1", true, 78, new ArrayList<Human>(Arrays.asList(h4,h5)));
Human h9 = new Human("GrandFather2", true, 78, new ArrayList<Human>(Arrays.asList(h4,h5)));
System.out.println(h1.toString());
System.out.println(h2.toString());
System.out.println(h3.toString());
System.out.println(h4.toString());
System.out.println(h5.toString());
System.out.println(h6.toString());
System.out.println(h7.toString());
System.out.println(h8.toString());
System.out.println(h9.toString());
}
public static class Human {
String name;
boolean sex;
int age;
ArrayList<Human> children = new ArrayList<Human>();
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 += "Name: " + this.name;
text += ", sex: " + (this.sex ? "male" : "female");
text += ", age: " + this.age;
// print childrens & parents
if (children != null && this.children.size() > 0) {
int childCount = this.children.size();
for (int i = 0; i < childCount; i++) {
// prints parents
if(children.get(i).children != null && children.get(i).children.size() > 0){
text += ", partent: " + children.get(i).name + ": children:";
for(int k = 0; k < children.get(i).children.size(); k++){
if(k == 0){
text += children.get(i).children.get(k).name;
} else {
text += ", " + children.get(i).children.get(k).name;
}
}
} else {
// prints childrens
if(i == 0){
text += ", children: " + children.get(i).name;
} else {
text += ", " + children.get(i).name;
}
}
}
}
return text;
}
}
}