具体见注释:
//1.定义一个学生类,后期用于创建对象封装学生数据 //2.定义一个集合对象用于装学生对象
通过用学生编号不断的循环查询学生信息;
由两部分组成;
1.主代码“
ArrayListDemo.java
”
2.Student.java 学生类--模板
------------
Student.java 的代码:
package student;
import com.sun.org.apache.xpath.internal.objects.XString;
public class Student {
private String studyid;
private String name;
private int age;
private String className;
public Student() { //设置无参构造器
}
public Student(String studyid, String name, int age, String className) { //设置有参构造器
this.studyid = studyid;
this.name = name;
this.age = age;
this.className = className;
}
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 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;
}
}
2.主代码:
package student;
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListDemo {
public static void main(String[] args) {
//1.定义一个学生类,后期用于创建对象封装学生数据
//2.定义一个集合对象用于装学生对象
ArrayList<Student> stus=new ArrayList<>();
//把一个学生实例对象存储到 stu中
stus.add(new Student("202001","猪八戒",900,"天宫一班"));
stus.add(new Student("202002","孙悟空",800,"天宫五班"));
stus.add(new Student("202003","沙和尚",1900,"天宫二班"));
stus.add(new Student("202004","白龙马",990,"天宫三班"));
//3.遍历集合中的每个学生对象,展示其数据
for (int i = 0; i <stus.size() ; i++) {
Student s=stus.get(i); //获取每个学生对象
System.out.println(s.getStudyid()+"\t\t"+s.getName()+"\t\t"+s.getAge()+"\t\t"+s.getClassName());
}
//4.让用户不断地输入学号,可以搜索出该学生对象信息并展示出来(独立成方法)
Scanner sc=new Scanner(System.in);
//idea中快捷键是ctrl+ait+T
while (true) {
System.out.println("请输入你要查询的学生的学号:");
String id=sc.next();
Student s=getStudentById(stus,id);
// 判断学号是否存在
if(s==null){
System.out.println("查无此人!");
}else{
//找到了该学生对象了,信息如下:
System.out.println(s.getStudyid()+"\t\t"+s.getName()+"\t\t"+s.getAge()+"\t\t"+s.getClassName());
}
}
}
// 根据学生类,去集合中找出学生对象并返回
public static Student getStudentById(ArrayList<Student> stus1,String studyId){
for (int i = 0; i < stus1.size(); i++) {
Student s=stus1.get(i);
if(s.getStudyid().equals(studyId)){
return s;
}
}
return null;
}
}