[英]How do I use an class defined array and add values (pre-defined parameters) to it?
so what I did was create 3 classes: 1. Library Class (main) 2. Book Class (which I created an object instance of it on the main class) 3. LibraryException (just to handle exceptions) 所以我要做的是创建3个类:1.库类(主)2.书本类(我在主类上创建了它的对象实例)3. LibraryException(仅用于处理异常)
However I am puzzled, I cannot figure out how to use the Array with the parameters / settings set in the Book class, here is my program: 但是我很困惑,我无法弄清楚如何使用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;
}
}
So my question is: How can I add (books) or make it possible to be added to the book array? 所以我的问题是:如何添加(书籍)或使其可以添加到书籍数组中? (see blow - after I create the new Library (object of the class Library) *Marked with bold on the main method (Library class)
(请参见打击-在创建新的Library(类Library的对象)之后*在主方法(Library类)上标记为粗体
You are missing the array initialization : 您缺少数组初始化:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.