im confused with a question which i was given, which is about bookshelf program. I have to create 2 classes called Book and BookShelf
I have more or less completed the Book class which contains these variables (id, author and title) with ( get, set , toString and constructors methods)
However for the BookShelf class, I am kind of clueless whether what i have done is correct
Here is what I am supposed to do at the BookShelf class
Create an addBook method, it takes in book object as input and adds the object into the bookshelf
returnBooks method, no parameter / arguments needed just return an arraylist of books in order
returnAuthorBooks, takes in author as input and returns an arraylist of books by the author
This is the code that i have done
import java.util.ArrayList;
import java.util.Collections;
public class BookShelf {
ArrayList<Book> listOfBooks = new ArrayList<Book>();
public void addBook(Book getTitle){
listOfBooks.add(getTitle);
}
public ArrayList<Book> returnBooks(){
ArrayList myBook = new ArrayList();
Collections.sort(myBook);
return myBook;
}
public ArrayList<Book> returnAuthor(Book author){
for (Book books : listOfBooks){
if (author.getAuthor() == books.getTitle()){
return listOfBooks;
}
}
return null;
}
}
Would like to clarify if there is any mistake here as for some reason i get the feeling that i have done something incorrect
1 Answer 1
Your returnBooks method returns an empty List. You should change
ArrayList myBook = new ArrayList();
to
ArrayList<Book> myBook = new ArrayList(listOfBooks);
In order to return a full sorted list.
Your returnAuthor method has several problems :
- It should take an author as input (I don't know if it should be a String or whether there is an Author class).
- You compare the book's authors with
==instead ofequals(see this question). - You return the entire list of books if you find a book with the author you are looking for. You should only return the books of that author.
2 Comments
books' was a typo (I'm not a native English speaker, and it has been many years since I finished learning English in high school, so I may be wrong). When you want to add 's (I forgot the name of that suffix) to a word that already ends with s (as books), you just add '. Your fix would be correct if I wanted to say the OP was comparing the authors of a single book. I wanted to say OP was comparing the authors of multiple books.
returnAuthor. For one, why are you passing aBookand not just a String with the author name, don't use==for string equality check, and you are returning the entire book list, not just the list of books by that author. Returningnullis a bad habit as well.book. For example, a variable name ofauthormakes someone reading the code think that may be a string or an Author class. Similarly forgetTitle, that's more a method name than a variable name, but don't name it justtitlebecause it's a Book object.