定義一個student類栈戳,屬性:name 姓名 岂傲,classname 班號 ,score 成績
現(xiàn)將若干個student對象放入list子檀,請統(tǒng)計出每個班級的總分和平均分镊掖,并
分別打印出來乃戈。
面向?qū)ο蠼忸}:
- student 類
- classroom類,用來存放一個班的學生亩进,和他們的總分
- list用來存放所有的學生
- map容器症虑,用來存放班級,因為每個班級的key都是班號不會重復(fù)归薛。而student類可以根據(jù)這個鍵值找到classroom谍憔,存放并加進去。
student類
public class Student {
private String name;
private int classname; //存放班號
private double score;
public Student() {
}
public Student(String name, int classname, double score) {
super();
this.name = name;
this.classname = classname;
this.score = score;
}
ClassRoom類
public class ClassRoom {
private int no;
private ArrayList<Student> stu;
private double totle;
public ClassRoom() {
stu =new ArrayList<Student>(); //這里stu必須手動初始化主籍,否則賦值為null后會出現(xiàn)空指針異常
}
public ClassRoom(int no) {
this(); //調(diào)用本類的其他構(gòu)造器
this.no = no;
}
主程序
public class Test01 {
public static void main(String[] args) {
ArrayList<Student> list=new ArrayList<>(); //建造存放student的列表习贫,泛型在使用時顯示確定為Student
add(list);
Map<Integer,ClassRoom> rooms=new HashMap<>(); //班號對應(yīng)班級存放學生對象,把學生放進classroom的數(shù)組里
count(rooms, list);
print(rooms);
}
public static void print(Map<Integer,ClassRoom> rooms){
Set<Map.Entry<Integer, ClassRoom>> entries=rooms.entrySet(); //
Iterator<Map.Entry<Integer, ClassRoom>> it=entries.iterator(); //得到鍵值對的迭代器
while(it.hasNext()){
Map.Entry<Integer,ClassRoom> entry=it.next();
ClassRoom room=entry.getValue();
int no=room.getNo();
double avery=room.getTotle()/room.getStu().size();
System.out.println("班號為"+no+"的班級崇猫,總分為:"+room.getTotle()+"沈条,平均分為:"+avery);
}
}
/**
* 計算成績
*/
public static void count(Map<Integer,ClassRoom> rooms,ArrayList<Student> list){
for(Student temp:list){
int no=temp.getClassname();
double score=temp.getScore();
//根據(jù)班號把classroom給拿出來
ClassRoom room=rooms.get(no);
if(room==null){
room=new ClassRoom(no);//如果沒有的話就得新建一個,然后放進去诅炉,下面執(zhí)行加的東西
rooms.put(no, room);//第一次直接丟進去就可以了
}
room.setTotle(room.getTotle()+score);//這里是有的了,先把總分加一下
room.getStu().add(temp);//把學生放進去屋厘,用的是ArrayList所以可以重名
//rooms.put(no, room);這個room已經(jīng)是從Map里面取出來得了涕烧,不用放。汗洒。议纯。
}
}
/**
* 現(xiàn)將若干對象放入List
*/
public static void add(ArrayList<Student> list){
list.add(new Student("a", 01, 80));
list.add(new Student("b", 01, 80));
list.add(new Student("c", 02, 80));
list.add(new Student("c", 01, 80));
list.add(new Student("a", 02, 80));
list.add(new Student("d", 03, 80));
list.add(new Student("e", 03, 80));
list.add(new Student("c", 02, 80));
list.add(new Student("f", 01, 80));
list.add(new Student("g", 03, 80));
}
}