-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBook.java
More file actions
102 lines (85 loc) · 2.64 KB
/
Book.java
File metadata and controls
102 lines (85 loc) · 2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import java.text.*;
import java.util.*;
public class Book implements Media, Comparable<Book> {
private static final DecimalFormat RATING_FORMAT = new DecimalFormat("0.##");
static {
RATING_FORMAT.setMinimumFractionDigits(1);
}
private final String title;
private final List<String> authors;
private final List<String> content;
private int ratingSum;
private int ratingCount;
public Book(String title, List<String> authors, Scanner contentScanner) {
this.title = Objects.requireNonNull(title, "title cannot be null");
List<String> authorCopy = new ArrayList<>();
if (authors != null) {
for (String author : authors) {
if (author != null && !author.isEmpty()) {
authorCopy.add(author);
}
}
}
this.authors = Collections.unmodifiableList(authorCopy);
List<String> tokens = new ArrayList<>();
if (contentScanner != null) {
while (contentScanner.hasNext()) {
tokens.add(contentScanner.next());
}
}
this.content = Collections.unmodifiableList(tokens);
}
@Override
public String getTitle() {
return title;
}
@Override
public List<String> getArtists() {
return authors;
}
@Override
public void addRating(int score) {
if (score < 0) {
throw new IllegalArgumentException("score must be non-negative");
}
ratingSum += score;
ratingCount++;
}
@Override
public int getNumRatings() {
return ratingCount;
}
@Override
public double getAverageRating() {
if (ratingCount == 0) {
return 0.0;
}
return (double) ratingSum / ratingCount;
}
@Override
public List<String> getContent() {
return content;
}
@Override
public int compareTo(Book other) {
Objects.requireNonNull(other, "other book cannot be null");
int byAverage = Double.compare(other.getAverageRating(), getAverageRating());
if (byAverage != 0) {
return byAverage;
}
int byRatings = Integer.compare(other.getNumRatings(), getNumRatings());
if (byRatings != 0) {
return byRatings;
}
return title.compareToIgnoreCase(other.title);
}
@Override
public String toString() {
if (ratingCount == 0) {
return title + " by " + authors;
}
return title + " by " + authors + ": "
+ RATING_FORMAT.format(getAverageRating())
+ " (" + ratingCount + " ratings)";
}
}