首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java:对象数组中的对象数组

Java:对象数组中的对象数组
EN

Stack Overflow用户
提问于 2020-05-02 16:19:47
回答 1查看 87关注 0票数 0

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

  • Books ==>包含一本书的标题
  • 体裁==>包含一个体裁的名称和一个对象数组
  • Library ==>包含一个体裁的对象数组
  • ==>包含对话框和扫描器

您将能够从app类创建新的类型数组和新的图书数组。

代码语言:javascript
复制
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
}

然而,我还不知道如何将一本书添加到它的体裁中,甚至不知道我应该如何“联系”(?)书

,如果我是正确的,我不能只做流派=新类型();图书=新图书();,因为它必须在数组(?)

如果有人能帮我,我会很高兴的,如果需要的话,我很乐意分享更多的信息。

干杯马丁

EN

回答 1

Stack Overflow用户

发布于 2020-05-02 16:26:22

你确定书的数量和类型的数量都是不变的吗?我认为将书籍和类型从数组转换为ArrayList应该有助于您实现程序的顺利运行。你不需要统计书籍的数量和类型的数量。当您使用ArrayList及其size()方法时,事情可能要简单得多。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61562606

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档