Java ArrayList 某中学有若干学生,每个学生有一个姓名属性、班级名称属性和考试成绩属性
题目:某中学有若干学生(学生对象放在一个List中),每个学生有一个姓名属性、班级名称属性(String)和考试成绩 属性(int),某次考试结束后,每个学生都获得了一个 考试成绩。请打印出每个班级的总分和平均分。
学生类:为了方便这里只提供了get方法。
public class Student {
private String name;
private String className;
private int grade;
public String getName() {
return name;
}
public String getClassName() {
return className;
}
public int getGrade() {
return grade;
}
public Student(String name, String className, int grade) {
this.name = name;
this.className = className;
this.grade = grade;
}
}
测试类
public class TestStudent {
public static void main(String[] args) {
// 给每个对象设置属性
Student student1 = new Student("曹操", "魏国", 100);
Student student2 = new Student("司马懿", "魏国", 98);
Student student3 = new Student("张飞", "蜀国", 89);
Student student4 = new Student("关羽", "蜀国", 89);
Student student5 = new Student("赵云", "蜀国", 97);
Student student6 = new Student("刘备", "蜀国", 96);
Student student7 = new Student("荀彧", "魏国", 99);
Student student8 = new Student("张郃", "魏国", 88);
// 将对象放入list
List<Object> list = new ArrayList<Object>();
list.add(student1);
list.add(student2);
list.add(student3);
list.add(student4);
list.add(student5);
list.add(student6);
list.add(student7);
list.add(student8);
Student stu;
// 定义两个存分数的数组
List<Integer> wei = new ArrayList<Integer>();
List<Integer> shu = new ArrayList<Integer>();
// 将每个班的分数放到一个数组
for (int i = 0; i < list.size(); i++) {
stu = (Student) list.get(i);
if (stu.getClassName().equals("魏国")) {
wei.add(stu.getGrade());
} else {
shu.add(stu.getGrade());
}
}
// 总分
double shuSum = 0;
double weiSum = 0;
for (int i = 0; i < shu.size(); i++) {
shuSum += shu.get(i);
weiSum += wei.get(i);
}
System.out.println("魏国分数:" + wei);
System.out.println("魏国的总分:" + weiSum + " 魏国的平均分:" + weiSum / wei.size());
System.out.println("蜀国分数:" + shu);
System.out.println("蜀国的总分:" + shuSum + " 蜀国的平均分:" + shuSum / shu.size());
}
}