[Java练习] 学生查询系统

视频教程传送门 -> https://www.bilibili.com/video/BV1Cv411372m?p=82

定义一个Student类

package com.test.arraylist;

public class Student {
    private String studyId;
    private String name;
    private String collegeName;

    public Student() {
    }

    public Student(String studyId, String name, String collegeName) {
        this.studyId = studyId;
        this.name = name;
        this.collegeName = collegeName;
    }

    public String getStudyId() {
        return studyId;
    }

    public void setStudyId(String studyId) {
        this.studyId = studyId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getcollegeName() {
        return collegeName;
    }

    public void setcollegeName(String collegeName) {
        this.collegeName = collegeName;
    }
}

定义一个测试类,把学生对象加到一个名为students的ArrayList<Student>

package com.test.arraylist;

import java.util.ArrayList;
import java.util.Scanner;

/**
 案例:学生信息系统:展示数据,并按照学号完成搜索
 学生类信息(学号,姓名,学院)
 */
public class StudentSys {
    public static void main(String[] args) {
        // 1、定义一个学生类,后期用于创建对象封装学生数据
        // 2、定义一个集合对象用于装学生对象
        ArrayList<Student> students = new ArrayList<>();
        students.add(new Student("20210300","哈利·波特","格兰芬多"));
        students.add(new Student("20210301","罗恩·韦斯莱","格兰芬多"));
        students.add(new Student("20210302","赫敏·格兰杰","格兰芬多"));
        students.add(new Student("20210303","德拉科·马尔福","斯莱特林"));
        students.add(new Student("20210304","塞德里克·迪戈里","赫奇帕奇"));
        students.add(new Student("20210305","卢娜·洛夫古德","拉文克劳"));
        System.out.println("学号\t\t姓名\t\t学院");

        // 3、遍历集合中的每个学生对象并展示其数据
        for (int i = 0; i < students.size(); i++) {
            Student s = students.get(i);
            System.out.println(s.getStudyId() +"\t\t" + s.getName()+"\t\t" + s.getcollegeName());
        }

        // 4、让用户不断的输入学号,可以搜索出该学生对象信息并展示出来(独立成方法)
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("请您输入要查询的学生的学号:");
            String id = sc.next();
            Student s = getStudentByStudyId(students, id);
            // 判断学号是否存在
            if(s == null){
                System.out.println("查无此人!");
            }else {
                // 找到了该学生对象了,信息如下
                System.out.println(s.getStudyId() +"\t\t" + s.getName()+"\t\t" + s.getcollegeName());
            }
        }
    }

    /**
     根据学号,去集合中找出学生对象并返回。
     * @param students
     * @param studyId
     * @return
     */
    public static Student getStudentByStudyId(ArrayList<Student> students, String studyId){
        for (int i = 0; i < students.size(); i++) {
            Student s = students.get(i);
            if(s.getStudyId().equals(studyId)){
                return s;
            }
        }
        return null; // 查无此学号!
    }
}

输出结果举例

猜你喜欢

转载自blog.csdn.net/wy_hhxx/article/details/121430183