一、创建异常
1、空指针异常
2、超出索引范围
二、遍历
for循环
三、求数组中的最大值
package cn.wt.day05.demon02; public class DemonArray03 { public static void main(String[] args) { int[] array = {10, 2, 3, 7, 9, 8, 3, 4, 20}; int max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max){ max = array[i]; } } System.out.println(max); } }
四、反转数组的数据
1、方法一,通过另一个数组
package cn.wt.day05.demon02; public class DemonArray04 { public static void main(String[] args) { int[] arr1 = {2, 1, 5, 3}; int[] arr2 = new int[arr1.length]; for (int i = 0; i < arr1.length; i++) { arr2[arr1.length-1-i] = arr1[i]; } for (int i = 0; i < arr2.length; i++) { System.out.println(arr2[i]); } } }
2、方法二,通过中间值
package cn.wt.day05.demon02; public class DemonArray05 { public static void main(String[] args) { int[] arr = {2, 4, 1, 8, 5, 0}; int temp; for (int i = 0; i < (int)arr.length/2; i++) { temp = arr[i]; arr[i] = arr[arr.length-1-i]; arr[arr.length-1-i] = temp; } for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } }
五、数组作为 方法参数
package cn.wt.day05.demon02; public class DemonArray06 { public static void main(String[] args) { int[] array = {1, 5, 2, 7, 3, 5, 0}; printArray(array); } public static void printArray(int[] arr){ for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } }
注意:python中有默认参数陷阱
六、数组 作为返回值
python 通过 tuple 直接返回
package cn.wt.day05.demon02; public class DemonArray07 { public static void main(String[] args) { int[] result = isCal(10, 20); System.out.println(result[1]); } public static int[] isCal(int a, int b){ int isSum = a + b; int isMax = a > b ? a:b; int isAvg = (a+b)/2; int[] total = {isSum, isMax, isAvg}; return total; } }
总结:
1、数据类型相同,运行过程中长度不可改变
2、参数、返回值 都是内存地址
3、异常:空指针、超出索引范围
4、遍历,最值,反转