Java筛选优秀学生:高效实现成绩过滤函数
Java筛选优秀学生:高效实现成绩过滤函数
本篇文章将带你了解如何使用Java实现一个函数,用于筛选出一个班级中成绩优秀的学生,即分数在90到100之间的学生。
函数接口定义
函数原型如下:
public static List<Student> filter(List<Student> students);
其中 students 是用户传入的参数,Student 类定义如下:
class Student {
public String name;
public String id;
public double score;
}
该函数需要返回一个 List,其中包含所有优秀(分数不小于90,但不能超过100)的学生,且顺序与传入的 students 列表相同。
思路
- 遍历学生列表。
- 检查每个学生的成绩是否在 90 到 100 之间。
- 如果成绩满足条件,将该学生加入新的列表中。
- 最后返回新的列表。
代码实现
public static List<Student> filter(List<Student> students) {
List<Student> excellentStudents = new ArrayList<>();
for (Student student : students) {
if (student.score >= 90 && student.score <= 100) {
excellentStudents.add(student);
}
}
return excellentStudents;
}
代码解析
- 创建一个新的
ArrayListexcellentStudents用于存储符合条件的学生。 - 使用
for循环遍历students列表。 - 对于每个学生,使用
if语句判断其分数是否在 90 到 100 之间。 - 如果满足条件,将该学生添加到
excellentStudents列表中。 - 最后返回
excellentStudents列表。
通过以上代码,我们成功实现了筛选优秀学生的函数。该函数简单易懂,易于维护,并能满足我们的需求。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/m0Nq 著作权归作者所有。请勿转载和采集!