我的构造函数包含我的数组:

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 ++ ;
}

最佳答案

从您的示例中,我看到您使用的是原始fixed-size array

  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 ++ ;
     }

    }

10-02 09:12