Exception in thread "main" java.lang.NullPointerException
at com.javarush.task.task06.task0621.Solution$Cat.toString(Solution.java:56)
at java.lang.String.valueOf(String.java:2994)
at java.io.PrintStream.println(PrintStream.java:821)
at com.javarush.task.task06.task0621.Solution.main(Solution.java:33)
package com.javarush.task.task06.task0621;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/*
Родственные связи кошек
*/
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String grandfatherName = reader.readLine();
Cat catGrandfather = new Cat(grandfatherName, null, null);
String grandmotherName = reader.readLine();
Cat catGrandmother = new Cat(grandmotherName, null, null);
String fatherName = reader.readLine();
Cat catFather = new Cat(fatherName, null, catGrandfather);
String motherName = reader.readLine();
Cat catMother = new Cat(motherName, catGrandmother, null);
String sunName = reader.readLine();
Cat catSun = new Cat(sunName, catMother, catFather);
String daughterName = reader.readLine();
Cat catDaughter = new Cat(daughterName, catMother, catFather);
System.out.println(catGrandfather);
System.out.println(catGrandmother);
System.out.println(catFather);
System.out.println(catMother);
System.out.println(catSun);
System.out.println(catDaughter);
}
public static class Cat {
private String name;
private Cat mother;
private Cat father;
Cat(String name, Cat mother, Cat father) {
this.name = name;
this.mother = mother;
this.father = father;
}
@Override
public String toString() {
if (mother == null) {
return "The cat's name is " + name + ", no mother," + " father is " + father.name;
}
else if (father == null) {
return "The cat's name is " + name + ", mother is " + mother.name + ", no father";
}
else {
return "The cat's name is " + name + ", mother is " + mother.name + ", father is " + father.name;
}
}
}
}