** 1, the information "student name, subject name / score" has been made into a two-dimensional map data structure. ** ** ** 2, the total score and average score of each student were output using the for statement. ** **
Collection classes cannot store anything that is not an instance. However, it can be stored by converting int type information to Integer type (wrapper class).
Run in Eclipse Oxygen
A program that creates and turns a 2D map
import java.util.LinkedHashMap;
import java.util.Map;
public class MapScore {
public static void main(String[] args) {
//Create a 2D map
//Immediately before the map name, that is, Map<String, Map<String, Integer>>Up to data type
Map<String, Map<String, Integer>> nameMap = new LinkedHashMap<String, Map<String, Integer>>();
//Suzuki
Map<String, Integer> scoresMap_suzuki = new LinkedHashMap<String, Integer>();
scoresMap_suzuki.put("National language", 78);
scoresMap_suzuki.put("Math", 90);
scoresMap_suzuki.put("English", 20);
//Mr Sato
Map<String, Integer> scoresMap_satoh = new LinkedHashMap<String, Integer>();
scoresMap_satoh.put("National language", 50);
scoresMap_satoh.put("Math", 40);
scoresMap_satoh.put("English", 90);
//Tanaka
Map<String, Integer> scoresMap_tanaka = new LinkedHashMap<String, Integer>();
scoresMap_tanaka.put("National language", 80);
scoresMap_tanaka.put("Math", 60);
scoresMap_tanaka.put("English", 85);
//Realize a 2D map by putting the above 3 maps in the value of the name map
nameMap.put("Suzuki", scoresMap_suzuki);
nameMap.put("Sato", scoresMap_satoh);
nameMap.put("Tanaka", scoresMap_tanaka);
//Turn the name map with Extended for
//In the case of LinkedHashMap, it is fetched in the order of storage.
for (Map.Entry<String, Map<String, Integer>> element : nameMap.entrySet()) {
//Get the value of nameMap and assign it to a new map
Map<String,Integer> scores = element.getValue();
int sum = 0;
int avg = 0;
//scoresMap_Turn the value of the name, that is, the score, and substitute it for sum
for(int hogeInt : scores.values()){
sum += hogeInt;
avg = sum / scores.size();
}
//For the number of people((For 3 people) Output
System.out.println(element + "The total score is" + sum + " " + "The average is" + avg);
}
}
}
Execution result
Execution result
Suzuki={National language=78,Math=90,English=20}The total score is 188 and the average is 62
Sato={National language=50,Math=40,English=90}Total score is 180 Average is 60
Tanaka={National language=80,Math=60,English=85}Total score is 225 Average is 75
Recommended Posts