JAVA之动态数组(实例说明)
今天介绍一下动态数组,通过几个案例加深理解。
1. 格式:数组类型[ ] 数组名 = new int[数组大小];
int[] arr1 = new int[20];
2.应用场景:数组里的值不知道,只知道数组的长度。
【注】若未对数组进行赋值,使用的是默认值。
1. int 默认:0 2. double 默认:0.0 3. boolean 默认:false 4. char 默认:u0000 -> 空格 5. 引用类型 默认:null */
例如:arr1数组未赋值且数组类型是int型,输出默认值0。
System.out.println(arr1[0]); //0
3.数组常见问题
越界 : arr1的索引是0-19,arr[20]不存在
System.out.println(arr1[20]);
报错:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
4.练习
4.1 练习1:求最值
int[] arr2 = {2, 33, 53, 26, 78}; int max = arr2[0]; for (int i = 1; i < arr2.length; i++) { //i从1开始而不是从0开始?因为不用和自己比 if (arr2[i] > max) { max = arr2[i]; } } System.out.println("arr2数组的最大值是:" + max);
4.2 练习2:
生成10个1~100之间的随机数存入数组 1)求出所有数据之和 2)求出数据的平均数 3)统计有多少个数据比平均值小
int[] arr3 = new int[10]; //使用动态数组 int sum = 0; //求和 Random r = new Random(); for (int i = 0; i < arr3.length; i++) { arr3[i] = r.nextInt(100) + 1; //r.nextInt(100)表示0~99,所以要+1 sum += arr3[i]; System.out.print(arr3[i] + " "); } //求平均数 int num = 0; //用以统计比平均数小的数的个数 int ave = sum / arr3.length; for (int i = 0; i < arr3.length; i++) { if (arr3[i] < ave) { num++; } } System.out.println(" 所有数据的和" + sum); System.out.println("平均数:" + ave); System.out.println("比平均数小的数的个数:" + num);
【注】r.nextInt(100)表示0~99,所以要+1。
4.3 练习3:
定义一个数组,存入1,2,3,4,5,按要求交换索引对应的元素 交换前:1,3,5,7,9 交换后:9,7,5,3,1 把首位两个数字调换以一下
int[] arr4 = {1, 2, 3, 4, 5}; for (int i = 0, j = arr4.length - 1; i < j; i++, j--) { int temp = arr4[i]; arr4[i] = arr4[j]; arr4[j] = temp; } for (int i1 = 0; i1 < arr4.length; i1++) { System.out.print(arr4[i1] + " "); //5 4 3 2 1 } /*练习4:打乱数组*/ int[] arr5 = {1, 2, 3, 4, 5}; //生成随机索引 Random r1 = new Random(); for (int i = 0; i < arr5.length; i++) { int rand_index = r1.nextInt(arr5.length); //生成随机索引,范围是0、1、2、3、4。 nextInt(),左闭右开 int temp = arr5[i]; arr5[i] = arr5[rand_index]; arr5[rand_index] = temp; } for (int i = 0; i < arr5.length; i++) { System.out.print(arr5[i] + " "); } } }
【注】生成随机索引
Random r1 = new Random(); int rand_index = r1.nextInt(arr5.length); 说明:索引的范围就是数组的大小-1。 nextInt(arr5.length)刚好表示的就是0~数组的大小-1。
制作不易,请多多支持哦(u‿ฺu✿ฺ)