java基础练习题

(1)判断和循环

①回文数

视频链接:判断和循环-10-两道力扣算法题和do...while循环_哔哩哔哩_bilibili

package com.itheima.demo1;

public class test {
    public static void main(String[] args) {
        int x=221;
        int temp=x;
        int num=0;
        while(x!=0){
            //拿到个位数
            int ge=x%10;
            //去掉个位
             x=x/10;
             //把个位数添加到右边
             num=num*10+ge;
        }
        System.out.println(num);
         //比较
        System.out.println(temp==num);
    }


}

②求商和余数

public class test {
    public static void main(String[] args) {
     int bcs=101;
     int cs=10;
     int count=0;

     while(bcs>=cs){
          bcs=bcs-cs;
          count++;
     }
        System.out.println("商为:"+count);
        System.out.println("余数为:"+bcs);
    }


}

(2)方法

 ①评委打分

视频网址:综合练习-05-评委打分_哔哩哔哩_bilibili

(3)字符串

 ①用户登录

视频网址:字符串-05-练习-用户登录_哔哩哔哩_bilibili

package com.itheima.demo1;

import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        //确定正确的用户名和密码
        String username="luomin";
        String password="123456";
        for(int i=3;i>0;i--){
            //输入账号和密码
            Scanner sc=new Scanner(System.in);
            System.out.println("请输入您的账号:");
            String susername=sc.next();
            System.out.println("请输入您的密码:");
            String spassword=sc.next();
            if(username.equals(susername) && password.equals(spassword)){
                System.out.println("登录成功!");
            }else{
                if(i==1){
                    System.out.println("登录失败,你没有机会了,账号已经锁定");
                }else{
                    System.out.println("登录失败,你还有"+(i-1)+"机会");
                }

            }
        }



    }


}

  ②遍历字符串

package com.itheima.demo1;

import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String str=sc.next();
        //进行遍历
        for(int i=0;i<str.length();i++) {
            //i依次表示字符串的每一个索引
            char c = str.charAt(i);
            System.out.println(c);
        }

    }


}

③统计字符次数

package com.itheima.demo1;

import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String str=sc.next();
        int bigCount=0;
        int smallCount=0;
        int numberCount=0;
        //进行遍历
        for(int i=0;i<str.length();i++) {
            //i依次表示字符串的每一个索引
            char c = str.charAt(i);
            if(c>='a'&&c<='z'){
                smallCount++;
            }else if(c>='A'&&c<='Z'){
                bigCount++;
            }else if(c>='0'&&c<='9'){
                numberCount++;
            }

        }
        System.out.println("小写字母有:"+smallCount+",大写字母有:"+bigCount+",数字字母有:"+numberCount);

    }


}

④拼接字符串

普通做法

package com.itheima.demo1;

public class test {
    public static void main(String[] args) {
        int []arr={1,2,3};
        String str=arrToString(arr);
        System.out.println("拼接之后为:"+str);
    }
    public static String arrToString(int[]arr){
        if(arr==null){
            return "";
        }
        if(arr.length==0){
            return "[]";
        }
        String result="[";
        for(int i=0;i<arr.length;i++){
            if(i==arr.length-1){
                result=result+arr[i];
            }else {
                result=result+arr[i]+",";
            }

        }
        return result+"]";
    }


}

利用StringBuilder

⑤字符串反转 

package com.itheima.demo1;

import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String str=sc.next();
        System.out.println(reverseStr(str));

    }

    public static String reverseStr(String str){
        String result="";
        for(int i=str.length()-1;i>=0;i--){
            result=result+str.charAt(i);

        }
        return result;
    }


}

⑥金额转换

package com.itheima.demo1;

import java.util.Scanner;

