我现在在我的程序中遇到一个问题,其中一个Student类允许1本书并且它必须存储在变量_book中但是我似乎无法找到一种方法来检查一个对象是否已经被实例化了或者没有得到运行时错误。
我试过了
简化代码:
学生班级
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);
}
}
TextBook Class
public class TextBook {
String _title;
public TextBook(String title) {
_title = title;
}
public String returnTitle() {
return _title;
}
}
上面的代码会给我一个java.lang.NullPointerException
。我查看了捕获错误,但似乎不建议这样做。
答案 0 :(得分:1)
您正在检查_book.returnTitle()
是否为null
,但是,这并未考虑_book
是否为空。您可以检查_book
是否为空。这应该可以修复你的nullpointer异常。
此外,您应始终将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.
}
}