java实现本学期期末学员共参加了3门课的考试,即Java,C,SQL,编写方法计算5名学员3门课的平均分。
时间: 2024-09-18 17:02:11 浏览: 51
在Java中,我们可以创建一个简单的类`Student`来存储每位学员的成绩,并提供一个方法来计算所有学员的平均成绩。下面是一个示例:
```java
class Student {
private String name;
private double javaScore;
private double cScore;
private double sqlScore;
public Student(String name, double java, double c, double sql) {
this.name = name;
this.javaScore = java;
this.cScore = c;
this.sqlScore = sql;
}
// 获取方法
public double getJavaScore() { return javaScore; }
public double getCScore() { return cScore; }
public double getSqlScore() { return sqlScore; }
// 计算总分
public double getTotalScore() {
return javaScore + cScore + sqlScore;
}
// 计算平均分
public double calculateAverage() {
if (javaScore + cScore + sqlScore == 0) {
throw new IllegalArgumentException("Total scores cannot be zero.");
}
return getTotalScore() / 3.0;
}
}
public class ExamAverageCalculator {
public static void main(String[] args) {
// 创建5位学员实例
Student student1 = new Student("学员1", 85, 90, 95);
Student student2 = new Student("学员2", 90, 87, 92);
Student student3 = new Student("学员3", 95, 92, 96);
Student student4 = new Student("学员4", 88, 89, 91);
Student student5 = new Student("学员5", 92, 93, 94);
// 存储学员列表
List<Student> students = Arrays.asList(student1, student2, student3, student4, student5);
// 计算所有学员的平均分
double totalAverage = students.stream()
.map(Student::calculateAverage)
.average()
.orElse(Double.NaN); // 避免除以零的情况
System.out.printf("五名学员三门课的平均分为 %.2f 分.\n", totalAverage);
}
}
```
在这个例子中,我们首先定义了`Student`类,然后在`ExamAverageCalculator`类里,通过流(Stream)操作计算所有学员的平均分。
阅读全文