0
点赞
收藏
分享

微信扫一扫

学生信息系统的数据搜索(java)

笑望叔叔 2022-02-18 阅读 78

需求

后台程序需要存储如上学生信息并展示,然后要提供按照学号搜索学生信息的功能。

分析

① 定义Student类,定义ArrayList集合存储如上学生对象信息,并遍历展示出来。
② 提供一个方法,可以接收ArrayList集合,和要搜索的学号,返回搜索到的学生对象信息,并展示。
③ 使用死循环,让用户可以不停的搜索。

代码

首先先创建一个Student类

package com.xxf1.arraylist;

public class Student {
    private String studyId;
    private String name;
    private int age;
    private String className;

    public Student() {
    }

    public Student(String atudyId, String name, int age, String className) {
        this.studyId = atudyId;
        this.name = name;
        this.age = age;
        this.className = className;
    }

    public String getStudyId() {
        return studyId;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }
}

在创建一个ArrayListDemo4类

package com.xxf1.arraylist;

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

/*
* 案例:学生信息系统:展示数据,并按学号完成搜索
* 学生类信息(学号,姓名,性别,班级)
*
* */
public class ArrayListDemo4 {
    public static void main(String[] args) {
        //1、定义一个Student类,后期用于创建对象封装学生数据
        //2、定义一个集合对象用于封装学生对象
        ArrayList<Student> student=new ArrayList<>();
        student.add(new Student("20180302","叶孤城",23,"护理一班"));
        student.add(new Student("20180303","东方不败",23,"推拿二班"));
        student.add(new Student("20180304","西门吹雪",26,"中药学四班"));
        student.add(new Student("20180305","梅超风",26,"神经科二班"));
        System.out.println("姓名\t\t\t\t学号\t\t\t年龄\t\t班级");
        //3、遍历集合中每个学生的对象并展示出来
        for (int i = 0; i < student.size(); i++) {
          Student s=  student.get(i);
            System.out.println(s.getName()+"\t\t"+s.getStudyId()+"\t\t"+s.getAge()+"\t\t"+s.getClassName());
        }
        //4、让用户不断输入学号,可以搜索出该学生对象信息并展示出来(独立方法)
        Scanner sc=new Scanner(System.in);
      while (true){
        System.out.println("请您输入要查询的学生的学号");
        String id=sc.next();
        Student s=getStudentById(student,id);
        //判断学号是否存在
        if(s==null){
            System.out.println("查无此人!");
        }else{
            //找到该学生对象了
            System.out.println(s.getName()+"\t\t"+s.getStudyId()+"\t\t"+s.getAge()+"\t\t"+s.getClassName());

        }
    }}

    private static Student getStudentById(ArrayList<Student> student,String studyId){
        for (int i = 0; i < student.size(); i++) {
            Student s=  student.get(i);
            if(s.getStudyId().equals(studyId)){
                return  s;
            }}
        return null;
    }
}

测试

在这里插入图片描述

举报

相关推荐

0 条评论