public class test {
    public static void main(String[] args) {
     //输入数值判断合法
        int number;
        while(true){
            Scanner sc=new Scanner(System.in);
            System.out.println("请输入金额:");
             number=sc.nextInt();
            if(number>=0&&number<=9999999){
                break;
            }else{
                System.out.println("你输入的金额不合法,请重新输入");
            }

        }
        //从右到左取数字
        String result="";
        while(number!=0){
            int ge=number%10;
            number=number/10;

            result=rever(ge)+result;
        }
        //将金额转换至七位
        int count=7-result.length();

        for(int i=0;i<count;i++){
           result='零'+result;

        }
//        System.out.println(result);
        //添加单位 String[] arr = {"佰","拾","万","仟","佰","拾","元"};
        String endResult="";
        for(int i=0;i<result.length();i++){
            String[] arr = {"佰","拾","万","仟","佰","拾","元"};
             endResult=endResult+result.charAt(i)+arr[i];

        }
        System.out.println("转换后的金额为:"+endResult);

    }
    //转换数字为"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"
    public static String rever(int number){
        String[] arr = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};

        return arr[number];
    }




}

⑦手机号屏蔽

package com.itheima.demo1;

public class test {
    public static void main(String[] args) {
    String phoneNumber="13971620670";
    String start=phoneNumber.substring(0,3);
    String end=phoneNumber.substring(7);
    String result=start+"****"+end;
        System.out.println(result);

    }


}

 ⑧身份证信息查看

package com.itheima.demo1;

public class test {
    public static void main(String[] args) {
        String id="361101201202287133";
        String year=id.substring(6,10);
        String month=id.substring(10,12);
        String day=id.substring(12,14);
        System.out.println("人物信息为:");
        System.out.println("出生年月日"+year+"年"+month+"月"+day+"日");
        char gender=id.charAt(16);
        int genderId=gender-'0';
        if(genderId%2==0){
            System.out.println("性别为女");
        }else{
            System.out.println("性别为男");
        }


    }


}

⑨敏感词替换

package com.itheima.demo1;

public class test {
    public static void main(String[] args) {
       String text="你游戏玩的真菜,SB";
       String [] arr={"菜","SB"};
       for(int i=0;i<arr.length;i++){
           text=text.replace(arr[i],"***");
       }
        System.out.println(text);

    }


}

⑩罗马数字的两种写法

package com.itheima.demo1;

import java.util.Scanner;

public class test {
    //  转换罗马数字
    public static void main(String[] args) {
        String number;
        while(true){
            //输入字符串
            Scanner sc=new Scanner(System.in);
            System.out.println("请输入一个字符串:");
             number=sc.next();
            //判断是否符合规则
            boolean flag=check(number);
            if(flag==true){
                break;
            }else{
                System.out.println("输入的字符串不合法,请重新输入:");
                continue;
            }
        }

        //查找法:转换为罗马数字
        StringBuilder result=new StringBuilder();
        for(int i=0;i<number.length();i++){
            char c=number.charAt(i);
            int strid=c-48;
//            System.out.println(strid);
           String res =change(strid);
           result.append(res);
        }
        System.out.println(result);


    }
    public static boolean check(String number){
        if(number.length()>9){
            return false;
        }
        for(int i=0;i<number.length();i++){
            char c=number.charAt(i);
            if(c<'0'||c>'9'){
                return false;
            }
        }
        return true;
    }
    public static String change(int strid){
        String[] arr = {"", "Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ", "Ⅴ", "Ⅵ", "Ⅶ", "Ⅷ", "Ⅸ"};
        return arr[strid];
    }


}

11.调整符串的内容并比较

package com.itheima.demo1;

public class test {
    public static void main(String[] args) {
        //给定两个字符串A和B
        String stra="abcde";
        String strb="cdeab";
        System.out.println(compare(stra,strb));
    }
    //旋转字符串A
    public static boolean compare(String stra,String strb){
        for(int i=0;i<stra.length();i++){
            stra=rotate(stra);
            if(stra.equals(strb)){
               return true;
            }
        }
        return false;
    }
    public static String rotate(String str){
        char first=str.charAt(0);
        String end=str.substring(1);
        String result=end+first;
        return result;
    }
}



12.对称字符串

package com.itheima.demo1;

import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入字符串:");
        String str=sc.next();
        String result=new StringBuilder().append(str).reverse().toString();
        if(str.equals(result)){
            System.out.println(str+"是对称字符串");
        }else{
            System.out.println(str+"是非对称字符串");
        }

    }


}

(4)面向对象

①文字版格斗游戏

视频网址:面向对象综合训练-01-文字版格斗游戏_哔哩哔哩_bilibili

