编写一个类方法,将数组添加到现有数组的空元素中

时间:2013-11-20 08:27:01

标签: java arrays object methods

此方法应将整个图书集添加到库对象书籍数组中。 该方法必须在当前库的末尾添加新数组,并避免覆盖库中已有的任何书籍。确保包含每本书的一份副本。 [为简单起见,通过这种方法添加的书籍不会与彼此或以前的书籍重复]。

我试图编写的方法没有正确添加数组。这是缩短的库类。

public class Library {

  Book [] books;
  int [] copies;
  int [] checkedOut;
  int numBooks;

  public Library() {
    books = new Book[400];// Array to hold each book in element
    copies = new int[400];// Array to hold number of "book" copies corresponding to the                               element in the books array. 
    checkedOut = new int[400];// Array to hold number of checked out books corresponding to the elemtn in the books array.
    numBooks = 0;// Number of unique books.
  }


 public void addMultipleBooks( Book [] b ) {

    for(int k = 0; k < b.length; k++) {
       for(int i = 0; i < books.length; i++) {
         if(books[i] == null) { numBooks = i; }
         books[numBooks] = b[k];
         copies[numBooks] = copies[numBooks] + 1;
       }
     }   
  }

}// End Library Class

addMultipleBooks应该执行以下操作:

1)在数组中的正确位置添加每本新书。  2)将每本书的份数设置为1。  3)更新numBooks。

这里是主要的新书籍对象数组,我试图通过这个方法。

Book [] buildLibrary = new Book[10];
  buildLibrary[0]  = new Book( "Ulysses", new Author("Joyce","James") );
  buildLibrary[1]  = new Book( "The Great Gatsby", new Author("Fitzgerald","F. Scott") );
  buildLibrary[2]  = new Book( "A Portrait of the Artist as a Young Man", new Author("Joyce","James") );
  buildLibrary[3]  = new Book( "Lolita", new Author("Nobokov","Vladimir") );
  buildLibrary[4]  = new Book( "Brave New World", new Author("Huxley","Aldous") );
  buildLibrary[5]  = new Book( "The Sound and the Fury", new Author("Faulkner","William") );
  buildLibrary[6]  = new Book( "Catch-22", new Author("Heller","Joseph") );
  buildLibrary[7]  = new Book( "Darkness at Noon", new Author("Koestler","Arthur") );
  buildLibrary[8]  = new Book( "Sons and Lovers", new Author("Lawrence","D.H.") );
  buildLibrary[9]  = new Book( "The Grapes of Wrath", new Author("Steinbeck","John") );

不使用arraylists你可以使用以下代码,但我同意arraylists是最简单的方法。

public void addMultipleBooks(Book [] b) {

 for(int i = 0; i < b.length; i++) {
      books[numBooks] = b[i];
      copies[numBooks]++;
      numBooks++;
     }
}   

2 个答案:

答案 0 :(得分:1)

无法更改数组的大小,因此您需要使用ArrayList而不是像Rohit Jain所说的那样,因为在添加和删除项目时可以扩展和缩短这些数据。

如果你想为它添加一个项目,你需要创建一个长度大于原始数组的全新数组,然后将所有原始数组项目移动到新数组中,然后移动新项目

是的,请使用ArrayList

答案 1 :(得分:0)

尝试修改代码以添加此方式:

for (int k = 0; k < b.length; k++) {
    for (int i = 0; i < books.length; i++) {
        if (books[i] == null) {
            numBooks = i;
            books[numBooks] = b[k];
            copies[numBooks] = copies[numBooks] + 1;
            break;
        }

    }
}

这样,只有当你的库中的书籍存储的当前插槽为空(null)时才会添加,然后继续进行下一个要添加的书籍项目(从库的书籍数组中搜索空槽开始)因为要存储的当前书已经找到了正确的插槽)