定义一个student类,包括属性学生学号,姓名,年级,班级,以及构造方法,定义一个搜索方法Search,可以接受arraylist集合和要搜索的学号,并且返回学生对象信息,定义测试方法,定义allaylist存储学生信息,当录入学生学号后,调用搜索方法,如果成功找到返回学生相关信息,如果没有找到,显示“未找到该学生”
时间: 2024-01-07 13:03:14 浏览: 76
好的,以下是代码实现:
```java
import java.util.ArrayList;
public class Student {
private String id; // 学号
private String name; // 姓名
private int grade; // 年级
private int clazz; // 班级
public Student(String id, String name, int grade, int clazz) {
this.id = id;
this.name = name;
this.grade = grade;
this.clazz = clazz;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public int getGrade() {
return grade;
}
public int getClazz() {
return clazz;
}
public static Student search(ArrayList<Student> students, String id) {
for (Student student : students) {
if (student.getId().equals(id)) {
return student;
}
}
return null;
}
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("001", "小明", 1, 1));
students.add(new Student("002", "小红", 1, 2));
students.add(new Student("003", "小刚", 2, 1));
String id = "002";
Student student = search(students, id);
if (student != null) {
System.out.println("找到了该学生:" + student.getName() + ",学号:" + student.getId() +
",年级:" + student.getGrade() + ",班级:" + student.getClazz());
} else {
System.out.println("未找到该学生");
}
}
}
```
输出结果为:
```
找到了该学生:小红,学号:002,年级:1,班级:2
```
阅读全文