我已经能够写代码,但我不能打印出钥匙和相应的平均数。
这是我的代码:
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
}发布于 2020-05-20 20:07:41
您正在计算平均值,但是您试图将平均值插入到Hashmap中。由于hashmap有一个类型为值的ArrayList,但是您要在其中插入一个double,这将给出编译时错误。
HashMap是无序的,所以它不一定按照数据插入的相同顺序给出entrySet (就像ArrayList)。因此,您获得的entrySet的顺序可能是不同的。如果结果的顺序无关紧要,则只需打印键和平均值,而不必将其插入Hashmap中。
您可以这样修改代码:
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);
}
https://stackoverflow.com/questions/61921538
复制相似问题