数组的扩容(Java)

import java.util.Scanner;

public class AddArray {
    public static void main(String[] args) {
        //创建扫描器对象
        Scanner sc = new Scanner(System.in);

        //创建整形数组并赋初值(静态赋值)
        int[] a = {1, 2, 3, 4, 5};
        
        while (true) {
            //创建新数组用来接受旧数组的数据并且添加新数据
            int[] b = new int[a.length + 1];

            //将原数组中的值一一赋值给新数组
            for (int i = 0; i < a.length; i++) {
                b[i] = a[i];
            }

            //输出原数组a
            System.out.println("原数组a->->->");
            for (int j = 0; j < a.length; j++) {
                System.out.print(a[j] + "\t");
            }

            //为新扩大的内存单元赋值
            System.out.println("\n输入一个数据放入新数组b中->->->");
            int addinteger = sc.nextInt();
            b[b.length - 1] = addinteger;//将插入的数据每次都放在最后一个位置
            //将数组b的地址赋值给数组a,得以让两者都指向同一个数组中的数据,
            // 进一步销毁a数组中的数据并且释放内存单元
            a = b;

            //输出新数组b
            System.out.println("\n改变后的新数组b->->->");
            for (int i = 0; i < b.length; i++) {
                System.out.print(b[i] + "\t");
            }

            //问用户是否继续添加
            System.out.println("\n是否继续添加(y/n)");
            char key = sc.next().charAt(0);//输入单个字符
            while (true) {
                if (key == 'n') {
                    //则终止运行
                    return;
                } else if (key != 'y') {
                    System.out.println("输入有误请重新输入->->->");
                    key = sc.next().charAt(0);
                } else {//输入y继续扩容
                    break;
                }
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_54702911/article/details/121569068