import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class studentManager {
// 学生类
static class Student {
private String name;
private String no;
private Double score;
public Student() {
super();
}
public Student(String name, String no, Double score) {
super();
this.name = name;
this.no = no;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
}
// 教室类
static class ClassRoom {
private List<Student> classRoom;
public List<Student> getClassRoom() {
return classRoom;
}
public void setClassRoom(List<Student> classRoom) {
this.classRoom = classRoom;
}
}
public static void main(String[] args) {
// 初始化数据
ClassRoom c1 = new ClassRoom();
ClassRoom c2 = new ClassRoom();
ArrayList<Student> l1 = new ArrayList<Student>();
ArrayList<Student> l2 = new ArrayList<Student>();
l1.add(new Student("小李", "01", 97.15));
l1.add(new Student("小张", "01", 86.70));
l1.add(new Student("小赵", "01", 72.35));
l2.add(new Student("小王", "02", 99.25));
l2.add(new Student("小强", "02", 68.70));
l2.add(new Student("小刘", "02", 79.58));
c1.setClassRoom(l1);
c2.setClassRoom(l2);
// 定义Map集合
Map<String, ClassRoom> map = new HashMap<String, ClassRoom>();
for (int i = 0; i < l1.size(); i++) {
map.put(l1.get(i).getNo(), c1);
}
for (int i = 0; i < l2.size(); i++) {
map.put(l2.get(i).getNo(), c2);
}
// 规定格式化
DecimalFormat df = new DecimalFormat("######0.00");
// 遍历map
Set keySet = map.keySet();
Iterator it = keySet.iterator();
while (it.hasNext()) {
Double sum = 0.0;
Double avg = 0.0;
String key = (String) it.next();
ClassRoom value = (ClassRoom) map.get(key);
// 遍历集合求总成绩与平均成绩
for (Student ss : value.getClassRoom()) {
sum += ss.getScore();
avg = sum / value.getClassRoom().size();
}
System.out.println(key + "班总成绩为" + df.format(sum) + "分");
System.out.println(key + "班平均成绩为" + df.format(avg) + "分");
}
}
}
|