import java.util.ArrayList; import java.util.Random; /** * This class stores a list of books * @author cs161 * @version spring2019 */ public class BookCase{ // Instance variables private int numBooks; private ArrayList books; private Random rng; /** * Creates a new empty bookcase */ public BookCase(){ numBooks = 0; books = new ArrayList(); rng = new Random(); } /** * Adds a book to the book case * @param title The title of the book * @param author The author of the book */ public void addBook(String title, String author){ Book b = new Book(title, author); books.add(b); numBooks++; } /** * 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 bookCount = books.size()-1; // NOTE: THIS SHOULD BE A FOR LOOP. WHY? while(bookCount >= 0){ Book curr = books.get(bookCount); String currTitle = curr.getTitle(); if(findBook.equals(currTitle)){ return true; } bookCount--; } return false; } private boolean isValid(int position){ return position < books.size() && position >= 0; } /** * Removes a book from the list * @param currPosition The index of the book to be moved */ public void removeBook(int currPosition){ if(isValid(currPosition)){ books.remove(currPosition); } } /** * Moves the book at the specified index to the first spot * in the book case * @param currPosition The index of the book to be moved */ public void promoteBook(int currPosition){ if(isValid(currPosition)){ Book selected = books.remove(currPosition); books.add(0, selected); } } /** * Returns the title of a random book in the book case * @return The title of a randomly chosen book */ public String getRandomBook(){ int index = rng.nextInt(numBooks); Book chosen = books.get(index); String title = chosen.getTitle(); return title; } /** * Returns a string representation of the state of the bookcase * @return A string representing the bookcase */ public String toString(){ // NOTE: THIS SHOULD BE A FOR-LOOP. WHY? int place = 0; String s = ""; while(place < books.size()){ Book selected = books.get(place); String info = selected.toString(); s = s + info + "\n"; place++; } return s; } }