1.普通的for循环
2.for-each循环
3.数组做方法入参
4.数组做返回值
package array; public class ArrayDemon03 { public static void main(String[] args) { int[] nums={1,2,3,4,5}; //打印全部的数组元素 for (int i = 0; i < nums.length ; i++) { System.out.println(nums[i]); } System.out.println("=========="); //计算所有元素的和 int sum=0; for (int i = 0; i <nums.length ; i++) { sum=sum+nums[i]; } System.out.println("sum="+sum); System.out.println("=========="); //查找最大元素 int max=nums[0]; for (int i = 1; i < nums.length; i++) { if(nums[i]>max){ max=nums[i]; } } System.out.println("max="+max); } }
package array; public class ArrayDemon05 { public static void main(String[] args) { int[] arrays={1,2,3,4,5}; //JDK1.5 没有下标 可用于打印数组 //快捷键: 数组名.for arrays.for 循环快捷按键: fori for (int array : arrays) { System.out.print(array+" "); } } }
package array; public class ArrayDemon04 { public static void main(String[] args) { int[] arrays = {1, 2, 3, 4, 5}; int[] reserve = reverse(arrays); printArray(reserve); } //打印数组元素 //数组做方法入参 public static void printArray(int[] arrays) { for (int i = 0; i < arrays.length; i++) { System.out.print(arrays[i] + " "); } } //反转数组 public static int[] reverse(int[] arrays) { //新造一个数组 int[] result = new int[arrays.length]; //反转操作 for (int i = 0, j = result.length - 1; i < arrays.length; i++, j--) { result[j] = arrays[i]; } //数组做返回值 return result; } }
2021-07-17