■定义类Student,属性name(姓名)、score(分 数),定义构造函数、getter、setter函数、重写toString()函数; ■新建测试类DemoStudentList,实现: 定义三个Student对象,分别为name和score赋值,定义一个List对象s_list,将三个Student添加到列表中,使用列表迭代器循环遍历列表,求三个学生的成绩加和,并求平均分,输出。
时间: 2024-02-28 18:57:12 浏览: 83
以下是代码实现:
```java
//定义Student类
public class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return "姓名:" + name + ",分数:" + score;
}
}
//测试类DemoStudentList
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class DemoStudentList {
public static void main(String[] args) {
Student s1 = new Student("张三", 80);
Student s2 = new Student("李四", 90);
Student s3 = new Student("王五", 85);
List<Student> s_list = new ArrayList<>();
s_list.add(s1);
s_list.add(s2);
s_list.add(s3);
int sum = 0;
Iterator<Student> iterator = s_list.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
sum += student.getScore();
System.out.println(student.toString());
}
System.out.println("总分:" + sum + ",平均分:" + (sum / 3.0));
}
}
```
运行结果:
```
姓名:张三,分数:80
姓名:李四,分数:90
姓名:王五,分数:85
总分:255,平均分:85.0
```
阅读全文