0

私のハッシュマップには、顧客名であるキーが含まれており、値は評価された本のすべての評価です。特定の本のタイトルの平均評価を計算する必要があります。

ハッシュマップからすべての値 (評価) にアクセスするにはどうすればよいですか? これを行う方法はありますか?

これが私のコードの一部です:

/** 
 * calculate the average rating by all customers for a named book
 * only count positive or negative ratings, not 0 (unrated)
 * if the booktitle is not found or their are no ratings then
 * return NO_AVERAGE
 * @param booktitle String to be rated
 * @return double the average of all ratings for this book
 */
public double averageRating(String booktitle) 
{ 
    numberOfRatingsPerCustomer/total
}
4

3 に答える 3

1

HashMap から keySet を取得する必要があります。次に、keySet を繰り返し処理し、HashMap から値をフェッチします。

于 2012-05-24T04:26:42.060 に答える
0

あなたの質問は意味がありません。

customerNameto を含むマップを作成してhisRatingOfBook、その中で を検索することはできませんbookTitle。1 つの方法のいずれかを実行する必要があります。

1)クラスpublic double averageRating()内にメソッドを作成Bookし、フィールドとしてそこに保持し、評価がにマップされcustomerNameますhisRatingOfBook

2)あなたの方法を使用してください:

public double averageRating(String booktitle) 
{ 
    numberOfRatingsPerCustomer/total
}

しかし、あなたのマップをもっと複雑なものにしcustomerくださいrating

于 2012-05-24T04:40:54.957 に答える
0

以下のコードを使用すると、クラスの生徒の平均点を見つけるために行った評価の問題を見つけるのに役立ちます

import java.util.*;

public class QueQue {

public static float getAverage(HashMap<String, ArrayList<Integer>> hm, String name) {
    ArrayList<Integer> scores;
    scores = hm.get(name);
    if (scores == null) {
        System.out.println("NOT found");
    }

    int sum = 0;
    for (int x : scores) {
        sum += x;
    }
    return (float) sum / scores.size();
}
public static void main(String[] args) {
    HashMap<String, ArrayList<Integer>> hm = new HashMap<>();
    hm.put("Peter", new ArrayList<>());
    hm.get("Peter").add(10);
    hm.get("Peter").add(10);
    hm.get("Peter").add(10);

    hm.put("Nancy", new ArrayList<>());
    hm.get("Nancy").add(7);
    hm.get("Nancy").add(8);
    hm.get("Nancy").add(8);

    hm.put("Lily", new ArrayList<>());
    hm.get("Lily").add(9);
    hm.get("Lily").add(9);
    hm.get("Lily").add(8);

    System.out.println("Find the average of the Peter");
    float num = getAverage(hm, "Peter");

}
  }
于 2016-03-24T15:11:19.827 に答える