java实战训练
案例 学生信息系统
需求
展示数据,并按照学号完成搜索
学生类信息(学号,姓名,性别,班级)
测试数据:
20180302,叶孤城,23,护理一班
20180303,东方不败,23,推拿二班
20180304,西门吹雪,26,中药学四班
20180305,梅超风,26,神经科二班
public class ArrayListTest6 {
public static void main(String[] args) {
//1.定义学生类,后期用于创建对象封装学生数据
//2.定义集合对象用于装学生对象
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("20180302", "叶孤城", 23, "护理一班"));
students.add(new Student("20180303", "东方不败", 23, "推拿二班"));
students.add(new Student("20180304", "西门吹雪", 26, "中药学四班"));
students.add(new Student("20180305", "梅超风", 26, "神经科二班"));
//3.遍历集合中每个学生对象展示其数据
for (int i = 0; i < students.size(); i++) {
Student student = students.get(i);
System.out.println("学号:" + student.getStudyId() + "姓名:" + student.getName() +
"年龄" + student.getAge() + "班级:" + student.getClassName());
}
//4.让用户不断地输入学号,可以搜索出该学生对象信息并展示出来(独立成方法)
Scanner sc = new Scanner(System.in);
System.out.println("请您输入要查询的学生的学号!");
String Id = sc.next();
Student s = getStudentByStudyId(students, Id);
if (s == null) {
System.out.println("查无此人!");
} else {
System.out.println(s.getStudyId() + s.getName() + s.getAge() + s.getClassName());
}
}
//根据学号去集合找出学生对象并返回。
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;//查无此学号!
}
}
public class Student {
private String studyId;
private String name;
private int age;
private String className;
public Student() {
}//标准javabean一定要有无参构造器
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;
}
}
总结
- 这里体现了封装的方便,面向对象的编程。同时在实现一个独立功能时尽量采用方法去实现