首先定义CourseScore类封装学生姓名和成绩,再使用ArrayList存储多个学生成绩对象,接着遍历集合计算平均分、最高分、最低分、及格人数及及格率,最后输出统计结果。示例代码展示了完整的统计逻辑与格式化输出,便于扩展成绩分段、排序和文件读取等功能。

在Java中实现课程成绩统计功能,主要是通过定义类来管理学生信息和成绩数据,再利用集合或数组存储多个学生成绩,最后编写方法完成平均分、最高分、最低分、及格率等常见统计。下面是一个简单实用的实现方式。
创建一个Student类或直接使用CourseScore类来封装学生姓名和成绩信息。
例如:
<font face="Consolas, Courier New">
class CourseScore {
private String studentName;
private double score;
<pre class='brush:java;toolbar:false;'>public CourseScore(String studentName, double score) {
this.studentName = studentName;
this.score = score;
}
public double getScore() {
return score;
}
public String getName() {
return studentName;
}}
使用ArrayList来动态存储多个学生的成绩,便于后续统计操作。
立即学习“Java免费学习笔记(深入)”;
示例代码:
<font face="Consolas, Courier New">
import java.util.ArrayList;
import java.util.List;
<p>List<CourseScore> scores = new ArrayList<>();
scores.add(new CourseScore("张三", 85.5));
scores.add(new CourseScore("李四", 92.0));
scores.add(new CourseScore("王五", 76.0));
scores.add(new CourseScore("赵六", 58.5));
scores.add(new CourseScore("钱七", 96.5));
</font>编写方法计算各项统计数据,如平均分、最高分、最低分、及格人数和及格率。
核心逻辑如下:
完整统计代码示例:
<font face="Consolas, Courier New">
double sum = 0.0;
double max = scores.get(0).getScore();
double min = scores.get(0).getScore();
int passCount = 0;
<p>for (CourseScore cs : scores) {
double s = cs.getScore();
sum += s;
if (s > max) max = s;
if (s < min) min = s;
if (s >= 60) passCount++;
}</p><p>double average = sum / scores.size();
double passRate = (double) passCount / scores.size() * 100;</p><p>System.out.println("总人数:" + scores.size());
System.out.println("平均分:" + String.format("%.2f", average));
System.out.println("最高分:" + max);
System.out.println("最低分:" + min);
System.out.println("及格人数:" + passCount);
System.out.println("及格率:" + String.format("%.1f%%", passRate));
</font>若需要更复杂功能,可考虑以下优化:
基本上就这些。用好类、集合和循环,就能清晰实现课程成绩统计功能,结构清晰也易于维护和扩展。
以上就是在Java中如何实现课程成绩统计功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号