java计算每个同学的平均成绩,分为Student,average,entrance类
时间: 2024-09-14 11:09:36 浏览: 60
Entrance-task
在Java中,我们可以创建三个相关的类来处理这个需求:`Student`, `AverageCalculator`, 和 `Entrance` 类。下面是一个简化的例子:
1. **Student** 类:代表一个学生,包含个人信息和成绩属性。
```java
public class Student {
private String name;
private double[] scores;
public Student(String name, double[] scores) {
this.name = name;
this.scores = scores;
}
// getters and setters for name and scores
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double[] getScores() {
return scores;
}
// 如果需要,可以添加getAverageScore()方法来获取当前学生的平均成绩
}
```
2. **AverageCalculator** 类:用于计算所有学生或特定学生群体的平均成绩。
```java
public class AverageCalculator {
private List<Student> students;
public AverageCalculator(List<Student> students) {
this.students = students;
}
public double calculateAverage(Student student) {
if (student.getScores().length == 0) {
throw new IllegalArgumentException("No scores found for the student.");
}
double sum = 0;
for (double score : student.getScores()) {
sum += score;
}
return sum / student.getScores().length;
}
// 添加一个方法来计算整个学生列表的平均分
public double calculateOverallAverage() {
double totalSum = 0;
for (Student student : students) {
totalSum += calculateAverage(student);
}
return totalSum / students.size();
}
}
```
3. **Entrance** 类(如果这是入学管理系统的类):可能包含初始化学生列表或操作平均成绩的方法。
```java
public class Entrance {
private AverageCalculator calculator;
public Entrance(List<Student> students) {
this.calculator = new AverageCalculator(students);
}
public void enroll(Student student) {
// 添加新学生到列表
}
public void displayAverage(Student targetStudent) {
double average = calculator.calculateAverage(targetStudent);
System.out.println("The average score of " + targetStudent.getName() + " is " + average);
}
// 其他入口点如显示总体平均分
public void displayOverallAverage() {
double overallAverage = calculator.calculateOverallAverage();
System.out.println("Overall average score is " + overallAverage);
}
}
```
阅读全文