изначально написал в методе такое:
public String toString() {
if (mother == null & father == null)
return "The cat's name is " + name + ", no mother, no father ";
if (mother == null & father != null)
return "The cat's name is " + name + ", no mother, father is " + father;
if (mother != null & father == null)
return "The cat's name is " + name + ", mother is " + mother + ", no father";
if (mother != null & father != null)
return "The cat's name is " + name + ", mother is " + mother + ", father is " + father;
}
и почему-то не компилит так, пишет "missing return statement", но как бы return есть в каждом if. Можно подумать что ни один if не true - но вроде же все варианты описаны в четырёх if -ах.
После заменил код метода на тот, что в примере ниже(менее наглядный и выглядящий менее красиво) и всё заработало.
Почему не работает первый вариант?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 grandDadName = reader.readLine();
Cat grandDad = new Cat(grandDadName, null, null);
String grandMomName = reader.readLine();
Cat grandMom = new Cat(grandMomName, null, null);
String dadName = reader.readLine();
Cat dad = new Cat(dadName, null, grandDad);
String momName = reader.readLine();
Cat mom = new Cat(momName, grandMom, null);
String sonName = reader.readLine();
Cat son = new Cat(sonName, mom, dad);
String daughterName = reader.readLine();
Cat daughter = new Cat(daughterName, mom, dad);
System.out.println(grandDad);
System.out.println(grandMom);
System.out.println(dad);
System.out.println(mom);
System.out.println(son);
System.out.println(daughter);
}
public static class Cat {
private String name;
private Cat mother;
private Cat father;
//Cat(String name) {
// this.name = name;
//}
Cat(String name, Cat mother, Cat father) {
this.name = name;
this.mother = mother;
this.father = father;
}
@Override
public String toString() {
if (mother == null & father == null)
return "The cat's name is " + name + ", no mother, no father ";
else{
if (mother == null & father != null)
return "The cat's name is " + name + ", no mother, father is " + father.name;
else{
if (mother != null & 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;
}
}
}
}
}