Question

In: Computer Science

Learning Objectives: ● review implementing the interface Comparable<T> ● programming against interfaces not objects. ● review...

Learning Objectives:

● review implementing the interface Comparable<T>

● programming against interfaces not objects.

● review reading in data from a file

● use the internet to learn about the interface Comparator<T>

● use a Comparator to provide an alternative way to order elements in a

collection

Description:

Turn in:

Turn in the assignment via Canvas

Create a package called booksthat includes 3 files: Book.java, BookApp.java, and books.csv (provided).

Class Book represents Pulitzer prize winning books that have a title, an author and a year, when they won the award. Implement the class Book exactly as specified in the UML diagram below.
You are allowed to create private methods to structure your code, but fields, constructors, and public methods must not be changed nor added or removed.

Notice that class Book implements the interface Comparable<T>. The method specified in the interface is not listed in the UML class diagram of class Book. However, the fact that Book implements Comparable<T> implies that the interface method needs to be implemented.
The interface Comparable<T> implements the natural order. In case of class Book it should sort by title.

Also notice that class Book is immutable. It has getters but no setters.

Method toString:

The toString method should return a string of the following form: name by author ( year )
Make sure to include the @Override annotation

Method getList:

Note that the method getList is underlined. Underlining a method in a UML class diagrams indicates that the method is static.
The method getList should readin the data from the csv file book.csv. If a line doesn’t follow the pattern title,author,yearthen a message should be written to the standard error stream (see sample output) The program should continue reading in the next line. NO exception should be thrown .

Please note that the sample output is only provided to help clarify the instructions. The program still needs to fulfill all the requirement when I test it with another csv file (e.g. where all lines are correct or other lines have an issue)

Write a test client called BookApp.java

● It should read in the data from the file book.csv. Two lines have an issue. Treat them as described above.

● Print the number of books that were read in.

Make sure to determine the number of books at run time. I will test your code with a different csv file.

● Sort the list in natural order and print the list

Sort the books in the list in reverse order using a Comparator<T>that is provided in class Collections

● List the book in the newly reversed order

Sample Output:

Problem reading in "No Pulitzer prize for fiction was awarded in 2012" Problem reading in "The Brief, Wondrous Life of Oscar Wao,Junot Diaz,2008" Number of books read in: 14

Sorted book list:
A Visit from the Goon Squad by Jennifer Egan (2011)
Empire Falls by Richard Russo (2002)
Gilead by Marilynne Robinson (2005)
Interpreter of Maladies by Jhumpa Lahiri (2000)
March by Geraldine Brooks (2006)
Middlesex by Jeffrey Eugenides (2003)
Olive Kitteridge by Elizabeth Strout (2009)
The Amazing Adventures of Kavalier & Clay by Michael Chabon (2001) The Goldfinch by Donna Tartt (2014)
The Hours by Michael Cunningham (1999)
The Known World by Edward P. Jones (2004)
The Orphan Master's Son by Adam Johnson (2013)
The Road by Cormac McCarthy (2007)
Tinkers by Paul Harding (2010)

Reverse order:
Tinkers by Paul Harding (2010)
The Road by Cormac McCarthy (2007)
The Orphan Master's Son by Adam Johnson (2013)
The Known World by Edward P. Jones (2004)
The Hours by Michael Cunningham (1999)
The Goldfinch by Donna Tartt (2014)
The Amazing Adventures of Kavalier & Clay by Michael Chabon (2001) Olive Kitteridge by Elizabeth Strout (2009)
Middlesex by Jeffrey Eugenides (2003)
March by Geraldine Brooks (2006)
Interpreter of Maladies by Jhumpa Lahiri (2000)
Gilead by Marilynne Robinson (2005)
Empire Falls by Richard Russo (2002)
A Visit from the Goon Squad by Jennifer Egan (2011)

Solutions

Expert Solution

//Bookapp.java

import java.util.*;
public class Bookapp
{
   public static void main(String[] args)
   {
      
       ArrayList<Book> MyBooks = Book.getList("books.csv");
       Collections.sort(MyBooks);
       //Collections.sort(MyBooks, Book.BY_AUTHOR);
       Collections.sort(MyBooks, Book.BY_DATE);
       System.out.println("\nSorted book list:");
       for(Book i: MyBooks)
       {
           System.out.println(i);
       }
       Collections.reverse(MyBooks);
       System.out.println("\nReverse order:");
       for(Book i: MyBooks)
       {
           System.out.println(i);
       }
   }

}

====================================================================

//Book.java

import java.util.*;
import java.io.*;
import java.util.regex.Pattern;

