public class ArrayDemo03 { public static void main(String[] args) { int[] arrays = {1,2,3,4,5}; //打印全部的数组元素 for (int i = 0; i < arrays.length; i++) { System.out.println(arrays[i]); } System.out.println("-------------"); //计算所有元素的总和 int sum = 0; for (int i = 0; i < arrays.length; i++) { sum = sum + arrays[i];//或 sum += arrays[i] } System.out.println("所有元素的总和为:"+ sum); System.out.println("-------------"); //查找最大元素 int max = arrays[0]; for (int i = 1; i < arrays.length; i++) { if (arrays[i] > max){ max = arrays[i]; } } System.out.println("最大元素为:"+ max); } }
public class ArrayDemo04 { public static void main(String[] args) { int[] arrays = {1, 2, 3, 4, 5}; //JDK1.5, 没有下标 for (int array : arrays) {//快捷方式添加:arrays.for——增强型for循环 System.out.println(array); } } }
public class ArrayDemo04 { public static void main(String[] args) { int[] arrays = {1, 2, 3, 4, 5}; //调用方法 printArray(arrays); } //打印数组元素 public static void printArray(int[] arrays){ for (int i = 0; i < arrays.length; i++) { System.out.print(arrays[i]+" "); } } }
public class ArraysDemo05 { public static void main(String[] args) { int[] arrays = {1,2,3,4,5,6}; int[] reverse = reverse(arrays); printArray(reverse); } //反转数组 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; } //打印数组元素 public static void printArray(int[] arrays){ for (int i = 0; i < arrays.length; i++) { System.out.print(arrays[i]+" "); } } }
凡是过往,皆为序章;数风流人物,还看今朝。——威廉·莎士比亚,戏剧家,《暴风雨》