Hi, I don't understand why I get a null pointer exception in line 67, and what's wrong with my code?
Can someone help me, thank you :-)
package com.codegym.task.task08.task0824;
import java.util.ArrayList;
/*
Make a family
*/
public class Solution {
public static void main(String[] args) {
ArrayList<Human> children = new ArrayList<>();
Human child1 = new Human("Anita", false, 30);
children.add(child1);
Human child2 = new Human("Allan", true, 27);
children.add(child2);
Human child3 = new Human("Katrine", false, 24);
children.add(child3);
Human grandfather1 = new Human("Jens", true, 90);
Human grandfather2 = new Human("Børge", true, 86);
Human grandmother1 = new Human("Else", false, 90);
Human grandmother2 = new Human("Olfa", false, 90);
Human father1 = new Human("Henrik", true, 52, children);
Human mother1 = new Human("Signe", false, 60, children);
System.out.println(grandfather1.toString());
System.out.println(grandfather2.toString());
System.out.println(grandmother1.toString());
System.out.println(grandmother2.toString());
System.out.println(father1.toString());
System.out.println(mother1.toString());
for (Human child : children) {
System.out.println(child);
}
}
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;
}
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;
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;
}
}
}