3. The Book class is used to store information about a book in a library. A partial declaration of the Book class is shown.
public class Book
{
/**
* Returns the genre of the book
*/
public String getGenre()
{ /* implementation not shown */ }
/**
* Returns the number of pages in the book
*/
public int getPages()
{ /* implementation not shown */ }
/**
* Returns true if the book is currently available to be borrowed
* and returns false otherwise
*/
public boolean isAvailable()
{ /* implementation not shown */ }
/* There may be instance variables, constructors, and
methods that are not shown. */
}public class Library
{
/** The list of all books in the library */
private ArrayList<Book> collection;
/**
* Returns the average number of pages of the available books
* in collection whose genre is equal to targetGenre
* Precondition: targetGenre is not null
* At least one available element of
* collection has a genre equal to targetGenre.
* No elements of collection are null.
*/
public double averagePagesForGenre(String targetGenre)
{ /* to be implemented */}
/* There may be instance variables, constructors, and methods
that are not shown. */
}Write the Library method averagePagesForGenre. The method should return the average number of pages of the available books in collection that match the parameter targetGenre.
Suppose collection contains the following five Book objects.
Title | "The Hobbit" | "1984" | "The Alchemist" | "Harry Potter" | "Foundation" |
|---|---|---|---|---|---|
Genre | "Fantasy" | "SciFi" | "Fantasy" | "Fantasy" | "SciFi" |
Pages | 300 | 320 | 200 | 405 | 250 |
Is Available | true | true | false | true | true |
Call: averagePagesForGenre("Fantasy")
Return Value: 352.5
Explanation: which is equal to the average number of pages of the available books with the genre "Fantasy" (300 pages for "The Hobbit" and 405 pages for "Harry Potter"). "The Alchemist" is a "Fantasy" book but is not available, so it is not included in the calculation. (300 + 405) / 2.0 = 352.5.
Complete method averagePagesForGenre.
/**
* Returns the average number of pages of the available books
* in collection whose genre is equal to targetGenre
* Precondition: targetGenre is not null
* At least one available element of
* collection has a genre equal to targetGenre.
* No elements of collection are null.
*/
public double averagePagesForGenre(String targetGenre)00:00