Role

package com.itheima.demo1;

import java.util.Random;

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


    public Role() {
    }

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

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

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

    /**
     * 获取
     * @return boold
     */
    public int getBoold() {
        return boold;
    }

    /**
     * 设置
     * @param boold
     */
    public void setBoold(int boold) {
        this.boold = boold;
    }
    //攻击
    public void attack(Role role){
        Random r=new Random();
        int hurt=r.nextInt(20)+1;
        int remainboold=role.getBoold()-hurt;
        remainboold=remainboold<0? 0:remainboold;
        //修改挨揍人的血量
        role.setBoold(remainboold);
        System.out.println(this.getName()+"打了"+role.getName()+"一下" +
                ",造成了"+hurt+"点伤害"+"还剩"+remainboold+"点血");
    }


}

GameTest测试类

package com.itheima.demo1;

public class GameTest {
    public static void main(String[] args) {
        Role r1=new Role("小明",100);
        Role r2=new Role("小李",100);
        while(true){
            r1.attack(r2);
            if(r2.getBoold()==0){
                System.out.println(r1.getName()+"K.O了"+r2.getName());
                break;
            }
            r2.attack(r1);
            if(r1.getBoold()==0){
                System.out.println(r2.getName()+"K.O了"+r1.getName());
                break;
            }
        }

    }
}

Role

package com.itheima.demo2;

import java.util.Random;

public class Role {
    private String name;
    private int boold;
    private String gender;
    private String face;
    String[] boyfaces= {"风流俊雅","气宇轩昂","相貌英俊","五官端正","相貌平平","一塌糊涂","面目狰狞"};
    String[] girlfaces ={"美奂绝伦","沉鱼落雁","婷婷玉立","身材娇好","相貌平平","相貌简陋","惨不忍睹"};
//    attack 攻击描述:
    String[] attacks_desc={
            "%s使出了一招【背心钉】,转到对方的身后,一掌向%s背心的灵台穴拍去。",
            "%s使出了一招【游空探爪】,飞起身形自半空中变掌为抓锁向%s。",
            "%s大喝一声,身形下伏,一招【劈雷坠地】,捶向%s双腿。",
            "%s运气于掌,一瞬间掌心变得血红,一式【掌心雷】,推向%s。",
            "%s阴手翻起阳手跟进,一招【没遮拦】,结结实实的捶向%s。",
            "%s上步抢身,招中套招,一招【劈挂连环】,连环攻向%s。"
    };

//    injured 受伤描述:
    String[] injureds_desc={
            "结果%s退了半步,毫发无损",
            "结果给%s造成一处瘀伤",
            "结果一击命中,%s痛得弯下腰",
            "结果%s痛苦地闷哼了一声,显然受了点内伤",
            "结果%s摇摇晃晃,一跤摔倒在地",
            "结果%s脸色一下变得惨白,连退了好几步",
            "结果『轰』的一声,%s口中鲜血狂喷而出",
            "结果%s一声惨叫,像滩软泥般塌了下去"
    };



    public Role() {
    }

    public Role(String name, int boold,String gender) {
        this.name = name;
        this.boold = boold;
        this.gender=gender;
        //设置长相
        setFace(gender);
    }

    public String getGender() {
        return gender;
    }

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

    public String getFace() {
        return face;
    }
    //根据性别随机长相
    public void setFace(String gender) {
        if(gender=="男"){
            Random r=new Random();
            int index=r.nextInt(boyfaces.length);
            this.face=boyfaces[index];
        }else if(gender=="女"){
            Random r=new Random();
            int index=r.nextInt(girlfaces.length);
            this.face=girlfaces[index];
        }else{
            this.face="面目狰狞";
        }

    }


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

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

    /**
     * 获取
     * @return boold
     */
    public int getBoold() {
        return boold;
    }

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

