summaryrefslogtreecommitdiff
path: root/search-engine/Book.java
blob: 330035f3be16f7f3010e51bbd24fd1719bb99814 (plain)
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
// 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!";
    }
}