数组的遍历输出和求出数组中的最大值
数组遍历
数组遍历: 就是将数组中的每个元素分别获取出来,就是遍历。遍历也是数组操作中的基石。
public static void main(String[] args) { int[] arr = { 1, 2, 3, 4, 5 }; System.out.println(arr[0]); System.out.println(arr[1]); System.out.println(arr[2]); System.out.println(arr[3]); System.out.println(arr[4]); }
以上代码是可以将数组中每个元素全部遍历出来,但是如果数组元素非常多,这种写法肯定不行,因此我们需要改
造成循环的写法。数组的索引是 0 到 lenght-1 ,可以作为循环的条件出现
public static void main(String[] args) { int[] arr = { 1, 2, 3, 4, 5 }; for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } }
数组获取最大值元素
最大值获取:从数组的所有元素中找出最大值。
实现思路:
~定义变量,保存数组0索引上的元素
~遍历数组,获取出数组中的每个元素
~将遍历到的元素和保存数组0索引上值的变量进行比较
~如果数组元素的值大于了变量的值,变量记录住新的值
~数组循环遍历结束,变量保存的就是数组中的最大值

public static void main(String[] args) { int[] arr = { 5, 15, 2000, 10000, 100, 4000 }; //定义变量,保存数组中0索引的元素 int max = arr[0]; //遍历数组,取出每个元素 for (int i = 0; i < arr.length; i++) { //遍历到的元素和变量max比较 //如果数组元素大于max if (arr[i] > max) { //max记录住大值 max = arr[i]; } } System.out.println("数组最大值是: " + max); }