// 实体类
public class Student {
private String name;
private double score;
public Student() {
}
public Student(String name,
double score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public String toString() {
return "Student{" + "name='" + name + '\'' + ", score=" + score + '}';
}
}
// 核心代码
/**
* 打印成绩不及格的学生姓名
* @param students
*/
private void printFailName(List<Student> students) {
for (Student student : students) {
if (student.getScore() < 60) System.out.println(student.getName());
}
}
/**
* 根据名字修改成绩
* @param name
* @param score
* @param students
*/
private void modifyScoreByName(String name,
double score,
List<Student> students) {
if (name == null) throw new RuntimeException("名字不能为空");
for (Student student : students) {
if (name.equals(student.getName())) student.setScore(score);
}
}
/**
* 根据姓名移除学生信息
*
* @param name
* @param students
* @return
*/
private void removeByName(String name,
List<Student> students) {
if (name == null) throw new RuntimeException("名字不能为空");
for (Student student : students) {
if (name.equals(student.getName())) {
students.remove(student);
break;
}
}
}
/**
* 初始化数据
*
* @return
*/
public List<Student> init() {
List<Student> students = new LinkedList<>();
students.add(new Student("刘德华",
85));
students.add(new Student("张学友",
100));
students.add(new Student("刘杰",
65));
students.add(new Student("章子怡",
58));
students.add(new Student("周迅",
76));
return students;
}
// 测试
@Test
public void test1() {
List<Student> students = init();// 初始化数据
System.out.println(students);
removeByName("刘杰",
students);// 移除信息;
System.out.println(students);
modifyScoreByName("刘德华",
95,
students);// 修改成绩
System.out.println(students);
printFailName(students);
System.out.println(students);
}
最终运行结果截图:
