【发布时间】: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<Genre>,例如ArrayList<Genre>。 3) 库应包含List<Book>,例如ArrayList<Book> -
我从来没有想过使用列表而不是数组。 + 我将代码翻译成英文以便更好地理解,这就是它的复数形式。但是感谢您的回答:)