当我尝试运行此方法时,我得到一个空指针异常,目标是填充booklist对象数组但不填充3个对象。当我设置booklist [0] = b
时会发生错误private Book [] booklist;
public boolean borrowBook(Book b)
{
if(booklist == null)
{
booklist[0] = b;
System.out.println(this.name+" has successfully borrowed "+b);
return true;
}
if(booklist.length < 3)
{
booklist[booklist.length] = b;
System.out.println(this.name+" has successfully borrowed "+b);
return true;
}
System.out.println(this.name+" has reached the borrowing limit! Return those books "+this.name);
return false;
答案 0 :(得分:4)
您需要ArrayList
而不是array
ArrayList<Book> booklist = new ArrayList<Book>();
public boolean borrowBook(Book b){
if(booklist.size() == 0){
booklist.add(b);
System.out.println(this.name+" has successfully borrowed "+b);
return true;
}
if(booklist.size() < 3){ //I'm not sure what you are trying to achieve here
booklist.add(booklist.size(), b);
System.out.println(this.name+" has successfully borrowed "+b);
return true;
}
System.out.println(this.name+" has reached the borrowing limit! Return those books "+this.name);
return false;
}
答案 1 :(得分:3)
试试这个。
private Book [] booklist;
public boolean borrowBook(Book b) {
if (booklist == null) {
booklist = new Book[3];
booklist[0] = b;
return true;
}
for (int i = 0; i < booklist.length; i++) {
if (booklist[i] == null) {
booklist[i] = b;
return true;
}
}
return false;
}
public static void main(String[] args) {
Book caller = new Book();
System.out.println(caller.borrowBook(new Book()));
System.out.println(caller.borrowBook(new Book()));
System.out.println(caller.borrowBook(new Book()));
System.out.println(caller.borrowBook(new Book()));
}
答案 2 :(得分:1)
同样,@ August说。
在行booklist[0] = b;
您必须先使用booklist = new Book[3];
答案 3 :(得分:1)
Java数组的大小不是动态的,可以编写一个方法来实现它。例如,
private static Book[] addBook(Book[] arr, Book b) {
int newLen = (arr == null ? 1 : arr.length + 1);
Book[] dest = new Book[newLen];
System.arraycopy(arr, 0, dest, 0, arr == null ? 0 : arr.length);
dest[newLen - 1] = b;
return dest;
}
然后你可以用它像
这样的东西public boolean borrowBook(Book b) {
if (booklist == null || booklist.length < 3) {
booklist = addBook(booklist, b);
System.out.println(this.name + " has successfully borrowed " + b);
return true;
}
System.out.println(this.name + " has reached the borrowing limit! "
+ "Return those books " + this.name);
return false;
}
或者,您可以只分配大小为n
的数组,或使用类似ArrayList
的集合。
答案 4 :(得分:1)
初始化booklist
会修复NullPointerException
,但您方法的逻辑仍然存在缺陷。您似乎想要将追加一本新书附加到已检出的图书数组中,而您的方法只会设置数组中的最后一个元素。
要解决此问题,您可以使用存储插入的最后一本书的索引的计数器。或者,我建议使用ArrayList
之类的可增长数组,它支持使用ArrayList#add
附加新元素。