Solution Review
Let’s look at the solution to the tasks from the previous lesson.
Task I: Total number of books by an author
The task was to find the total number of books written by an author. Look at the code below.
public class driver{public static int authorBooks(String author, String[][] dataset){// Creating an ArrayList to keep booksArrayList<String> book = new ArrayList<String>();for(int i=0; i<dataset.length; i++) // traversing the whole dataset{/* If the name of the book’s author matches with the given author, andthe ArrayList doesn't already contain this book, then we add this book to the ArrayList*/if(dataset[i][1].equals(author) && !book.contains(dataset[i][0]))book.add(dataset[i][0]);}return book.size(); // returning the size of array list}public static void main(String args[]){reader r = new reader(); // A helper class designed to read data// Calling func that reads data from data.csv and returns in a 2D matrixString[][] dataset= r.readDataset("data.csv");// Call to the functionSystem.out.print(authorBooks("Bill O'Reilly", dataset));}}
Look at the header of the authorBooks
method at line 3. We make an ArrayList
variable, book
, at line 6. Then, we traverse all rows of the dataset
with a for
loop.
Look at line 13. If a record’s author matches with the given author
(argument passed), and we haven’t already added the book’s name of that record in book
, then we add the book’s name of that record in book
.
Lastly, we return the size of book
, which is the number of books written by the author.
Task II: All the authors in the dataset
The task was to find the names of all the authors present in the dataset. Look at the code below.
public class driver{public static ArrayList<String> allAuthors(String[][] dataset){// Creating an ArrayList to store the names of the authorsArrayList<String> author = new ArrayList<String>();for(int i=1; i<dataset.length; i++) // traversing thw whole dataset{// If the author is not already present in the ArrayList authors, then we add their name to the ArrayListif(author.contains(dataset[i][1]) == false)author.add(dataset[i][1]);}return author; // returning the authors' list}public static void main(String args[]){reader r = new reader(); // A helper class designed to read data// Calling func that reads data from data.csv and returns in a 2D matrixString[][] dataset= r.readDataset("data.csv");// Call to the functionfor(String author: allAuthors(dataset))System.out.println(author);}}
Look at the header of the allAuthors
method at ...