标签:double new ext.get student hash get bsp java style
TestStudent.java
package com.sxt.home; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /* * 计算三个不同班学生的的总成绩和平均成绩 * 存储在集合中 */ public class TestStudent { public static void main(String[] args) { //定义一个Hashmap存储每个班 定义一个ArrayList存储每个班的成绩 Map<Integer,List<Student>> map = new HashMap<>(); //第一个班 List<Student> list1 = new ArrayList<>(); list1.add(new Student("小花", "男", 77.5)); list1.add(new Student("小明", "女", 43.5)); list1.add(new Student("小刚", "男", 33.5)); map.put(1, list1); //第二个班 List<Student> list2 = new ArrayList<>(); list2.add(new Student("小明", "男", 43.5)); list2.add(new Student("小明", "男", 43.5)); list2.add(new Student("小明", "男", 43.5)); list2.add(new Student("小明", "男", 99.5)); map.put(2, list2); //第三个班 List<Student> list3 = new ArrayList<>(); list3.add(new Student("刚刚", "女", 43.5)); list3.add(new Student("小明", "男", 43.5)); map.put(3, list3); //遍历集合取出数据 //entrySet取出键值对 Set<Entry<Integer, List<Student>>> entrySet = map.entrySet(); Iterator<Entry<Integer, List<Student>>> iterator = entrySet.iterator(); double sum = 0;//成绩总和 int num = 0;//人数统计 //迭代器遍历循环HashMap 取出每个ArrayList while(iterator.hasNext()){ Entry<Integer, List<Student>> next = iterator.next(); List<Student> value = next.getValue(); //增强for循环遍历ArrayList:遍历每个班的成绩 for(Student s : value){ sum += s.getScore(); num++; } System.out.println(next); } System.out.println("三个班总成绩:"+sum); System.out.println("三个班级的平均成绩:"+sum/num); } }
Student.java
package com.sxt.home; public class Student { private String name; private String sex; private double score; public Student(String name, String sex, double score) { super(); this.name = name; this.sex = sex; this.score = score; } public Student() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } @Override public String toString() { return "Student [name=" + name + ", sex=" + sex + ", score=" + score + "]"; } }
标签:double new ext.get student hash get bsp java style
原文地址:http://www.cnblogs.com/qingfengzhuimeng/p/6792023.html