数组对象练习

定义一个长度为3的数组,数组存储1~3名学生对象作为初始数据,学生对象的学号,姓名各不相同。学生的属性:学号,姓名,年龄。

要求1:再次添加一个学生对象,并在添加的时候进行学号的唯一性判断。

要求2:添加完毕之后,遍历所有学生信息。

要求3∶通过id删除学生信息如果存在,则删除,如果不存在,则提示删除失败。

要求4:删除完毕之后,遍历所有学生信息。

要求5:查询数组id为“02”的学生,如果存在,则将他的年龄+1岁
 

最后完成要求5

利用方法来识别id是否存在,在数组的哪一个位置

package Test7;

public class StudentTest2 {
    public static void main(String[] args) {
        //创建长度三的数组
        Student[] arr = new Student[3];

        //创建学生对象
        Student s1 = new Student(1,"小明",19);
        Student s2 = new Student(2,"小红",20);
        Student s3 = new Student(3,"小白",22);
        //Student s3 = new Student(3,"小李",21);

        //把学生对象添加到数组当中
        arr[0] = s1;
        arr[1] = s2;
        arr[2] = s3;

        int Intdex = getIndex(arr,2);
        if(Intdex >= 0){
            Student stu = arr[Intdex];
            int newArr = stu.getAge() + 1;
            stu.setAge(newArr);
            printArr(arr);
        }else {
            System.out.println("此id不存在,修改失败");
        }
    }
    public static void printArr(Student[] arr){
        for (int i = 0; i < arr.length; i++) {
            Student stu = arr[i];
            if(stu != null){
                System.out.println(stu.getId()+", "+stu.getName()+", "+stu.getAge());
            }
        }
    }

    public static int getIndex(Student[] arr , int id){
        for (int i = 0; i < arr.length; i++) {
            Student stu = arr[i];
            if(stu != null){
                int Index = stu.getId();
                if(Index == id){
                    return i;
                }
            }
        }
        return -1;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值