I am writing a program that simulates a simple library. It compiles with no exceptions. However, it keeps printing when the printAvalibleBooks() method is called. the exact same book even though I have a method that is supposed to poplalate the array here is what I have so far.
public class Library {
Book[] books = new Book[20];;
int numBooks = 0;
String address;
static String hours;
public Book addBook(String bookTitle) { //This where I am having trouble populating my array
books[numBooks] = new Book(bookTitle);
++numBooks;
return books[numBooks];
}
public boolean borrowBook(String title) { //Marks the book as borrowed
if (Book.title == Book.getTitle()){
Book.borrowed = true;} //refers to a method in another class I created
return Book.borrowed;
}
public boolean returnBook(String title) { //Marks the book as returned
if (Book.title == Book.getTitle()){
Book.borrowed = false; }//refers to a method in another class I created
return Book.borrowed;
}
public Library(String street) { //creates new street address
street = address;
}
public String printAddress() { //returns the street address when referenced
return address;
}
void printAvailableBooks() { //supposed take a book out of the list if borrowed
for(int i = 0; i < numBooks; i++) {
if (i < 0) {
System.out.println("There are no books avalible");
break;
}
else System.out.println(books[i].getTitle());
}
}
static String printOpeningHours() {
hours = "We are open from 9-5.";
return hours;
}
public static void main(String[] args){
Library firstLibrary = new Library("10 Main St."); // Create two libraries
Library secondLibrary = new Library("228 Liberty St.");
firstLibrary.addBook("The Da Vinci Code");// This is where I am getting my exception
firstLibrary.addBook("Le Petit Prince");
firstLibrary.addBook("A Tale of Two Cities");
firstLibrary.addBook("The Lord of the Rings");
System.out.println("Library hours:"); // Print opening hours and the addresses
printOpeningHours();
System.out.println(hours);
System.out.println("Library addresses:");
firstLibrary.printAddress();
secondLibrary.printAddress();
// Try to borrow The Lords of the Rings from both libraries
System.out.println("Borrowing The Lord of the Rings:");
firstLibrary.borrowBook("The Lord of the Rings");
firstLibrary.borrowBook("The Lord of the Rings");
secondLibrary.borrowBook("The Lord of the Rings");
// Print the titles of all available books from both libraries
System.out.println("Books available in the first library:");
firstLibrary.printAvailableBooks();
System.out.println("Books available in the second library:");
secondLibrary.printAvailableBooks();
// Return The Lords of the Rings to the first library
System.out.println("Returning The Lord of the Rings:");
firstLibrary.returnBook("The Lord of the Rings");
// Print the titles of available from the first library
System.out.println("Books available in the first library:");
firstLibrary.printAvailableBooks();
}
}
Thanks.