为什么构造函数不读取库类数组中的元素?

当我说一个元素csBooks[3]时,我得到了垃圾。

public class Library {

     String address;
     public static Book[] bookLibrary = {};


      public Library(String location, Book[] s){

        address = location;

          for(int i = 0; i < bookLibrary.length-1; i++){

                bookLibrary[i] = s[i];
              }





     public static void main(String[] args) {
        // Create two libraries
       Book [] books = {new Book("The Da Vinci Code"),
                        new Book("Le Petit Prince"),
                        new Book("A Tale of Two Cities"),
                        new Book("The Lord of the Rings")};

        Book [] csBooks = {new Book("Java for Dummies"),
                          new Book("Operating Systems"),
                          new Book("Data Structures in Java"),
                          new Book("The Lord of the Rings")};



          Library firstLibrary = new Library("535 W114th St.", books);
          Library secondLibrary = new Library("1214 Amsterdam Av.", csBooks);


    }
}


这是Book Class:

public class Book {

    String title;
    boolean borrowed;

    // Creates a new Book
    public Book(String bookTitle) {
        //Implement this method
    title = bookTitle;
    borrowed = false;
    }

    // Marks the book as rented
    public void borrowed() {
        //Implement this method
    borrowed = true;
    }

    // Set the book to borrowed
    public void rented() {
    //Implement this method
    borrowed = true;
    }

    // Marks the book as not rented
    public void returned() {
    //Implement this method
    borrowed = false;
    }

    // Returns true if the book is rented, false otherwise
    public boolean isBorrowed() {
    //Implement this method
    if(borrowed){
      return true;
    } else {
                  return false;
    }
    }

    // Returns the title of the book
    public String getTitle() {
    //Implement this method
    return title;
    }

}

最佳答案

我假设bookLibrary应该保存图书馆的库存,即其中的书籍。在这种情况下,它必须是非静态的,因为您希望它为类(库)的每个实例存储不同的内容。

第二个问题是您将bookLibrary -Array创建为空。总共可以存储0个元素(书)的数组将无法存储您尝试写入其中的四个元素。更重要的是,由于您要根据bookLibrary的长度进行迭代。因此,您必须沿着bookLibrary=new Book[s.length];行在构造函数中正确设置bookLibrary数组

关于java - 图书馆和图书课,构造函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32857260/

10-09 23:03