gpt4 book ai didi

java - 检查 Java 中对象是否已实例化

转载 作者:行者123 更新时间:2023-11-30 03:08:43 26 4
gpt4 key购买 nike

我现在在我的程序中遇到一个问题,学生类允许读一本书,并且它必须存储在变量 _book 中,但是我似乎找不到一种方法来检查对象是否已经实例化。出现运行时错误。

我已经尝试过

  1. 将变量与 null 进行比较
  2. 访问变量内的函数来检查变量是否为 null
  3. 访问变量内的函数来检查变量是否为 0

简化代码:

学生类

public class Student {
private String _name;
private Library _collegeLibrary;
private LibraryCard _card;
private TextBook _book;

public Student(String name, Library library) {
_name = name;
_collegeLibrary = library;
System.out.println("[Student] Name: " + _name);
}

public void describe() {
String message;
message = "[Student] " + _name;
if (_book.returnTitle() == null) // returns java.lang.NullPointerException
message += " does not have a book";
else {
message += " is borrowing the book \"" + _book.returnTitle() + "\"";
}
System.out.println(message);
}
}

课本课

public class TextBook {
String _title;

public TextBook(String title) {
_title = title;
}

public String returnTitle() {
return _title;
}
}

上面的代码会给我一个 java.lang.NullPointerException 。我研究过捕获错误,但似乎不建议这样做。

最佳答案

您正在检查 _book.returnTitle() 是否为 null,但是,这并没有考虑到 _book 为 null。您可以检查 _book 是否为 null。这应该可以修复您的空指针异常。

此外,您应该始终将 if-else 子句括在大括号中。这样就更容易阅读。

更改代码的这一部分:

if (_book.returnTitle() == null) // returns java.lang.NullPointerException
message += " does not have a book";
else {
message += " is borrowing the book \"" + _book.returnTitle() + "\"";
}

对此:

if (_book == null) { // returns java.lang.NullPointerException
message += " does not have a book";
} else {
message += " is borrowing the book \"" + _book.returnTitle() + "\"";
}

此外,作为提示,您可以重写 toString 函数以准确执行 describe 函数的操作:

   @Override
public String toString() {
String message;
message = "[Student] " + _name;
if (_book == null) { // returns java.lang.NullPointerException
message += " does not have a book";
} else {
message += " is borrowing the book \"" + _book.returnTitle() + "\"";
}
return message;
}

用法:

public class SomeClass {
public static void main(String[] args) {
Student student = new Student("Student", new Library());
System.out.println(student); //Because you override #toString() you can just println the Student object.
}
}

关于java - 检查 Java 中对象是否已实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34119911/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com