使用LinkedList存储学生信息,学生信息包括学号,姓名,年龄,性别,实现列出所有学生,增加学生,删除某个学号的学生的功能
时间: 2024-05-13 11:17:42 浏览: 117
可以使用如下的Java代码实现:
```
import java.util.LinkedList;
public class Student {
private String id;
private String name;
private int age;
private String gender;
public Student(String id, String name, int age, String gender) {
this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getGender() {
return gender;
}
public String toString() {
return "ID: " + id + ", Name: " + name + ", Age: " + age + ", Gender: " + gender;
}
}
public class StudentManager {
private LinkedList<Student> students;
public StudentManager() {
students = new LinkedList<>();
}
public void listStudents() {
for (Student student : students) {
System.out.println(student);
}
}
public void addStudent(Student student) {
students.add(student);
}
public void deleteStudent(String id) {
for (Student student : students) {
if (student.getId().equals(id)) {
students.remove(student);
break;
}
}
}
}
```
其中,`Student`类表示学生,包含学号、姓名、年龄、性别等信息,并且提供了获取这些信息的方法和重写了`toString()`方法。`StudentManager`类表示学生管理器,使用`LinkedList`存储所有学生信息,并提供了列出所有学生、增加学生、删除某个学号的学生等功能。
可以按照如下方式使用`StudentManager`类:
```
public static void main(String[] args) {
StudentManager manager = new StudentManager();
// 添加学生
manager.addStudent(new Student("1001", "张三", 20, "男"));
manager.addStudent(new Student("1002", "李四", 21, "女"));
manager.addStudent(new Student("1003", "王五", 22, "男"));
// 列出所有学生
manager.listStudents();
// 删除学号为1002的学生
manager.deleteStudent("1002");
// 再次列出所有学生
manager.listStudents();
}
```
阅读全文