自学内容网 自学内容网

java后端开发day13--面向对象综合练习

在这里插入图片描述
(以下内容全部来自上述课程)
注意:先有javabean,才能创建对象。

1.文字版格斗游戏

格斗游戏,每个游戏角色的姓名,血量,都不相同,在选定人物的时候(new对象的时候),这些信息就应该被确定下来。
在这里插入图片描述
简单版:

JavaBean类(无main):

import java.util.Random;

public class Role {
    private String name;
    private int blood;

    public Role() {
    }

    public Role(String name, int blood) {
        this.name = name;
        this.blood = blood;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return blood
     */
    public int getBlood() {
        return blood;
    }

    /**
     * 设置
     * @param blood
     */
    public void setBlood(int blood) {
        this.blood = blood;
    }

    public String toString() {
        return "Role{name = " + name + ", blood = " + blood + "}";
    }
    //定义一个方法,用于攻击别人
    //思考:谁攻击谁?
    //Role r1 = new Role();
    //Role r2 = new Role();
    //r1.attack(r2);
    //方法的调用者去攻击参数
    public void attack(Role role){
        //计算造成的伤害1~20
        Random r = new Random();
        int hurt = r.nextInt(20)+1;
        //修改挨打的人的血量
        //挨揍的人的剩余血量 = 老的血量-新的伤害
        int remainBlood = role.getBlood() - hurt;
        //对剩余血量做一个判断,如果为负数,那么就修改为0
        remainBlood = remainBlood<0?0:remainBlood;
        //修改挨打的人的血量
        role.setBlood(remainBlood);
        //this表示方法的调用者
        System.out.println(this.getName()+"举起拳头,打了"+role.getName()+"一下,"
                + "造成了"+hurt+"点伤害,"+ role.getName()+"还剩下了"+remainBlood+"点血");
    }
}

开始使用

public class GameTest {
    public static void main(String[] args) {
        //1.创建第一个角色
        Role r1 = new Role("乔峰",100);
        //2.创建第二个角色
        Role r2 = new Role("鸠摩智",100);
        //3.让两个角色进行格斗,回合制游戏
        while (true){
            //r1 用拳头打 r2
            r1.attack(r2);
            //判断r2的血量是否小于等于0
            if(r2.getBlood()<=0){
                System.out.println(r2.getName()+"已经挂了,"+r1.getName()+"赢了");
                break;
            }
            //r2 用拳头打 r1
            r2.attack(r1);
            //判断r1的血量是否小于等于0
            if(r1.getBlood()<=0){
                System.out.println(r1.getName()+"已经挂了,"+r2.getName()+"赢了");
                break;
            }
        }
    }
}

复杂版:

在这里插入图片描述

import java.util.Random;

public class Role {
    private String name;
    private int blood;
    private char gender;
    private String face;

    String[] boyfaces = {"风流俊雅","气宇轩昂","相貌英俊","五官端正","相貌平平","一塌糊涂","面目狰狞"};
    String[] girlfaces = {"美奂绝伦","沉鱼落雁","婷婷玉立","身材娇好","相貌平平","相貌简陋","惨不忍睹"};

    String[] attacks_desc = {
            "%s使出了一招【背心钉】,转到对方身后,一掌向%s背心的灵台穴拍去。",
            "%s使出了一招【游空探爪】,飞起身形自半空中变掌为抓锁向%s。",
            "%s大喝一声,身形下伏,一招【劈雷坠地】,捶向%s双腿。",
            "%s运气于掌,一瞬间掌心变得血红,一式【掌心雷】,推向%s。",
            "%s阴手翻起阳手跟进,一招【没遮拦】,结结实实的捶向%s。",
            "%s上步抢身,招中套招,一招【劈挂连环】,连环攻向%s。"
    };
    String[] injureds_desc = {
            "结果%s退了半步,毫发无损",
            "结果给%s造成一处瘀伤",
            "结果一击命中,%s痛得弯下腰",
            "结果%s痛苦地闷哼了一声,显然受了点内伤",
            "结果%s摇摇晃晃,一跤摔倒在地",
            "结果%s脸色一下变得惨白,连退了好几步",
            "结果%s一声惨叫,像滩软泥般塌了下去"
    };


    public Role() {
    }

