1
所以我所做的就是創建3類:1。 庫類(主) 2. Book類(我創建其主類的對象實例) 3. LibraryException(只是爲了處理異常)如何使用類定義數組併爲其添加值(預定義參數)?
不過我百思不得其解,我無法弄清楚如何使用在書類設置的參數/設置數組,這裏是我的程序:
public class Library
{
String name;
Book[] books;
int nrBookz = 0;
public Library(String name, int nrBookz) throws LibraryException {
if(nrBookz < 500){
throw new LibraryException();
}
this.name = name;
this.nrBookz = nrBookz;
}
public void addBook(Book Book) throws LibraryException {
if(indexOf(Book) == -1){
if(nrBookz < books.length){
books[nrBookz++] = Book;
}
}
}
private int indexOf(Book Book)throws LibraryException {
for(int i = 0; i < books.length; i++){
if(books[i] == null){
throw new LibraryException("That book does not exist!");
}
else if(books[i].equals(Book)){
return i;
}
}
return -1;
}
public static void main(String[]args) throws LibraryException{
Library b = new Library("Sami Frasheri", 750);
**b.addBook(new Book("Paul Colhen - Alchemist", 138));
b.addBook(new Book("Paul Colhen - Winners Stand ALone", 139));
b.addBook(new Book("Paul Colhen - The river Piedra I sat and I cried", 140));**
}
}
。
public class Book {
String name;
int isbn;
public Book(String e, int iNr) throws LibraryException{
if(e == ""){
throw new LibraryException("Book name is not allowed to be blank/empty!!");
}
else if(iNr < 1 || iNr > 9000){
throw new LibraryException("The isbn is not within the allowed range (1 - 9000)! ");
}
name = e;
isbn = iNr;
}
public boolean equals(Object obj){
if(obj instanceof Book){
Book p = (Book)obj;
return name.toLowerCase().equals(p.getName().toLowerCase());
}
return false;
}
public String getName() {
if(name == null || name == ""){
System.out.print("name (Book) EXCEPTION TO BE ADDED!");
}
return name;
}
public void setname(String name) {
this.name = name;
}
public int getIsbn() {
if(isbn < 0){
System.out.print("ISBN (Book) EXCEPTION TO BE ADDED!");
}
return isbn;
}
public void setIsbn(int isbn) {
this.isbn = isbn;
}
}
所以我的問題是:我如何添加(書籍)或使其可能被添加到書籍數組? (見的打擊 - 在我創建新庫(類庫的對象)*帶有大膽的主要方法(Library類)
噢,我的..我很慚愧。我想這樣做的正常方式只是 '書=新集[nrBookz]「這個」' 完全忘了用... 非常感謝你,這麼簡單的事卻浪費了更多的時間在我身上比它的整個休息...該死的... 再次感謝你^^ – ShabanCoder
@ShabanCoder實際上,'books = new Book [nrBookz]'也應該可以工作,假設你的'Library'構造函數沒有名爲'books'的局部變量。 – Eran
我很困惑..它確實有效,沒有這個。也是,idk早些時候給了我一個錯誤,我可能會錯過輸入它或idk的東西。我是Java新手,所以你不得不原諒我。 反正非常感謝你救了我^^ – ShabanCoder