【Java学习笔记】数组的扩容和缩减

数组的扩容和缩减

一、扩容

Scanner input = new Scanner(System.in);
        int[] a = {1, 2, 3};

        // 使用 do....while 循环结构
        do{

            int[] b = new int[a.length+1];
            //先把a数组的内容拷贝到b数组中
            for( int i = 0; i < a.length; i++){
                b[i] = a[i];
            }
            System.out.println("请输入要添加的元素:");
            int add = input.nextInt();
            b[b.length-1] = add;

            //现在数组完成了扩容,但是是b数组,接下来让a指向扩容后的数组

            a = b;
            System.out.println("扩容后的数组如下:");
            for( int i = 0; i < a.length; i++){
                System.out.print(a[i]+ " ");
            }
            System.out.println("");
            //接下来判断是否继续
            System.out.println("是否还要继续添加元素?输入 y / n ");
            char judge = input.next().charAt(0);
            if('n' == judge){
                System.out.println("程序结束,不再继续添加元素,数组的最终状态如下:");
                for( int i = 0; i < a.length; i++){
                    System.out.print(a[i]+ " ");
                }
                break;
            }
        }while(true);

二、缩减

        Scanner input = new Scanner(System.in);
        int[] a = {1, 2, 3};
        int cnt;
        // 使用 do....while 循环结构
        do{

            System.out.println("是否还要继续缩减元素?输入 y / n ");
            char judge = input.next().charAt(0);
            if('n' == judge){
                System.out.println("停止缩减,最终数组状态如下:");
                for( int i = 0; i < a.length; i++){
                    System.out.print(a[i]+ " ");
                }
                break;
            }

            int[] b = new int[a.length-1];

            //先把a数组的内容拷贝到b数组中
            for( int i = 0; i < a.length-1; i++){
                b[i] = a[i];
            }

            //现在数组完成了缩减,但是是b数组,接下来让a指向缩减后的数组

            a = b;
            System.out.println("缩减后的数组如下:");
            for( int i = 0; i < a.length; i++){
                System.out.print(a[i]+ " ");
            }

            //缩减完之后记录数组的长度
            cnt = a.length;

            System.out.println("");

            if(cnt == 1){
                System.out.print("程序结束,数组剩下最后一个元素,不再缩减");
                break;
            }

        }while(true);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jackson凌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值