import java.util.Random; import java.util.ArrayList; /** * This illustrates the use of an ArrayList to store a collection of books * * @author alchambers * @version sp16 */ public class BookCase{ private Random rng; private ArrayList bookCase; /** * Creates a new book case to store books */ public BookCase(){ rng = new Random(); bookCase = new ArrayList(); } /** * Adds a book to the book case * @param title the title of the book */ public void addBook(String title){ bookCase.add(title); } /** * Checks if a book is contained in the book case * @param findBook the title of the book * @return true if the book occurs in the book case, false otherwise */ public boolean containsBook(String findBook){ int i = 0; while(i < bookCase.size()){ String bookCheck = bookCase.get(i); if(bookCheck.equals(findBook)){ return true; } i++; } return false; } /** * Returns the title of a random book in the book case * @return the title of a randomly chosen book */ public String getRandomBook(){ int size = bookCase.size(); String title = bookCase.get(rng.nextInt(size)); return title; } /** * Returns a string representation of the state of the bookcase * @return a string representing the bookcase */ public String toString(){ String str = ""; int i = 0; while(i < bookCase.size()){ String title = bookCase.get(i); str += title + "\n"; // str = str + title + "\n"; i++; // i = i + 1; } return str; } }