import java.util.Random; import java.util.ArrayList; /** * This illustrates the use of an ArrayList to store a collection of books * @author alchambers */ 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){ boolean found = false; int counter = 0; // In this case, a while loop is a better choice than a for loop // becauses we want to iterate WHILE found == false. In other words, // we want to iterate WHILE some state is true. You could turn this // into a for loop, but it will look a bit messier while(found == false && counter < bookCase.size()){ // Get the title of the book at that position in the list String bookTitle = bookCase.get(counter); // If findBook equals the title of the book if(findBook.equals(bookTitle)){ found = true; } // Not the book we were looking for else{ found = false; } counter++; } return found; } /** * Returns the title of a random book in the book case * @return the title of a randomly chosen book */ public String getRandomBook(){ // Get the size of the list int size = bookCase.size(); // Generate a random int between [0, size-1] int rand = rng.nextInt(size); // Get the title of the book at that random position return bookCase.get(rand); } /** * Returns a string representation of the state of the bookcase * @return a string representing the bookcase */ public String toString(){ // In this case, a for loop is the better choice because we want to // iterate over each String in the ArrayList. In other words, for // bookCase.size() iterations we want to perform some action String str = "The bookcase contains " + bookCase.size() + " books:\n"; for(int i = 0; i < bookCase.size(); i++){ String bookTitle = bookCase.get(i); str += bookTitle + "\n"; } return str; } }