package practice;
import java.util.ArrayList;
import java.util.Scanner;
public class Text7 {
public static void main(String[] args) {
//1.定义一个学生类
//2.创建集合存储学生对象,创建学生对象并封装
//把学生对象添加到集合中去
ArrayList<Student> students = new ArrayList<>();
Student s1 = new Student("12345", "张三", 12, "护理二班");
Student s2 = new Student("12346", "李四", 13, "环境一班");
Student s3 = new Student("12347", "王五", 12, "科技二班");
Student s4 = new Student("12348", "张麻子", 12, "医疗二班");
students.add(s1);
students.add(s2);
students.add(s3);
students.add(s4);
for (int i = 0; i < students.size(); i++) {
Student s = students.get(i);
System.out.println(s.getStudyNumber() + " " + s.getName() + " " + s.getAge() + " " + s.getClassName());
}
Scanner sc =new Scanner(System.in);
while (true) { //能多次查询
System.out.println("请输入学号查询");
String studyNumber =sc.next();
//调用方法查询
Student s = getStudengById(students,studyNumber);
//判断s中是否存在学生对象地址
if (s==null){
System.out.println("查无此人");
}else {
System.out.println("您查询的学生信息如下:");
System.out.println(s.getStudyNumber() + " " + s.getName() + " " + s.getAge() + " " + s.getClassName());
}
}
}
/**
* 根据学生学号查询学生对象返回
* @param students 存储全部学生对象的集合
* @param studyNumber 搜索学生的学号
* @return 学生对象|null
*/
public static Student getStudengById(ArrayList<Student> students,String studyNumber){
//遍历全部学生对象
for (int i = 0; i < students.size(); i++) {
Student s=students.get(i);
//询问当前学号是否是我们要找的
if (s.getStudyNumber().equals(studyNumber)){
return s;
}
}
return null;
}
}
ArrayList小练习:学生信息查询
最新推荐文章于 2023-08-23 16:58:16 发布