Reputation: 51
So the question asks me to do the following:
public boolean addRating(int rating)
Add a rating for the video. If rating is between 1-5 inclusive, then update the ratings for this video, keeping track of how many ratings for it have been received, and return true. Otherwise, print out an error message and return false.
And this is what I managed to do:
public class Video {
private int rating;
public boolean addRating(int rating){
this.rating = rating;
boolean result;
int newRating = rating;
if(newRating>=1 && newRating <=5){
rating = newRating;
result = true;
}
else{
System.out.println("ERROR!");
result = false;
}
return result;
}
So my question is how exactly do I count the number of times a video is rated?
Upvotes: 0
Views: 178
Reputation: 7304
The question seems to state that you need to remember multiple ratings for one video. Notice that the method name is addRating
not setRating
. You better model this with a list of ratings:
List<Integer> ratings;
Then tracking the number of ratings is as simple as computing the size of the list. Your call might look like this:
public class Video {
private List<Integer> ratings = new LinkedList<Integer>();
public boolean addRating(int rating){
// Some other code you will have to write...
ratings.add(rating);
// Some other code you will have to write...
}
}
Upvotes: 2
Reputation: 321
This is how I would do it.
public class Video {
private int rating = 0; // sum of all ratings
private int count = 0; // count the number of ratings
public boolean addRating(int newRating){
boolean result;
if(newRating>=1 && newRating <=5){
count++;
this.rating = this.rating + newRating;
result = true;
}
else{
System.out.println("ERROR!");
result = false;
}
return result;
}
// returns the avg of the ratings added
public int getRating(){
return Math.Round(((double) rating) / ((double) count));
}
}
Upvotes: 1