Java实现数组中元素的增加(扩容)和减少

数组中元素的增加

//实现动态的给数组添加元素效果,实现对数组扩容
import java.util.Scanner;

public class ArrayDemo5 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] a = {1,2,3};
        do {
            int count = scanner.nextInt();//扩容个数

            int[] a1 = new int[a.length+count];


            for (int i = 0; i < a.length; i++) {
                a1[i] = a[i];
            }
            for (int i = 0; i < count; i++) {
                System.out.println("请输入数字");
                int num = scanner.nextInt();//扩容数字
                a1[a.length+i] = num;
            }
            a = a1;
            for (int i = 0; i < a.length; i++) {
                System.out.println(a[i]);
            }
            System.out.println("是否继续添加  y/n");
            char key = scanner.next().charAt(0);
            if (key == 'n') {
                break;
            }
        }while (true);
            System.out.println("你退出了");
        }
}

数组中元素的缩减:缩减最后一个

import java.util.Scanner;

//实现数组的缩减
public class ArrayDemo6 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] a = {1,2,3,4,5,6};
        do {
            int[] a1 = new int[a.length-1];
            for (int i = 0; i < a.length-1; i++) {
                a1[i] = a[i];
            }
            a = a1;
            System.out.println("==缩减后的a");
            for (int i = 0; i < a.length; i++) {
                System.out.println(a[i]);
            }
            System.out.println("是否要继续缩减  y/n");
            char key = scanner.next().charAt(0);
            if (key == 'n') {
                break;
            }
            if (a.length-1 == 0) {
                break;
            }
        }while (true);
        System.out.println("您退出了程序");
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值