java运用重载求多门功课的平均成绩
时间: 2024-11-21 11:30:09 浏览: 19
在Java中,你可以利用方法重载(Method Overloading)的概念来计算多门课程的成绩平均值。方法重载允许你在同一个类里定义多个同名但参数列表不同的方法。下面是一个简单的示例,假设有一个`Student`类,它包含一个`calculateAverage`的方法,可以根据传入的不同参数类型(单门成绩、成绩数组等)来计算平均分:
```java
public class Student {
// 假设每门课的成绩都存储在一个List或数组中
private List<Double> courseScores;
// 定义重载的calculateAverage方法
public double calculateAverage() {
if (courseScores == null || courseScores.isEmpty()) {
return 0; // 如果没有任何成绩,返回0作为默认值
}
return courseScores.stream().average().orElse(0);
}
public double calculateAverage(double singleScore) {
if (singleScore != null) {
courseScores.add(singleScore);
return calculateAverage(); // 添加成绩后重新计算平均值
} else {
throw new IllegalArgumentException("Invalid score");
}
}
public double calculateAverage(Double[] scores) {
if (scores != null && scores.length > 0) {
this.courseScores = Arrays.asList(scores);
return calculateAverage();
} else {
throw new IllegalArgumentException("No scores provided");
}
}
// 其他相关方法...
}
// 使用示例
Student student = new Student();
student.calculateAverage(85); // 单门成绩
double[] array = {90, 80, 75};
student.calculateAverage(array); // 成绩数组
```
在这个例子中,用户可以分别通过一个单门成绩或一个成绩数组来调用`calculateAverage`方法,程序会根据传入的参数类型自动选择对应版本来计算平均分。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![java](https://img-home.csdnimg.cn/images/20250102104920.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![java](https://img-home.csdnimg.cn/images/20250102104920.png)