package practice;
import java.util.ArrayList;
import java.util.Scanner;
public class practicedemo12 {
public static void main(String[] args) {
//1.定义一个Student类
//3.直接建立集合,往Student类里添加内容,并把地址给集合
ArrayList<Student> students=new ArrayList<>();
students.add(new Student("202201","陈1",21,"1801"));
students.add(new Student("202202","陈2",22,"1801"));
students.add(new Student("202203","陈3",23,"1801"));
students.add(new Student("202204","陈4",24,"1801"));
//4.输出所有学生信息
System.out.println("学生信息如下:");
for (int i = 0; i < students.size(); i++) {
Student m=students.get(i);
System.out.println(m.getStuNumber()+"\t"+m.getName()+"\t"+m.getAge()+"\t"+m.getClassNumber());
}
//5.输入想查找的学生的学号
Scanner sc=new Scanner(System.in);
//7.引用方法,因为不知道查几个人,所以要用一个死循环
while (true){
System.out.println("想查找的学生学号:");
String studyNumber=sc.next(); //易错,如果不把这句放在循环里面,会一直报查无此人,查无此人
Student v= returnmesage(students,studyNumber);
if(v==null){
System.out.println("查无此人");
}else {
System.out.println(v.getStuNumber()+"\t"+v.getName()+"\t"+v.getAge()+"\t"+v.getClassNumber());
}
}
}
///6.定义方法,输入学生学号即可查她的所有信息
public static Student returnmesage(ArrayList<Student> students,String studyNumber){
for (int i = 0; i < students.size(); i++) {
Student s=students.get(i);
if(s.getStuNumber().equals(studyNumber)){
return s; //易错,返回的应该是集合里的第i个元素,里面装着Student类的第i条信息的地址
}
}
//System.out.println("查无此人");
return null;
}
}
package practice;
public class Student {
//2.按常规操作定义
private String stuNumber;
private String name;
private int age;
private String classNumber;
public Student(String stuNumber, String name, int age, String classNumber) {
this.stuNumber = stuNumber;
this.name = name;
this.age = age;
this.classNumber = classNumber;
}
public String getStuNumber() {
return stuNumber;
}
public void setStuNumber(String stuNumber) {
this.stuNumber = stuNumber;
}
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 getClassNumber() {
return classNumber;
}
public void setClassNumber(String classNumber) {
this.classNumber = classNumber;
}
}
注意:
1.定义方法的时候,集合students的属性是ArrayList< Student> ;
2.用死循环的时候,把Scanner输入学号内置,不然一直出现 “查无此人”。