package com.codegym.task.task08.task0824;
/*
Make a family
*/
import java.util.*;
public class Solution {
public static void main(String[] args) {
//write your code here
Human daughter = new Human("Lili",false,2);
Human son = new Human("Xing",true,1);
Human son1 = new Human("Sheng",true,3);
Human father = new Human("Dave",true,28,daughter,son,son1);
Human mother = new Human("Cynthia",false,24,daughter,son,son1);
Human grandfather1 = new Human("Guo",true,55,father);
Human grandfather2 = new Human("Chao",true,56,mother);
Human grandmother1 = new Human("Yu",false, 55, father);
Human grandmother2 = new Human("Lian",false,56,mother);
System.out.println(son.toString());
System.out.println(son1.toString());
System.out.println(daughter.toString());
System.out.println(father.toString());
System.out.println(mother.toString());
System.out.println(grandmother1.toString());
System.out.println(grandmother2.toString());
System.out.println(grandfather1.toString());
System.out.println(grandfather2.toString());
}
public static class Human {
//write your code here
String name;
boolean sex;
int age;
ArrayList<Human> children = new ArrayList<Human>();
public Human(String name, boolean sex,int age){
this.name = name;
this.sex = sex;
this.age = age;
}
public Human(String name,boolean sex,int age, Human ...human){
this.name = name;
this.sex = sex;
this.age = age;
for(Human h: human){
this.children.add(h);
}
}
public String toString() {
String text = "";
text += "Name: " + this.name;
text += ", sex: " + (this.sex ? "male" : "female");
text += ", age: " + this.age;
int childCount = this.children.size();
if (childCount > 0) {
text += ", children: " + this.children.get(0).name;
for (int i = 1; i < childCount; i++) {
Human child = this.children.get(i);
text += ", " + child.name;
}
}
return text;
}
}
}
I have figured out this way to do the variable-length arguments. However, I think there might be a better way to print all objects from a class, Is there a way to print all objects from a class?Better way to print?
Under discussion
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Mike McKenna
23 December 2019, 02:45
Hi ,
in my code i used ArrayList through out. included Collections to simplify print function .< Collections.addAll(parents, sonA, sonB, sonC);>
hope i helped
0
Olek
22 December 2019, 21:47
You can try to do it in a more general way:
0