实现一个学生类Student类,对学号,姓名,三门课的课程成绩进行管理。类应该能够单独设置和获取三门课课程的成绩,可以计算平均成绩
时间: 2024-10-21 19:04:27 浏览: 33
当然,我们可以创建一个名为`Student`的类,用于表示学生的信息并管理他们的课程成绩。这里是一个基础的设计:
```java
public class Student {
private String studentId; // 学号
private String name; // 姓名
private double[] scores; // 三门课程的成绩
// 构造函数初始化学生信息
public Student(String studentId, String name) {
this.studentId = studentId;
this.name = name;
this.scores = new double[3]; // 初始化三门课程的成绩数组
}
// 设置单门课程成绩
public void setScore(int courseIndex, double score) {
if (courseIndex >= 0 && courseIndex < 3) {
scores[courseIndex] = score;
} else {
throw new IllegalArgumentException("Invalid course index");
}
}
// 获取单门课程成绩
public double getScore(int courseIndex) {
if (courseIndex >= 0 && courseIndex < 3) {
return scores[courseIndex];
} else {
throw new IllegalArgumentException("Invalid course index");
}
}
// 计算平均成绩
public double calculateAverage() {
if (scores != null && scores.length > 0) {
double sum = 0;
for (double score : scores) {
sum += score;
}
return sum / scores.length;
} else {
throw new IllegalStateException("No scores available");
}
}
// 获取学生信息
@Override
public String toString() {
return "Student{" +
"studentId='" + studentId + '\'' +
", name='" + name + '\'' +
", scores=" + Arrays.toString(scores) +
'}';
}
}
```
阅读全文
相关推荐


















