定义一个student类,属性:name 姓名 ,classname 班号 ,score 成绩
现将若干个student对象放入list,请统计出每个班级的总分和平均分,并
分别打印出来。
面向对象解题:
- student 类
- classroom类,用来存放一个班的学生,和他们的总分
- list用来存放所有的学生
- map容器,用来存放班级,因为每个班级的key都是班号不会重复。而student类可以根据这个键值找到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后会出现空指针异常
}
public ClassRoom(int no) {
this(); //调用本类的其他构造器
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<>(); //班号对应班级存放学生对象,把学生放进classroom的数组里
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();
//根据班号把classroom给拿出来
ClassRoom room=rooms.get(no);
if(room==null){
room=new ClassRoom(no);//如果没有的话就得新建一个,然后放进去,下面执行加的东西
rooms.put(no, room);//第一次直接丢进去就可以了
}
room.setTotle(room.getTotle()+score);//这里是有的了,先把总分加一下
room.getStu().add(temp);//把学生放进去,用的是ArrayList所以可以重名
//rooms.put(no, room);这个room已经是从Map里面取出来得了,不用放。。。
}
}
/**
* 现将若干对象放入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));
}
}
网友评论