    //显示人物信息
    public void showInfo(){
        System.out.printf("姓名为:"+this.getName());
        System.out.println("");
        System.out.printf("血量为:"+this.getBoold());
        System.out.println();
        System.out.printf("性别为:"+this.getGender());
        System.out.println();
        System.out.printf("长相为:"+this.getFace());
        System.out.println();
    }
    //攻击方法
    public void attack(Role role){
        //攻击者的描述
        Random r=new Random();
        int index=r.nextInt(attacks_desc.length);
        String Kongfu=attacks_desc[index];
        System.out.printf(Kongfu,this.getName(),role.getName());
        System.out.println("");
        //随机血量
        int hurt=r.nextInt(20)+1;
        int remainboold=role.getBoold()-hurt;
        remainboold=remainboold<0? 0:remainboold;
        //修改挨揍人的血量
        role.setBoold(remainboold);
        //根据血量给出被攻击者的受伤描述

        if(remainboold>90){
            System.out.printf(injureds_desc[0],role.getName());
        }else if(remainboold>80&&remainboold<=90){
            System.out.printf(injureds_desc[1],role.getName());
        }else if(remainboold>70&&remainboold<=80) {
            System.out.printf(injureds_desc[2], role.getName());
        }else if(remainboold>60&&remainboold<=70){
                System.out.printf(injureds_desc[1],role.getName());
        }else if(remainboold>50&&remainboold<=60){
            System.out.printf(injureds_desc[3],role.getName());
        }else if(remainboold>40&&remainboold<=50){
            System.out.printf(injureds_desc[4],role.getName());
        }else if(remainboold>30&&remainboold<=40){
            System.out.printf(injureds_desc[5],role.getName());
        }else if(remainboold>10&&remainboold<=20){
            System.out.printf(injureds_desc[6],role.getName());
        }else {
            System.out.printf(injureds_desc[7],role.getName());
        }
        System.out.println("");
    }


}

GameTest

package com.itheima.demo2;

public class GameTest {
    public static void main(String[] args) {
        Role r1=new Role("小明",100,"男");
        Role r2=new Role("小李",100,"男");
        r1.showInfo();
        r2.showInfo();
        while(true){
            r1.attack(r2);
            if(r2.getBoold()==0){
                System.out.println(r1.getName()+"K.O了"+r2.getName());
                break;
            }
            r2.attack(r1);
            if(r1.getBoold()==0){
                System.out.println(r2.getName()+"K.O了"+r1.getName());
                break;
            }
        }

    }
}

②对象数组练习 

视频网址:面向对象综合训练-02-两个对象数组练习_哔哩哔哩_bilibili

Goods

package com.itheima.demo3;

public class Goods {
    private String id;
    private String goodsname;
    private double price;
    private int count;

    public Goods() {
    }

    public Goods(String id, String goodsname, double price, int count) {
        this.id = id;
        this.goodsname = goodsname;
        this.price = price;
        this.count = count;
    }

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

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

    /**
     * 获取
     * @return goodsname
     */
    public String getGoodsname() {
        return goodsname;
    }

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

    /**
     * 获取
     * @return price
     */
    public double getPrice() {
        return price;
    }

    /**
     * 设置
     * @param price
     */
    public void setPrice(double price) {
        this.price = price;
    }

    /**
     * 获取
     * @return count
     */
    public int getCount() {
        return count;
    }

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


}

GoodsTest

package com.itheima.demo3;

public class GoodsTest {
    public static void main(String[] args) {
        //定义数组
        Goods []arr=new Goods[3];
        //三个商品对象
        Goods g1 = new Goods("001","华为P40",5999.0,100);
        Goods g2 = new Goods("002","保温杯",227.0,50);
        Goods g3 = new Goods("003","枸杞",12.7,70);
        //把对象存入数组中
        arr[0]=g1;
        arr[1]=g2;
        arr[2]=g3;
        //遍历数组
        for(int i=0;i<arr.length;i++){
            System.out.println(arr[i].getId()+","+arr[i].getGoodsname()+","
            +arr[i].getPrice()+","+arr[i].getCount());
        }



    }
}

Car

package com.itheima.demo4;

public class Car {
    private String brand;
    private double price;
    private String color;

    public Car() {
    }

    public Car(String brand, double price, String color) {
        this.brand = brand;
        this.price = price;
        this.color = color;
    }

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

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

    /**
     * 获取
     * @return price
     */
    public double getPrice() {
        return price;
    }

    /**
     * 设置
     * @param price
     */
    public void setPrice(double price) {
        this.price = price;
    }

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

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


}

