Вот, выводит первые две строчки, далее следует ошибка:
The cat's name is дедушка Вася, no mother, no father
The cat's name is бабушка Мурка, no mother, no father
java.lang.NullPointerException
at com.javarush.task.task06.task0621.Solution$Cat.toString(Solution.java:61)
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:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAcce
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);
String grandmatherName = reader.readLine();
Cat catgrandmather = new Cat(grandmatherName);
String fatherName = reader.readLine();
Cat catfather = new Cat(fatherName, null, catgrandfather);
String matherName = reader.readLine();
Cat catMather = new Cat(matherName, catgrandmather, null);
String sonName = reader.readLine();
Cat catson = new Cat(sonName, catMather, catfather);
String dochName = reader.readLine();
Cat catdoch = new Cat(dochName, catMather, catfather);
System.out.println(catgrandfather);
System.out.println(catgrandmather);
System.out.println(catfather);
System.out.println(catMather);
System.out.println(catson);
System.out.println(catdoch);
}
public static class Cat {
private String name;
private Cat parentM;
private Cat parentF;
Cat(String name) {
this.name = name;
}
Cat(String name, Cat parentM, Cat parentF) {
this.name = name;
this.parentM = parentM;
this.parentF = parentF;
}
@Override
public String toString() {
if (parentM == null && parentF == null)
return "The cat's name is " + name + ", no mother, no father";
else if(parentM == null)
return "The cat's name is " + name + ", mother is " + parentM.name + ", no father";
else if(parentF == null)
return "The cat's name is " + name + ", no mother, father is " + parentF.name;
else
return "The cat's name is " + name + ", mother is " + parentM.name + ", father is " + parentF.name;
}
}
}