    public Role(String name, int blood,char gender) {
        this.name = name;
        this.blood = blood;
        this.gender = gender;
        //随机长相
        setFace(gender);
    }


    public char getGender() {
        return gender;
    }

    public void setGender(char gender) {
        this.gender = gender;
    }

    public String getFace() {
        return face;
    }

    public void setFace(char gender) {
        //长相是随机的
        if(gender=='男'){
            //随机一个长相
            int index = new Random().nextInt(boyfaces.length);
            this.face = boyfaces[index];
        } else if(gender=='女'){
            //随机一个长相
            int index = new Random().nextInt(girlfaces.length);
            this.face = girlfaces[index];
        } else {
            face = "面目狰狞";
        }
    }



    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return blood
     */
    public int getBlood() {
        return blood;
    }

    /**
     * 设置
     * @param blood
     */
    public void setBlood(int blood) {
        this.blood = blood;
    }

    public String toString() {
        return "Role{name = " + name + ", blood = " + blood + "}";
    }
    //定义一个方法,用于攻击别人
    //思考:谁攻击谁?
    //Role r1 = new Role();
    //Role r2 = new Role();
    //r1.attack(r2);
    //方法的调用者去攻击参数
    public void attack(Role role){
        Random r = new Random();
        int index = r.nextInt(attacks_desc.length);
        String KungFu = attacks_desc[index];
        System.out.println("===============================");
        //输出攻击效果
        System.out.printf(KungFu,this.getName(),role.getName());
        //计算造成的伤害1~20
        int hurt = r.nextInt(20)+1;
        //修改挨打的人的血量
        //挨揍的人的剩余血量 = 老的血量-新的伤害
        int remainBlood = role.getBlood() - hurt;
        //对剩余血量做一个判断,如果为负数,那么就修改为0
        remainBlood = remainBlood<0?0:remainBlood;
        //修改挨打的人的血量
        role.setBlood(remainBlood);
       //受伤的描述:按照程度不同来判断
        if(remainBlood>90){
            System.out.printf(injureds_desc[0],role.getName());
        } else if(remainBlood>80 && remainBlood<=90){
            System.out.printf(injureds_desc[1],role.getName());
        } else if(remainBlood>70 && remainBlood<=80){
            System.out.printf(injureds_desc[2],role.getName());
        } else if(remainBlood>60 && remainBlood<=70){
            System.out.printf(injureds_desc[3],role.getName());
        } else if(remainBlood>40 && remainBlood<=60){
            System.out.printf(injureds_desc[4],role.getName());
        } else if(remainBlood>10 && remainBlood<=40){
            System.out.printf(injureds_desc[5],role.getName());
        } else if(remainBlood<=10){
            System.out.printf(injureds_desc[6],role.getName());
        }
        System.out.println();

    }
    public void showRoleInfo(){
        System.out.println("姓名:"+getName());
        System.out.println("血量:"+getBlood());
        System.out.println("性别:"+getGender());
        System.out.println("长相:"+getFace());
    }
}

public class GameTest {
    public static void main(String[] args) {
        //1.创建第一个角色
        Role r1 = new Role("乔峰",100,'男');
        //2.创建第二个角色
        Role r2 = new Role("鸠摩智",100,'男');
        //显示角色信息
        r1.showRoleInfo();
        r2.showRoleInfo();
        //3.让两个角色进行格斗,回合制游戏
        while (true){
            //r1 用拳头打 r2
            r1.attack(r2);
            //判断r2的血量是否小于等于0
            if(r2.getBlood()<=0){
                System.out.println(r2.getName()+"已经挂了,"+r1.getName()+"赢了");
                break;
            }
            //r2 用拳头打 r1
            r2.attack(r1);
            //判断r1的血量是否小于等于0
            if(r1.getBlood()<=0){
                System.out.println(r1.getName()+"已经挂了,"+r2.getName()+"赢了");
                break;
            }
        }
    }
}

2.两个对象数组练习

1.定义数组存储3个商品对象

商品的属性:商品的id,名字,价格,库存。
创建三个商品对象,并把商品对象存入到数组当中。

javabean:

package test2;

public class Goods {
    private String id;
    private String name;
    private double price;
    private int count;
    public Goods() {

    }
    public Goods(String id, String name, double price, int count) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.count = count;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public int getCount() {
        return count;
    }
    public void setCount(int count) {
        this.count = count;
    }

}

使用:

package test2;

public class GoodsTest {
    public static void main(String[] args) {
    //1.创建一个数组
    Goods[] goods = new Goods[3];
    //2.创建三个商品对象
    Goods g1 = new Goods("001","倚天剑",1000,100);
    Goods g2 = new Goods("002","屠龙刀",10000,50);
    Goods g3 = new Goods("003","九阳神功",9999,10000);
    //3.把商品对象添加到数组中
    goods[0] = g1;
    goods[1] = g2;
    goods[2] = g3;
    //4.遍历数组
    for (int i = 0; i < goods.length; i++) {
        Goods g = goods[i];
        System.out.println(g.getId()+"\t"+g.getName()+"\t"+g.getPrice()+"\t"+g.getCount());

        }
    }

}

2.键盘录入的两种不同体系:

package cars;

import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        //键盘录入
        //第一套体系
        //nextInt; 接收整数
        //nextDouble(); 接收小数
        //next(); 接收字符串
        //遇到空格,制表符,回车就停止接受。这些符号后面的数据就不会接收了。

