【问题标题】:Java: Object Array within Object ArrayJava:对象数组中的对象数组
【发布时间】:2020-05-02 16:19:47
【问题描述】:

我正在构建一个库程序,它有 4 个类:

  • Books ==> 包含书名
  • 流派 ==> 包含流派名称和书籍对象数组
  • 库 ==> 包含一个流派对象数组
  • 应用 ==> 包含对话框和扫描仪

您将能够从应用程序类创建新的流派数组和新书数组。

public class App{
  Library library = new Library();

  //the other stuff

  private void run(){
     library.addGenres(insertGenreNameHere);
  }
}


public class Library{
   private Genres[] genres = new Genres[5];    //Obj. Array of genres
   private Int nrOfGenres = 0;                 //number of how many genres there are in an array

    public void addGenres(String genreName){   //adds a new genre to the array
       if (nrOfGenres < genres.length) {
        genres[nrOfGenres] = new Genres(genreName);
        nrOfGenres++;
    }
    else {
        System.out.println("You already have the maximum of " + genres.length + " genres!");
    }
}



public class Genres {

   private String name;
   private Books[] books = new Books[5];        //Obj. Array of books
   private int nrOfBooks = 0;                   //number of how many books there are in an array

   public Genres(String name) {                 //Constructor
       this.name = name;
   }

   //getter & setter for the name of the genre

   public void addBooks(String titel){          //adds new book to the array
      if (nrOfBooks < books.length) {
         books[nrOfBooks] = new Books(titel);
         nrOfBooks++;
    }
    else {
        System.out.println("You already have the maximum of " + books.length + " books!");
    }
}

public void showBooks(){                        //prints the books line by line
    int x = 0;
    while(x < books.length && books[x] != null) {
        System.out.println(books[x].getTitle());
        x++;
    }
  }
}



public class Books(){
   private String title;

   public Books(String title){                  //Constructor
      this.title = title;
   }

   //getter & setter for the title
}

但是我还不知道如何将一本书添加到其类型中,甚至不知道我应该如何“联系”(?)一本书

如果我是正确的,我不能这样做 类型流派 = new Genre(); 书籍书籍 = new Book() ; 因为它必须在一个数组中(?)

如果有人可以帮助我,我会很高兴,如果需要,我很乐意分享更多信息

干杯 马丁

【问题讨论】:

  • 这里我根本不会使用数组。取而代之的是:1)书籍应重新命名为“书籍”,因为它代表一本书。 2) 图书应包含List&lt;Genre&gt;,例如ArrayList&lt;Genre&gt;。 3) 库应包含List&lt;Book&gt;,例如ArrayList&lt;Book&gt;
  • 我从来没有想过使用列表而不是数组。 + 我将代码翻译成英文以便更好地理解,这就是它的复数形式。但是感谢您的回答:)

标签: java arrays object


【解决方案1】:

您确定书籍的数量和类型的数量保持不变吗?我相信将书籍和流派从数组转换为 ArrayList 应该可以帮助您实现程序的平稳运行。您不需要计算书籍的数量和流派的数量。当您使用 ArrayList 及其 size() 方法时,事情会简单得多。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多