计算添加变量值的次数

时间:2013-03-08 22:07:31

标签: java

所以问题要求我做以下事情:

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

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

2 个答案:

答案 0 :(得分: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...

    }
}

答案 1 :(得分: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));  
  }
}