用java编写:在两个类中实现统计某个班级的学生成绩
时间: 2024-10-29 10:18:59 浏览: 14
在Java中,我们可以创建两个类:`Student` 和 `Classroom` 来实现这个功能。`Student` 类表示学生,包含学生的姓名和成绩,而 `Classroom` 类则代表班级,包含学生的列表以及一些方法用于统计数据。
首先,我们定义`Student` 类:
```java
public class Student {
private String name;
private double score;
public Student(String name, double score) {
this.name = name;
this.score = score;
}
// getter and setter methods
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getScore() { return score; }
public void setScore(double score) { this.score = score; }
}
```
接下来,我们定义`Classroom` 类,它有一个`List<Student>` 存储学生,同时提供计算平均分和总分的方法:
```java
import java.util.ArrayList;
import java.util.List;
public class Classroom {
private List<Student> students;
public Classroom() {
students = new ArrayList<>();
}
public void addStudent(Student student) {
students.add(student);
}
public double calculateAverageScore() {
double totalScore = 0;
for (Student student : students) {
totalScore += student.getScore();
}
return totalScore / students.size();
}
public double calculateTotalScore() {
double totalScore = 0;
for (Student student : students) {
totalScore += student.getScore();
}
return totalScore;
}
// 其他可能需要的方法,如删除学生等...
}
```
现在,你可以创建 `Classroom` 对象,添加学生,然后调用其方法来计算平均分和总分。例如:
```java
public class Main {
public static void main(String[] args) {
Classroom classroom = new Classroom();
classroom.addStudent(new Student("张三", 85));
classroom.addStudent(new Student("李四", 90));
// 添加更多学生...
double averageScore = classroom.calculateAverageScore();
double totalScore = classroom.calculateTotalScore();
System.out.printf("班级平均分: %.2f 分\n", averageScore);
System.out.printf("班级总分: %.2f 分\n", totalScore);
}
}
```
阅读全文