我对编码很新,所以只是想知道是否有人可以指出我正确的方向。我正在寻找一个包含Book对象的数组或数组列表的Library类,这些对象执行适当的功能,例如添加Book,编辑Books详细信息,删除Book,返回Book和借书。 / p>
到目前为止,我已经创建了以下Book类
//Instance variables
private int BookID;
private String Title;
private String Author;
private boolean On_Loan;
private int Number_of_Loans;
//Constructor
public Book(int BookID, String Title, String Author, boolean On_Loan, int Number_of_Loans){
this.BookID = BookID;
this.Title = Title;
this.Author = Author;
this.On_Loan = On_Loan;
this.Number_of_Loans = Number_of_Loans;
}
//Mutator methods
public void setBookID(int BookID){
this.BookID = BookID;
}
public void setTitle(String Title){
this.Title = Title;
}
public void setAuthor(String Author){
this.Author = Author;
}
public void setOn_Loan(boolean On_Loan){
this.On_Loan = On_Loan;
}
public void setNumber_of_Loans(int Number_of_Loans){
this.Number_of_Loans = Number_of_Loans;
}
//Accessor methods
public int getBookID(){
return BookID;
}
public String getTitle(){
return Title;
}
public String getAuthor(){
return Author;
}
public boolean getOn_Loan(){
return On_Loan;
}
public int getNumber_of_Loans(){
return Number_of_Loans;
}
}
答案 0 :(得分:0)
首先,您必须创建Book对象
然后你可以像这样创建一个Book对象数组
Book[] books = new Book[10]; //fixed list of size 10
Book b1 = new Book(); // create a book object
books[0] = b1; // assign it to be the first array element
或像这样的arraylist列表
ArrayList<Book> books = new ArrayList<Book>(); //initial empty list, no fixed size
Book b1 = new Book(); // create a book object
books.add(b1); // append it to the list
答案 1 :(得分:0)
如果它们是可变数量的书籍,使用ArrayList将是一个不错的选择,因为您可以动态添加更多书籍,这与您必须修改大小的阵列不同。
要创建Book对象的ArrayList,请使用:ArrayList<Book> books = new ArrayList<Book>();
要将图书添加到列表中:books.add(new Book());
要对书籍执行命令(即编辑详细信息),您需要知道书籍的索引,或者您可以浏览所有书籍。您可以使用.get(index)命令执行此操作,例如:
books.get(index).doSomething();
答案 2 :(得分:0)
你需要一个ArrayList<Book>
对象!要创建一个:
ArrayList<Book> books = new ArrayList<> ();
要向其添加项目,
books.add (yourBookObjectToBeAdded);
改变书籍&#39;属性,你需要先得到这本书,
books.get(theIndexOfTheBook);
建议将图书存储在变量中:
Book myBook = books.get(theIndexOfTheBook);
然后你可以使用其中一个mutator(setter),
myBook.setOn_Loan (true);
优点:
ArrayList
的大小是动态的。这基本上是使用数组列表的指南。现在你想创建一个完成所有这些工作的课程。所以它必须包含ArrayList<Book>
:
public class Library {
private ArrayList<Book> books
public Library () {
books = new ArrayList<> ();
}
public ArrayList<Book> getBooks () {
return books;
}
}
然后用户可以获取books
并对数组列表执行操作。
或者,你可以使它更抽象。您可以在课程中添加borrowBook
,returnBook
,editBook
和其他方法。例如,borrowBook
方法将如下所示:
public void borrowBook (int bookIndex) {
Book book = books.get(bookIndex);
book.setOn_Loan (true);
}