        //第二套体系
        //nextLine(); 接收字符串
        //可以接受空格,制表符,遇到回车才会停止。

        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个整数:"); //123 123
        int num1 = sc.nextInt();
        System.out.println(num1); //123
        System.out.println("请输入第二个整数");//不会显示,无需再次输入
        int num2 = sc.nextInt();
        System.out.println(num2); //123

        Scanner sc1 = new Scanner(System.in);
        System.out.println("请输入一个字符串"); //abc bcd
        String str1 = sc1.nextLine();
        System.out.println(str1); //abc
        System.out.println("请输入第二个字符串"); //不会显示,无需再次输入
        String str2 = sc1.nextLine();
        System.out.println(str2); //bcd

        Scanner sc2 = new Scanner(System.in);
        System.out.println("请输入一个字符串"); //abc bcd
        String line1 = sc2.nextLine();
        System.out.println(line1); //abc bcd
        System.out.println("请输入第二个字符串"); //123 789
        String line2 = sc2.nextLine();
        System.out.println(line2); //123 789
    }
}

注意:

  1. 两套体系不能混用。
  2. 先用第一套体系。
  3. 等学习类型转换之后,再用第二套体系。

3.定义数组存储3部汽车对象。

汽车的属性:品牌,价格,颜色。
创建三个汽车对象,数据通过键盘录入而来,并把数据存入到数组当中。

javabean:

package cars;

public class Cars {
    private String brand;
    private int prise;
    private String color;


    public Cars() {
    }

    public Cars(String brand, int prise, String color) {
        this.brand = brand;
        this.prise = prise;
        this.color = color;
    }

    /**
     * 获取
     * @return brand
     */
    public String getBrand() {
        return brand;
    }

    /**
     * 设置
     * @param brand
     */
    public void setBrand(String brand) {
        this.brand = brand;
    }

    /**
     * 获取
     * @return prise
     */
    public int getPrise() {
        return prise;
    }

    /**
     * 设置
     * @param prise
     */
    public void setPrise(int prise) {
        this.prise = prise;
    }

    /**
     * 获取
     * @return color
     */
    public String getColor() {
        return color;
    }

    /**
     * 设置
     * @param color
     */
    public void setColor(String color) {
        this.color = color;
    }

    public String toString() {
        return "Cars{brand = " + brand + ", prise = " + prise + ", color = " + color + "}";
    }
}

使用:

package cars;

import cars.Cars;

import java.util.Scanner;

public class CarsTest {
    public static void main(String[] args) {
        //1.创建一个数组用来存3个汽车对象
        Cars[] cars = new Cars[3];

        //2.创建3个汽车对象,数据来自于键盘录入
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < cars.length; i++) {
            //创建汽车的对象
            //放在循环外就只有一个对象,后续录入都是在修改这个对象,
            // 所以需要放在循环里面
            Cars c = new Cars();

            //录入品牌
            System.out.println("请输入第" + (i + 1) + "辆车的品牌");
            String brand = sc.next();
            c.setBrand(brand);

            //录入价格
            System.out.println("请输入第" + (i + 1) + "辆车的价格");
            int prise = sc.nextInt();
            c.setPrise(prise);

            //录入颜色
            System.out.println("请输入第" + (i + 1) + "辆车的颜色");
            String color = sc.next();
            c.setColor(color);
            //把汽车对象存入数组中
            cars[i] = c;
        }

