首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在ArrayList中打印键和HashMap中的平均值

如何在ArrayList中打印键和HashMap中的平均值
EN

Stack Overflow用户
提问于 2020-05-20 19:40:17
回答 1查看 40关注 0票数 0

我已经能够写代码,但我不能打印出钥匙和相应的平均数。

这是我的代码:

代码语言:javascript
复制
Map<String,List<Double>> stdMap = new HashMap<>();

//Create arraylist of integers to store student's marks

//Create and initialise at creation

ArrayList<Double> Mark1 = new ArrayList<>(Arrays.asList(78.0,68.0,82.0));
ArrayList<Double> Mark2 = new ArrayList<>(Arrays.asList(80.0,73.0));
ArrayList<Double> Mark3 = new ArrayList<>(Arrays.asList(72.0,81.0,75.0));
ArrayList<Double> Mark4 = new ArrayList<>(Arrays.asList(83.0,76.0,65.0,93.0));
ArrayList<Double> Mark5 = new ArrayList<>(Arrays.asList(85.0,78.0,77.0));

//Add content to HashMap
stdMap.put("Nii", Mark1);
stdMap.put("Felicity", Mark2);
stdMap.put("Evelyn", Mark3);
stdMap.put("Samuelis", Mark4);
stdMap.put("Bertina", Mark5);  //(1a)Print out Each student's content from hashmap
     System.out.println("\tStudent Results: \n");
     for(Map.Entry<String, ArrayList<Double>>stdMapEntry: stdMap.entrySet()){
        System.out.println("\t\t Student Name:" + stdMapEntry.getKey());
        System.out.println("\t\t Student Marks:" + stdMapEntry.getValue()+"\n");
    }
//(1b) Finding the Average Mark of Each Student
     System.out.println("\tAverage Mark: \n");


for (Map.Entry<String, ArrayList<Double>> stdMapEntry: stdMap.entrySet()) {
        double averageNumber;
        double sum = 0;

    String key = stdMapEntry.getKey();           
    for(int i=0; i<stdMapEntry.getValue().size(); i++){
        sum += stdMapEntry.getValue().get(i);

    }   
    averageNumber = sum / stdMapEntry.getValue().size();
    System.out.println("\nThis is the averaged map: ");
    System.out.println(stdMap.put(key, averageNumber)); // won't work
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-20 20:07:41

您正在计算平均值,但是您试图将平均值插入到Hashmap中。由于hashmap有一个类型为的ArrayList,但是您要在其中插入一个double,这将给出编译时错误。

HashMap是无序的,所以它不一定按照数据插入的相同顺序给出entrySet (就像ArrayList)。因此,您获得的entrySet的顺序可能是不同的。如果结果的顺序无关紧要,则只需打印键和平均值,而不必将其插入Hashmap中。

您可以这样修改代码:

代码语言:javascript
复制
for (Map.Entry<String, ArrayList<Double>> stdMapEntry: stdMap.entrySet()) {
            double averageNumber;
            double sum = 0;

            System.out.println("key: " + stdMapEntry.getKey());

            String key = stdMapEntry.getKey();
            for(int i=0; i<stdMapEntry.getValue().size(); i++){
                sum += stdMapEntry.getValue().get(i);

            }
            averageNumber = sum / stdMapEntry.getValue().size();
            System.out.println("average value:" + averageNumber);
        }

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61921538

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档