public class Book implements Comparable<Book>
{
   public static final Comparator<Book> BY_AUTHOR = new ByAuthor();
   public static final Comparator<Book> BY_DATE = new ByDate();
   private String title;
   private String author;
   private int year;
  
   public Book(String title, String author, int year)
   {
       super();
       this.title = title;
       this.author = author;
       this.year = year;
   }

   public String getTitle() {
       return title;
   }

   public String getAuthor() {
       return author;
   }

   public int getYear() {
       return year;
   }

   @Override
   //format of our string method to return
   public String toString()
   {
       return title + " by " + author + "("+year+")";              
   }

   //creates our list of books, the number of books, the file input
   //and pattern for string to compare
   public static ArrayList<Book> getList(String file)
   {
       ArrayList<Book> MyBooks = new ArrayList<Book>();
       int numOfBooks = 0;
       File readIn = new File(file);
       //parse the data to check against the following string pattern
       String pattern = "[^,]*,[^,]*,\\d{4}";
       try
       {          
           Scanner inputStream = new Scanner(readIn);
           while(inputStream.hasNext())
           {
               String data = inputStream.nextLine();
               //check each line against our string pattern
               //if it matches, increment our book count
               //create instance of Book
               //and add it to our list of Books (MyBooks)
               if(Pattern.matches(pattern, data))
               {
                   numOfBooks++;
                   String[] newString = data.split(",");
                   Book newBook = new Book(newString[0], newString[1], Integer.parseInt(newString[2]));
                   MyBooks.add(newBook);
                  
               }
               //if it does not match print error message
               else
               {
                   System.err.println("Problem reading in \""+data+"\"");
               }
           }
           System.out.println("Number of books read in: " + numOfBooks);
       }
       catch (FileNotFoundException e)
       {
           e.printStackTrace();
       }
      
       return MyBooks;
   }
   @Override
   public int compareTo(Book o) {
       // TODO Auto-generated method stub
       return this.getTitle().compareTo(o.getTitle());
   }
  
  
   private static class ByAuthor implements Comparator<Book>
   {
       public int compare(Book v, Book w)
       {
           return v.author.compareTo(w.author);
       }
   }
   private static class ByDate implements Comparator<Book>
   {
       public int compare(Book v, Book w)
       {
           return v.year - w.year;
       }
   }
}

=====================================================================

books.csv

The Goldfinch,Donna Tartt,2014
The Orphan Master's Son,Adam Johnson,2013
No Pulitzer prize for fiction was awarded in 2012
A Visit from the Goon Squad,Jennifer Egan,2011
Tinkers,Paul Harding,2010
Olive Kitteridge,Elizabeth Strout,2009
The Brief, Wondrous Life of Oscar Wao,Junot Diaz,2008
The Road,Cormac McCarthy,2007
March,Geraldine Brooks,2006
Gilead,Marilynne Robinson,2005
The Known World,Edward P. Jones,2004
Middlesex,Jeffrey Eugenides,2003
Empire Falls,Richard Russo,2002
The Amazing Adventures of Kavalier & Clay,Michael Chabon,2001
Interpreter of Maladies,Jhumpa Lahiri,2000
The Hours,Michael Cunningham,1999

========================================================================

sample output:


Related Solutions

(Implementing Interfaces) Implement the following interface and classes: a. Interface IsCompetition, which has no constants and...
(Implementing Interfaces) Implement the following interface and classes: a. Interface IsCompetition, which has no constants and two methods (see the classes below for details about what these methods should do): i. getSummary(), ii. getCompetitors() b. Class Game: A game object is associated with a home team, away team, home score, away score, and a date of competition. It should only be created using the following constructor: Game(String HTeam, String ATeam, int HScore, int AScore, LocalDate date). A game is also...
This activity will require you to apply your knowledge of interfaces – including the Comparable interface...
This activity will require you to apply your knowledge of interfaces – including the Comparable interface – in order to leverage the capabilities of the ArrayList data structure. --------- You may work individually or with a partner, but be sure that each student submits their own assignment in Canvas (and leave a comment with your partner's name if you worked with one). --------- Description: Interfaces are used to make a Class implement a behavior or set of behaviors. Recall the...
In this class add Comparable interface. In the driver program create a few objects and In...
In this class add Comparable interface. In the driver program create a few objects and In the driver program create a few objects and compare them . then create a list of those objects and sort them .A Quadratic is bigger than another Quadratic if it opens faster package pack2; /** * This is a program for defining a quadratic equation * @author sonik */ public class Quadratic { public int coeffX2 = 0; public int coeffX = 0; public...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT