Как добавить циклом элементы и вывести их?
public static void main(String[] args) {
Human a1 = new Human("Михаил", true, 21);
Human a2 = new Human("Олег", true, 22);
Human a3 = new Human("Евгений", true, 23);
Human a4 = new Human("Катя", false, 21);
Human a5 = new Human("Игорь", true,22, a1.father, a4.mother);
Human a6 = new Human("Аня", false, 30, a1.father,a4.mother);
Human a7 = new Human("Светлана", false,22, a6.father,a6.mother);
Human a8 = new Human("Дмитрий", true,40, a1.father, a6.mother);
Human a9 = new Human("Павел", true, 33, a2.father, a7.mother);
System.out.println(a1);
System.out.println(a2);
System.out.println(a3);
System.out.println(a4);
System.out.println(a5);
System.out.println(a6);
System.out.println(a7);
System.out.println(a8);
System.out.println(a9);
}
public static class Human {
String name;
int age;
boolean sex;
Human father;
Human mother;
public Human(String name, boolean sex, int age) {
this.name = name;
this.age = age;
this.sex = sex;
}
public Human(String name, boolean sex, int age, Human father, Human mother) {
this.name = name;
this.age = age;
this.sex = sex;
this.father = father;
this.mother = mother;
}
public String toString() {
String text = "";
text += "Имя: " + this.name;
text += ", пол: " + (this.sex ? "мужской" : "женский");
text += ", возраст: " + this.age;
if (this.father != null) {
text += ", отец: " + this.father.name;
}
if (this.mother != null) {
text += ", мать: " + this.mother.name;
}
return text;
}
}
Можно как то упростить и не писать 9 раз принт?
Ответы (1 шт):
Автор решения: Artur Vartanyan
→ Ссылка
Можно упростить, использовав коллекции.
Пример:
List<Human> humansCollection = new ArrayList();
humansCollection.add(a1);
//...
for(Human a : humansCollection){ // Это цикл foreach
System.out.println(a);
}