        //3.遍历数组,获取每一个汽车对象的品牌,价格,颜色
        for (int i = 0; i < cars.length; i++) {
            System.out.println("第" + (i + 1) + "辆车的品牌是:" + cars[i].getBrand());
            System.out.println("第" + (i + 1) + "辆车的价格是:" + cars[i].getPrise());
            System.out.println("第" + (i + 1) + "辆车的颜色是:" + cars[i].getColor());
        }
    }
}

4.定义数组存储3部手机对象

手机的属性:品牌,价格,颜色
要求:计算出三部手机的平均价格

JavaBean:

package Phone;

public class Phone {
    private String brand;
    private int prise;
    private String color;


    public Phone() {
    }

    public Phone(String brand, int prise, String color) {
        this.brand = brand;
        this.prise = prise;
        this.color = color;
    }

    /**
     * 获取
     * @return brand
     */
    public String getBrand() {
        return brand;
    }

    /**
     * 设置
     * @param brand
     */
    public void setBrand(String brand) {
        this.brand = brand;
    }

    /**
     * 获取
     * @return prise
     */
    public int getPrise() {
        return prise;
    }

    /**
     * 设置
     * @param prise
     */
    public void setPrise(int prise) {
        this.prise = prise;
    }

    /**
     * 获取
     * @return color
     */
    public String getColor() {
        return color;
    }

    /**
     * 设置
     * @param color
     */
    public void setColor(String color) {
        this.color = color;
    }

    public String toString() {
        return "Phone{brand = " + brand + ", prise = " + prise + ", color = " + color + "}";
    }
}

使用:

package Phone;

public class PhoneTest {
    public static void main(String[] args) {
        //1.创建一个数组用来存3个手机对象
        Phone[] phones = new Phone[3];
        //2.创建3个手机对象
        Phone p1 = new Phone("小米", 2999, "黑色");
        Phone p2 = new Phone("苹果", 8999, "玫瑰金");
        Phone p3 = new Phone("锤子", 3999, "棕色");
        //3.把手机对象添加到数组当中
        phones[0] = p1;
        phones[1] = p2;
        phones[2] = p3;
        //4.计算三部手机的平均价格
        int sum = 0;
        for (int i = 0; i < phones.length; i++) {
            sum += phones[i].getPrise();
        }
        //求平均值
        int avg = sum / phones.length;
        System.out.println(avg);
    }
}

5.定义数组存储4个女朋友的对象

女朋友的属性:姓名,年龄,性别,爱好
要求1:计算出四个女朋友的平均年龄
要求2:统计年龄比平均值小的女朋友有几个,并把她们的所有信息打印出来

javabean:

public class GrilFriend {
    private String name;
    private int age;
    private String gender;
    private String hobby;


    public GrilFriend() {
    }

    public GrilFriend(String name, int age, String gender, String hobby) {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.hobby = hobby;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
        this.age = age;
    }

    /**
     * 获取
     * @return gender
     */
    public String getGender() {
        return gender;
    }

    /**
     * 设置
     * @param gender
     */
    public void setGender(String gender) {
        this.gender = gender;
    }

    /**
     * 获取
     * @return hobby
     */
    public String getHobby() {
        return hobby;
    }

    /**
     * 设置
     * @param hobby
     */
    public void setHobby(String hobby) {
        this.hobby = hobby;
    }

    public String toString() {
        return "GrilFriend{name = " + name + ", age = " + age + ", gender = " + gender + ", hobby = " + hobby + "}";
    }
}

使用:

package girlfriend;

