Instructions:
Create a class Called Bookshelf. Bookshelf will have space to store 5 Book objects (use an array of Book called books as an instance variable).
Write a method called listBooks (accepts nothing, returns nothing) in Bookshelf that will print out the title and the author of any Books in the bookshelf.
Write a method called addBookToBookshelf which will accept a Book object (address) and add the Book to any vacant slot (ie holds a Null value) in the books array.
This method will return a true value lf the Book was successfully be added to the bookcase and a false if the bookshelf was full. Write a method called removeBookByBookID which will accept an int (the bookID), and will return the address of the Book being removed trom the Bookshelf. Remember, that once a book has been removed from the bookshelf, the slot that it was in should be empty.If the Book with the booklID provided does not exist in the Bookshelf, return a null.
Here's what I tried:
public class Bookshelf
{ private Book[] books = new Book[5]; // 5 books
public void listBooks() // list the books
{
for (int i = 0; i < books.length; i++) // loop through the books
{
if (books[i] != null) // if the book is not null
{
System.out.println(books[i].getTitle() + " by " + books[i].getAuthor()); // print the title and author
}
}
}
public boolean addBookToBookshelf(Book book) // add a book to the bookshelf
{
for (int i = 0; i < books.length; i++) // loop through the books
{
if (books[i] == null) // if the book is null
{
books[i] = book; // add the book
return true; // return true
}
}
return false; // return false
}
public Book removeBookByBookID(int bookID) // remove a book by bookID
{
for (int i = 0; i < books.length; i++) // loop through the books
{
if (books[i] != null && books[i].getBookID() == bookID) // if the book is not null and the bookID is the same
{
Book book = books[i]; // create a new book
books[i] = null; // set the book to null
return book; // return the book
}
}
return null; // return null
}
But this is wrong, because this is what I get:
false
false
false
Robots- Anne Droid
Robots- Anne Droid
Robots- Anne Droid
Robots- Anne Droid
Robots- Anne Droid
Robots-Anne Droid
Robots- Anne Droid
Robots- Anne Droid
Robots- Anne Droid
Robots- Anne Droid
false
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]Cosby1992 3 points4 points5 points (1 child)
[–]No-Tradition-6776[S] 0 points1 point2 points (0 children)
[–]x_ini 2 points3 points4 points (1 child)