0

所以问题要求我执行以下操作:

public boolean addRating(int rating)

为视频添加评分。如果评分介于 1-5 之间,则更新此视频的评分,跟踪已收到多少评分,并返回 true。否则,打印出错误消息并返回 false。

这就是我设法做到的:

   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;
    }

所以我的问题是如何准确计算视频的评分次数?

4

2 回答 2

2

该问题似乎表明您需要记住一个视频的多个评级。请注意,方法名称addRating不是setRating. 您最好使用评级列表对此进行建模:

List<Integer> ratings;

然后跟踪评分的数量就像计算列表的大小一样简单。您的电话可能如下所示:

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...

    }
}
于 2013-03-08T22:11:23.503 回答
1

我就是这样做的。

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));  
  }
}
于 2013-03-08T22:27:53.083 回答