我的构造函数包含我的数组:
public Library(int maxNumberofTextBook)
{
// initialise instance variables
nextBook = 0;
numberOfBorrowers = 0;
numberOfChapters = 6;
bookShelf = new Textbook[maxNumberofTextBook + 1];
for (int i = 0; i < maxNumberofTextBook; i++)
bookShelf[i] = new Textbook("Text book number" +i, numberOfChapters);
}
在此方法中,我希望数组接受参数输入并将其添加到上面的数组中:
public void returnBook(Textbook book)
{
//add book into array//
numberOfBorrowers -- ;
bookInShelf ++ ;
}
最佳答案
从您的示例中,我看到您正在使用一个原始固定大小
数组
,
Textbook bookShelf [] = new Textbook [maxNumberofTextBook];
要添加一个新对象,您只需分配它(可能会抛出ArrayOutOfBoundException
)
public void returnBook(Textbook book)
{
if(bookInShelf < maxNumberofTextBook ){ //just to avoid the exception
bookShelf[maxNumberofTextBook - 1] = book;
numberOfBorrowers -- ;
bookInShelf ++ ;
}
}
关于Java 如何将元素添加到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58858308/