public class GrilFriendTest {
    public static void main(String[] args) {
        //1.创建一个数组用来存4个女朋友对象
        GrilFriend[] gf = new GrilFriend[4];
        //2.创建4个女朋友对象
        GrilFriend gf1 = new GrilFriend("迪丽热巴", 18, "女", "旅游");
        GrilFriend gf2 = new GrilFriend("古力娜扎", 19, "女", "化妆");
        GrilFriend gf3 = new GrilFriend("马尔扎哈", 20, "男", "购物");
        GrilFriend gf4 = new GrilFriend("赵丽颖", 21, "女", "跳舞");
        //3.把女朋友对象添加到数组中
        gf[0] = gf1;
        gf[1] = gf2;
        gf[2] = gf3;
        gf[3] = gf4;
        //4.计算平均年龄
        int sum = 0;
        for (int i = 0; i < gf.length; i++) {
            GrilFriend g = gf[i];
            sum += g.getAge();
        }
        int avg = sum / gf.length;
        System.out.println("平均年龄是:" + avg);
        //5.找出低于平均年龄的女朋友,并统计个数
        int count = 0;
        for (int i = 0; i < gf.length; i++) {
            if (gf[i].getAge() < avg) {
                //6.输出低于平均年龄的女朋友的信息
                System.out.println(gf[i].getName() + " " + gf[i].getAge() +
                        " " + gf[i].getGender() + " " + gf[i].getHobby());
                count++;
                System.out.println("低于平均年龄的女朋友有" + count + "个");
            }
        }
    }


}

3.复杂对象数组练习

定义一个长度为3的数组,数组存储1~3名学生对象作为初始数据,学生对象的学号,姓名各不同。
学生的属性:学号,姓名,年龄。
要求1:再次添加一个学生对象,并在添加的时候进行学号的唯一性判断。
要求2:添加完毕后,遍历所有学生信息。
要求3:通过id删除学生信息。
如果存在,则删除,如果不存在,则提示删除失败。
要求4:删除完毕之后,遍历所有学生信息。
要求5:查询数组id为“heima002”的学生,如果存在,则将他的年龄+1岁

javabean:

package Student;

public class Student {
    private int id;
    private String name;
    private int age;


    public Student() {
    }

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     * @return id
     */
    public int getId() {
        return id;
    }

    /**
     * 设置
     * @param id
     */
    public void setId(int id) {
        this.id = id;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return "add{id = " + id + ", name = " + name + ", age = " + age + "}";
    }
}

1.添加和遍历

使用:

package Student;

public class StudentTest {
    public static void main(String[] args) {
        /*定义一个长度为3的数组,数组存储1~3名学生对象作为初始数据,学生对象的学号,姓名各不同。
        学生的属性:学号,姓名,年龄。
        要求1:再次添加一个学生对象,并在添加的时候进行学号的唯一性判断。
        要求2:添加完毕后,遍历所有学生信息。
        要求3:通过id删除学生信息。
如果存在,则删除,如果不存在,则提示删除失败。
        要求4:删除完毕之后,遍历所有学生信息。
        要求5:查询数组id为“heima002”的学生,如果存在,则将他的年龄+1岁*/
        //1.创建一个数组用来存储学生对象
        Student[] arr = new Student[3];
        //2.创建学生对象
        Student s1 = new Student(1, "张三", 20);
        Student s2 = new Student(2, "李四", 21);
        Student s3 = new Student(3, "王五", 22);
        //3.把学生对象添加到数组中
        arr[0] = s1;
        arr[1] = s2;
        arr[2] = s3;
        //要求1:再次添加一个学生对象,并在添加的时候进行学号的唯一性判断。
        //读题拆题法
        //创建一个学生对象
        Student s4 = new Student(4, "赵六", 23);

        //学号的唯一性判断
        //已存在---不添加
        //不存在---添加
        boolean flag = contains(arr, s4.getId());
        if (flag) {
            System.out.println("学号已存在,添加失败");
        } else {
            //把s4添加到数组当中
            //1.数组已经存满---只能创建一个新的数组,新数组的长度 = 老数组的长度 + 1
            //2.数组没有存满---直接把s4添加到数组当中
            int count = getCount(arr);
            if (count == arr.length) {
                //已经存满
                //创建一个新的数组,长度 = 老数组 + 1
                //然后把老数组的元素,拷贝到新数组当中
                Student[] newArr = creatNewArr(arr);
                //[stu1,stu2,stu3]
                //[stu1,stu2,stu3,null]
                //把s4添加进去
                newArr[count] = s4;

                //要求2:添加完毕后,遍历所有学生信息。
                printArr(newArr);
            } else {
                //没有存满
                //[stu1,stu2,null]
                //getCount获取到的是2,表示数组中已经有了2个元素
                //还有一层意思:如果下一次要添加数据,就是添加到2的位置
                arr[count] = s4;

                //要求2:添加完毕后,遍历所有学生信息。
                printArr(arr);
            }
        }


    }

