diff options
| author | pants <niklasjo2004@gmail.com> | 2026-09-21 14:16:34 -0700 |
|---|---|---|
| committer | pants <niklasjo2004@gmail.com> | 2026-09-21 14:16:34 -0700 |
| commit | 81ba9eb66f8284d8760012973f84cdbe617ceb94 (patch) | |
| tree | 466432644e9e3fd66ee183ec53a1f10abb1b7faa /search-engine/Book.java | |
Diffstat (limited to 'search-engine/Book.java')
| -rw-r--r-- | search-engine/Book.java | 88 |
1 files changed, 88 insertions, 0 deletions
diff --git a/search-engine/Book.java b/search-engine/Book.java new file mode 100644 index 0000000..330035f --- /dev/null +++ b/search-engine/Book.java @@ -0,0 +1,88 @@ +// Nik Johnson +// TA: Zachary Bi +// 4-2-2024 + +import java.util.*; +import java.text.DecimalFormat; + +// book object, which can have a title, authors, and a list of ratings +public class Book implements Media { + + private String title; + private String author; + private List<String> authors; + private List<Integer> ratings; + + public Book(String title, String author) { + this.title = title; + this.author = author; + } + + public Book(String title, List<String> authors) { + this.title = title; + this.authors = authors; + } + + public String getTitle() { + return this.title; + } + + public List<String> getArtists() { + List<String> artists = new ArrayList<>(); + if (this.author != null) { + artists.add(this.author); + } + + if (this.authors != null) { + for (String author : authors) { + artists.add(author); + } + } + return artists; + } + + public void addRating(int score) { + if (this.ratings == null) { + ratings = new ArrayList<>(); + } + this.ratings.add(score); + } + + public int getNumRatings() { + + if (this.ratings == null) { + return 0; + } + + return this.ratings.size(); + } + + public double getAverageRating() { + if (this.ratings == null) { + return 0; + } + + int sum = 0; + for (int rating : ratings) { + sum += rating; + } + + return (double)sum / this.ratings.size(); + } + + public String toString() { + String output = ""; + + output += this.title + " by " + this.getArtists() + ": "; + + DecimalFormat df = new DecimalFormat("#." + "0".repeat(2)); + + if (ratings != null) { + output += df.format(this.getAverageRating()) + " (" + (this.ratings.size()) + " ratings" + ")"; + return output; + } + + return output + "No ratings yet!"; + } +} + |
