gpt4 book ai didi

java - 对象数组的问题

转载 作者:行者123 更新时间:2023-12-01 05:58:50 24 4
gpt4 key购买 nike

当我尝试运行此方法时出现空指针异常,目标是填充书目对象数组但不超过 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;

最佳答案

你需要 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;
}

关于java - 对象数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26133031/

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