    //遍历数组(新老都遍历)
    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 Student[] creatNewArr(Student[] arr) {
        Student[] newArr = new Student[arr.length + 1];
        for (int i = 0; i < arr.length; i++) {
            newArr[i] = arr[i];
        }
        //把新数组返回
        return newArr;
    }

    //定义一个方法判断数组中已经存了几个元素
    public static int getCount(Student[] arr) {
        //定义一个计数器
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] != null) {
                count++;
            }
        }
        return count;
    }

    //1.我要干嘛?---唯一性判断
    //2.我干这件事,需要什么才能完成?---数组,id
    //3.方法的调用处是否需要继续使用方法的结果?---需要
    public static boolean contains(Student[] arr, int id) {
        for (int i = 0; i < arr.length; i++) {
            Student stu = arr[i];
            if (stu != null) {
                if (arr[i].getId() == id) {
                    return true;
                }
            }
        }
        //遍历完了数组,还没有找到,说明不存在
        return false;
    }
}


2.删除和修改

使用:

package Student;

public class Test {
    public static void main(String[] args) {
        /*定义一个长度为3的数组,数组存储1~3名学生对象作为初始数据,学生对象的学号,姓名各不同。
        学生的属性:学号,姓名,年龄。
        要求1:再次添加一个学生对象,并在添加的时候进行学号的唯一性判断。
        要求2:添加完毕后,遍历所有学生信息。
        要求3:通过id删除学生信息。
如果存在,则删除,如果不存在,则提示删除失败。
        要求4:删除完毕之后,遍历所有学生信息。
        要求5:查询数组id为“2”的学生,如果存在,则将他的年龄+1岁*/
        //1.创建一个数组用来存储学生对象
        Student[] arr = new Student[3];
        //2.创建学生对象
        Student s1 = new Student(1, "张三", 20);
        Student s2 = new Student(2, "李四", 21);
        Student s3 = new Student(3, "王五", 22);
        //3.把学生对象添加到数组中
        arr[0] = s1;
        arr[1] = s2;
        arr[2] = s3;

        //要求3:通过id删除学生信息。
        //如果存在,则删除,如果不存在,则提示删除失败。
        //找到id在数组中对应的索引
        int index = getIndex(arr, 2);
        //判断index是否为-1
        if (index == -1) {
            System.out.println("id不存在,删除失败");
        } else {
            //删除
            //把index位置的元素赋值为null
            arr[index] = null;
            //要求4:删除完毕之后,遍历所有学生信息。
            printArr(arr);
        }
        // 要求5:查询数组id为“2”的学生,如果存在,则将他的年龄+1岁
        //找到id为2的学生对象
        int index2 = getIndex(arr, 2);
        //判断index2是否为-1
        if (index2 == -1) {
            System.out.println("id不存在,年龄+1失败");
        } else {
            //把id为2的学生对象的年龄+1
            Student stu = arr[index2];
            int newAge = stu.getAge() + 1;
            //把+1的年龄设置回去
            stu.setAge(newAge);
            //要求2:添加完毕后,遍历所有学生信息。
            printArr(arr);
        }



    }
    //找到id在数组中对应的索引
    //1.我要干嘛? 我要找到id在数组中对应的索引
    //2.我干这件事,需要什么才能完成? 数组  id
    //3.方法的调用处是否需要继续使用方法的结果?  需要
    public static int getIndex(Student[] arr, int id) {
        int index = -1; //假设id在数组中不存在,值为-1
        for (int i = 0; i < arr.length; i++) {
            //获取数组中的每一个学生对象
            Student stu = arr[i];
            //对stu进行一个非空判断
            if (stu != null) {
                int sid = stu.getId();
                if (sid == id) {
                    index = i;
                    break;
                }
            }
        }
        //当循环结束之后如果还没找到就表示不存在
        return index;
    }
    //遍历数组(新老都遍历)
    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());
            }
        }
    }
}


原文地址:https://blog.csdn.net/2301_80071187/article/details/145537955

免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!