0

我的 hashmap 包含一个键,它是客户的名字,值是所有书籍的评分。我必须计算给定书名的平均评分。

如何访问哈希图中的所有值(评级)?有没有办法做到这一点?

这是我的一段代码:

/** 
 * 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 种方式之一:

public double averageRating()1)在类内创建方法Book,并保留在那里,作为字段,评级被映射customerNamehisRatingOfBook

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 回答