CarTest

package com.itheima.demo4;

import java.util.Scanner;

public class CarTest {
    public static void main(String[] args) {
        //创建存储3个对象的数组
        Car[] arr=new Car[3];
        //通过键盘录入获取数据
        for(int i=0;i<arr.length;i++){
            //new一个空对象;
            Car c=new Car();
            Scanner sc=new Scanner(System.in);
            System.out.println("请输入汽车的品牌:");
            String brand=sc.next();
            c.setBrand(brand);
            System.out.println("请输入汽车的价格:");
            double price=sc.nextInt();
            c.setPrice(price);
            System.out.println("请输入汽车的颜色:");
            String color=sc.next();
            c.setColor(color);
            arr[i]=c;

        }
        //遍历数组
        for(int i=0;i<arr.length;i++){
            System.out.println(arr[i].getBrand()+","+arr[i].getPrice()+","+arr[i].getColor());

        }
    }
}

Phone

package com.itheima.demo4;

public class Phone {
    private String brand;
    private double price;
    private String color;

    public Phone() {
    }

    public Phone(String brand, double price, String color) {
        this.brand = brand;
        this.price = price;
        this.color = color;
    }

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

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

    /**
     * 获取
     * @return price
     */
    public double getPrice() {
        return price;
    }

    /**
     * 设置
     * @param price
     */
    public void setPrice(double price) {
        this.price = price;
    }

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

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


}

PhoneTest

package com.itheima.demo4;

public class PhoneTest {
    public static void main(String[] args) {
        //数组
        Phone []arr=new Phone[3];
        //三个手机对象
        Phone p1=new Phone("华为",2300,"蓝色");
        Phone p2=new Phone("苹果",8300,"白色");
        Phone p3=new Phone("小米",3300,"黑色");
        //存入数组中
        arr[0]=p1;
        arr[1]=p2;
        arr[2]=p3;
        //遍历数组
        double sum=0;
        for(int i=0;i<arr.length;i++){
            Phone p=arr[i];
            sum=sum+p.getPrice();
        }
        double avg=sum/arr.length;
        System.out.println("三部手机的平均价格为:"+avg);


    }
}

GirlFriend

package com.itheima.demo4;

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

    public GirlFriend() {
    }

    public GirlFriend(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;
    }


}

GirlFriendTest

package com.itheima.demo4;

public class GirlFriendTest {
    public static void main(String[] args) {
        //创建数组
        GirlFriend []arr=new GirlFriend[4];
        //创建四个对象
        GirlFriend g1=new GirlFriend("谈若",20,"女","听音乐");
        GirlFriend g2=new GirlFriend("刘芳",18,"女","跳舞");
        GirlFriend g3=new GirlFriend("李心",22,"女","唱歌");
        GirlFriend g4=new GirlFriend("罗田",19,"女","弹琴");
        //存入数组中
        arr[0]=g1;
        arr[1]=g2;
        arr[2]=g3;
        arr[3]=g4;
        //计算平均年龄
        double sum=0;
        for(int i=0;i<arr.length;i++){
            GirlFriend g=arr[i];
            sum=sum+g.getAge();

        }
        double avg=sum/arr.length;
        System.out.println("平均年龄为:"+avg);
        int count=0;
        //统计年龄比平均值低的女朋友的数量和所对应的信息
        for(int i=0;i<arr.length;i++){
            GirlFriend g=arr[i];
            if(arr[i].getAge()<avg){
                count++;
                System.out.println(arr[i].getName()+","+arr[i].getAge()+","+arr[i].getGender()+","+arr[i].getHobby());
            }
        }
        System.out.println("年龄比平均值低的女朋友有"+count+"个");
    }
}

③复杂对象数组练习--添加和遍历

要求1和要求2:

Student

package com.itheima.demo4;

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;
    }


}

Test

package com.itheima.demo4;

