练习:对象数组 5
定义一个长度为 3 的数组,数组存储 1~3 名学生对象作为初始数据,学生对象的学号,姓名各不相同。学生的属性:学号,姓名,年龄。
要求 1:再次添加一个学生对象,并在添加的时候进行学号的唯一性判断。
要求 2:添加完毕之后,遍历所有学生信息。
要求 3:通过 id 删除学生信息,如果存在,则删除,如果不存在,则提示删除失败。
要求 4:删除完毕之后,遍历所有学生信息。
要求 5:查询数组 id 为“2022072002”的学生,如果存在,则将他的年龄+1 岁。
代码一:
//对象数组 5:
//代码一:
package demo03;
public class Students {//定义学生的三个私有属性:姓名(name)、学号(id)、年龄(age):private String name;private int id;private int age;//空参构造:public Students() {}//含参构造:public Students(String name, int id, int age) {this.name = name;this.id = id;this.age = age;}//get 和 set 方法:public String getName() {return name;}public void setName(String name) {this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}
}
代码二:
//对象数组 5:
//代码二:
package demo03;
public class StudentsTest {public static void main(String[] args) {//定义一个长度为 3 的数组,用于存储学生对象;Students[] stu = new Students[3];//存储 3 名学生对象作为初始数据:Students stu1 = new Students("张三", 2022072001, 20);Students stu2 = new Students("李四", 2022072002, 21);Students stu3 = new Students("王五", 2022072003, 22);stu[0] = stu1;stu[1] = stu2;stu[2] = stu3;//再次添加一个学生对象:Students stu4 = new Students("赵六", 2022072004, 23);//判断学号唯一性:boolean result = idJudge(stu, stu4);if(result) {System.out.println("学号已经存在!");}else {int count = countNumber(stu);if(count == stu.length) {Students[] newArr = creatNewArr(stu);newArr[count] = stu4;printArr(newArr);}else {stu[count] = stu4;printArr(stu);}}//删除 id:int index = index(stu, 2022072001);if(index >= 0) {stu[index] = null;System.out.println("删除 id 后的学生信息:");printArr(stu);}else {System.out.println("id 不存在,删除失败!");}//查询数组 id 为“2022072002”的学生的索引:int studentIndex = index(stu, 2022072002);//如果存在则将年龄 +1:if(studentIndex >= 0) {int age = stu[studentIndex].getAge() + 1;stu[studentIndex].setAge(age);System.out.println("修改年龄后的学生信息:");printArr(stu);}else {System.out.println("id不存在,修改失败!");}}//定义学号唯一性判断的方法:public static boolean idJudge(Students[] stu, Students stu4) {for(int i = 0; i < stu.length; i++) {if(stu[i] != null) {if(stu[i].getId() == stu4.getId()) {return true;}}}return false;}//定义一个方法来判断数组中存了几个元素:public static int countNumber(Students[] stu) {int count = 0;for(int i = 0; i < stu.length; i++) {if(stu[i] != null) {count++;}}return count;}//定义一个创建新数组的方法:public static Students[] creatNewArr(Students[] stu) {Students[] newArr = new Students[stu.length + 1];for(int i = 0; i < stu.length; i++) {newArr[i] = stu[i];}return newArr;}//定义一个方法来遍历数组中每个元素:public static void printArr(Students[] stu) {for(int i = 0; i < stu.length; i++) {if(stu[i] != null) {System.out.println(stu[i].getName() + "------" + stu[i].getId() + "------" + stu[i].getAge());}}}//定义一个方法用于判断 id 所在索引位置:public static int index(Students[] stu, int id) {for(int i = 0; i < stu.length; i++) {if(stu[i] != null) {if(stu[i].getId() == id) {return i;}}}return -1;}
}
运行结果: