Собственно, можно ли как-то в цикле вызывать конструктор и передавать ему разные параметры. Ну, то бишь дабы не создавать 9 объектов построчно.
Может массив для каждого параметра конструктора объявить и передавать в цикле значения из массива? Или есть более элегантный способ? Подскажите в какую сторону копать, пожалуйста.
Что-то такого типа имеет потенциал?
package com.javarush.task.task07.task0724;
/*
Семейная перепись
*/
public class Solution {
public static void printObjects(Human[] humans) {
for (Human human :
humans) {
System.out.println(human);
}
}
public static String[] getNames(int length) {
String[] names = new String[length];
for (int i = 0; i < names.length; i++) {
names[i] = "Human" + i;
}
return names;
}
public static boolean[] getSexes(int length) {
boolean[] sexes = new boolean[length];
for (int i = 0; i < sexes.length; i++) {
sexes[i] = (Math.round(Math.random()) == 1) ? true : false;
}
return sexes;
}
public static int[] getAges(int length) {
int[] ages = new int[length];
for (int i = 0; i < ages.length; i++) {
int max = 99;
int min = 1;
int range = max - min + 1;
ages[i] = (int) (Math.random() * range) + 1;
}
return ages;
}
public static Human[] humansCreation(int size, int withoutParents){
int pointer = 0;
String[] names = getNames(size);
boolean[] sexes = getSexes(size);
int[] ages = getAges(size);
Human[] humans = new Human[size];
Human[] fathers = new Human[size];
Human[] mothers = new Human[size];
for (int i = 0; i < size; i++) {
if (i < withoutParents) {
humans[i] = Human.humanFactory(names[i], sexes[i], ages[i], null, null);
fathers[i] = humans[i];
mothers[i] = humans[i];
} else {
humans[i] = Human.humanFactory(names[i], sexes[i], ages[i], fathers[pointer], mothers[pointer]);
pointer++;
}
}
return humans;
}
public static void main(String[] args) {
// напишите тут ваш код
Human[] humans = humansCreation(9,4);
printObjects(humans);
}
public static class Human {
// напишите тут ваш код
private String name;
private boolean sex;
private int age;
private Human father, mother;
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 father, Human mother) {
this.name = name;
this.sex = sex;
this.age = age;
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;
}
public static Human humanFactory(String name,
boolean sex,
int age,
Human father,
Human mother) {
{
Human human = null;
if (father == null && mother == null) {
human = new Human(name, sex, age);
} else {
human = new Human(name, sex, age, father, mother);
}
return human;
}
}
}
}
}