public class Test {
    public static void main(String[] args) {
        //1.创建一个长度为3的数组
        Student []arr=new Student[3];


        //2.创建学生对象
        Student s1=new Student(1,"李明",20);
        Student s2=new Student(2,"王五",21);


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



        //4.再次创建一个学生对象
        Student s4=new Student(4,"张三",19);


        //唯一性判断
        boolean flag=contain(arr,s4.getId());
         int count=getCount(arr);
      ;
        if(flag==true){
            //5.1 已存在 --- 提示重复
            System.out.println("ID重复,请重新输入一个学生数据");
        }else{
            //5.2 不存在 --- 添加学生对象
            //6.添加学生对象
            //判断老数组是否存满
            if(count==arr.length){
                //6.1 老数组已经存满
                //创建新数组
                Student[] newarr=newArray(arr);
                //添加对象到新数组中
                newarr[count]=s4;
                //遍历数组
                printArray(newarr);

            }else{
                //6.2 老数组没有存满
                arr[count]=s4;
                //遍历数组
                printArray(arr);
            }

            }




        }
        //遍历数组
    public static void printArray(Student[] arr){
        for(int i=0;i<arr.length;i++){
            System.out.println("学号:"+arr[i].getId()+",姓名:"+arr[i].getName()+",年龄:"+arr[i].getAge());
        }
    }

        //创建新数组
    public static Student[] newArray(Student[] arr){
        //新数组在老数组长度的基础上+1
        Student [] newarray=new Student[arr.length+1];
        //把老数组的内容添加到新数组中
        for(int i=0;i<newarray.length;i++){
            newarray[i]=arr[i];
        }
        //返回新数组
        return newarray;
    }

   //获取老数组中的元素数量
    public static int getCount(Student[] arr) {
        int count=0;
        for (int i = 0; i < arr.length; i++) {
            if(arr[i]!=null){
                count++;
            }

        }
        return count;
    }
    //唯一性判断
    public static  boolean contain(Student[] arr,int id){
        for(int i=0;i<arr.length;i++){
            Student stu=arr[i];
            if(stu!=null){
                int sid=stu.getId();
                if(sid==id){
                    return true;
                }
            }

        }
        return false;

    }
}









④ 复杂对象数组练习--删除和修改

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

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

package com.itheima.demo4;

public class Test2 {
    public static void main(String[] args) {

        //1.创建一个数组用来存储学生对象
        Student[] arr = new Student[3];
        //2.创建学生对象并添加到数组当中
        Student stu1 = new Student(1, "zhangsan", 23);
        Student stu2 = new Student(2, "lisi", 24);
        Student stu3 = new Student(3, "wangwu", 25);

        //3.把学生对象添加到数组当中
        arr[0] = stu1;
        arr[1] = stu2;
        arr[2] = stu3;

        //通过id删除学生信息
        //查询id是否存在
        int index=getId(arr,2);
        if(index>=0){
            //存在,删除
            arr[index]=null;
            printArr(arr);
        }else{
            //不存在,提示删除失败
            System.out.println("id不存在,删除失败");
        }

    }

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

    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());
            }
        }
    }

}

要求5:查询数组id为“2”的学生,如果存在,则将他的年龄+1岁,然后遍历所有学生信息

package com.itheima.demo4;

public class Test3 {
    public static void main(String[] args) {
        //1.创建一个数组用来存储学生对象
        Student[] arr = new Student[3];
        //2.创建学生对象并添加到数组当中
        Student stu1 = new Student(1, "zhangsan", 23);
        Student stu2 = new Student(2, "lisi", 24);
        Student stu3 = new Student(3, "wangwu", 25);

        //3.把学生对象添加到数组当中
        arr[0] = stu1;
        arr[1] = stu2;
        arr[2] = stu3;
        //查询id为2的学生
        int index=getIndex(arr,stu2.getId());
        if(index>=0){
            //存在,年龄+1
            Student stu=arr[index];
            //获取年龄
            int age=stu.getAge()+1;
            //重新设置年龄
            stu.setAge(age);
            //遍历数组
            printArr(arr);

        }else{
            //不存在,提示信息
            System.out.println("不存在id为:"+stu2.getId()+"的学生信息");
        }
    }
    public static int getIndex(Student[] arr,int id){
        for(int i=0;i<arr.length;i++){
            Student stu=arr[i];
            if(stu!=null){
                if(stu.getId()==id){
                    return i;
                }
            }
        }
        return -1;
    }
    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());
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值