ublic 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 grannyName = reader.readLine();
Cat catGranny = new Cat(grannyName);
String fatherName = reader.readLine();
Cat catFather = new Cat(fatherName, catGrandFather);
String motherName = reader.readLine();
Cat catMother = new Cat(motherName, catGranny);
String sonName = reader.readLine();
Cat catSon = new Cat(sonName, catMother,catFather);
String daughterName = reader.readLine();
Cat catDaughter = new Cat(daughterName, catMother, catFather);
System.out.println(catGrandFather);
System.out.println(catGranny);
System.out.println(catFather);
System.out.println(catMother);
System.out.println(catSon);
System.out.println(catDaughter);
}
public static class Cat {
private String name;
private Cat parent;
private Cat mother;
private Cat father;
Cat(String name) {
this.name = name;
}
Cat(String name, Cat mother) {
this.name = name;
if(mother != null)
this.parent = mother;
else this.parent = father;
}
Cat(String name, Cat mother, Cat father) {
this.name = name;
this.parent = mother;
this.parent = father;
}
@Override
public String toString() {
if (parent.mother == null && parent.father == null)
return "The cat's name is " + name + ", no mother, " + " no father";
if (parent.mother != null && parent.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;
}
}
}
При попытке компиляции выкидывает ошибку Нулл поинтер.
Подскажите что не так, пожалуйста
Карбофос Огарин
14 уровень
NullPointerException
Обсуждается
Комментарии (3)
- популярные
- новые
- старые
Для того, чтобы оставить комментарий Вы должны авторизоваться
Павел Безумный учёный Expert
10 января 2021, 13:53
NPE возникает в методе toString() при попытке доступа к полю несуществующего объекта (прежде всего parent.mother). Когда Вы создаёте кота-деда catGrandFather, в конструктор передаётся только имя кота; поля parent, mother и father при этом остаются не инициализарованными, т. е. имеют значение null. При вызове метода toString() на объекте кота-деда происходит обращение к полю parent без его предварительной проверки на null, что и приводит к генерации исключения.
Строго говоря, в самом поле parent нет необходимости, поскольку имеются поля mother и father. При создании кота Вы передаёте в конструктор его имя, а также ссылки на котов-родителей:
Тогда проверка в методе toString() может выглядеть, к примеру, так:
0
Карбофос Огарин
10 января 2021, 13:58
Благодарю!
С этим я уже разобрался. Теперь у меня проблема, что валидатор не пропускает решение, хотя в консоль всё выводится корреткно. ПО классике, ругается начиная с папы.
0
Павел Безумный учёный Expert
10 января 2021, 14:07
Проверьте пробелы и знаки препинания в выводе. Один лишний пробел может влиять на результат.
+2