所以我做的是创建3个类: 1.图书馆类(主要) 2. Book Class(我在主类上创建了它的对象实例) 3. LibraryException(只是为了处理异常)
但是我很困惑,我无法弄清楚如何使用带有Book类中设置的参数/设置的数组,这是我的程序:
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;
}
}
所以我的问题是:如何添加(书籍)或者可以添加到书籍数组? (请参阅打击 - 在我创建新库(类库的对象)之后*在主方法上标记为粗体(库类)
答案 0 :(得分:0)
您缺少阵列初始化:
public Library(String name, int nrBookz) throws LibraryException {
if(nrBookz < 500){
throw new LibraryException();
}
this.name = name;
this.nrBookz = nrBookz;
this.books = new Book[nrBookz]; // add this
}