gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:57:38 25 4
gpt4 key购买 nike

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

  • Books ==> 包含一本书的标题
  • Genre ==> 包含流派的名称和书籍的对象数组
  • Library ==> 包含流派的对象数组
  • 应用程序==>包含对话框和扫描仪

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

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(); 书籍 books = new Book() ;因为它必须在数组中(?)

如果有人能帮助我,我会非常高兴,并乐意在需要时分享更多信息

干杯马丁

最佳答案

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

关于Java:对象数组中的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61562606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com