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

質問は、1 つの動画に対して複数の評価を覚えておく必要があると述べているようです。メソッド名が では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 に答える