import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FuJiaTest02 {
/**
* 4.分析以下需求,并用代码实现:
(1)定义一个学生类Student,属性:姓名(String name)、班级班号(String no)、成绩(double score)
(2)将若干Student对象存入List集合,并统计每个班级的总分和平均分
思路:
a.采用面向对象的思想
b.不推荐使用Map<String,List<Student>> 操作不方便
c.推荐使用Map<String,ClassRoom>
*/
public static void main(String[] args) {
// 创建一个List集合,泛型是Student
List<Student> list = exam();
Map<String, ClassRoom> map = count(list);
view(map);
}
/**
* @param map
*/
private static void view(Map<String, ClassRoom> map) {
//
for (Map.Entry<String, ClassRoom> en : map.entrySet()) {
String no = en.getKey(); //班号
ClassRoom room = en.getValue(); // 班级
double totalScore = room.getTotalScore(); //总分
int size = room.getList().size(); // 班级的学生人数
System.out.println(no+"的总分为"+totalScore+",平均分为"+totalScore / size);
}
}
/**
* @param list
* @return
*/
private static Map<String, ClassRoom> count(List<Student> list) {
//
Map<String,ClassRoom> map = new HashMap<>();
for (Student s : list) {
String no = s.getNo(); // 获取到班号
double score = s.getScore();// 获取到分数
ClassRoom room = map.get(no);
// 如果班级不存在,就创建
if(room==null){
room = new ClassRoom();
}
room.setTotalScore(room.getTotalScore()+score);
room.getList().add(s);
map.put(no, room);
}
return map;
}
/**
* @return
*/
private static List<Student> exam() {
List<Student> list = new ArrayList<>();
list.add(new Student("张三", "1班", 90));
list.add(new Student("周七", "1班", 100));
list.add(new Student("王五", "2班", 70));
list.add(new Student("李四", "1班", 82));
list.add(new Student("赵六", "2班", 59));
list.add(new Student("王8", "2班", 60));
return list;
}
}
// 班级
class ClassRoom{
private double totalScore;//班级的总分
private List<Student> list ;
public ClassRoom() {
list = new ArrayList<>();
}
public double getTotalScore() {
return totalScore;
}
public void setTotalScore(double totalScore) {
this.totalScore = totalScore;
}
public List<Student> getList() {
return list;
}
public void setList(List<Student> list) {
this.list = list;
}
}
// 学生
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;
}
@Override
public String toString() {
return "Student [name=" + name + ", no=" + no + ", score=" + score
+ "]";
}
}
|