提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、数组遍历
将数组中的每个元素分别获取出来,就是遍历。遍历也是数组操作中的基石,本阶段需要熟练掌握。
public class ArrayTest01 {
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 class ArrayTest01 {
public static void main(String[] args) {
//定义数组
int[] arr = {11, 22, 33, 44, 55};
//使用通用的遍历格式
for(int x=0; x<arr.length; x++) {
System.out.println(arr[x]);
}
}
}
二、数组最值
最大值获取:从数组的所有元素中找出最大值。
实现思路:
定义变量,保存数组0索引上的元素
遍历数组,获取出数组中的每个元素
将遍历到的元素和保存数组0索引上值的变量进行比较
如果数组元素的值大于了变量的值,变量记录住新的值
数组循环遍历结束,变量保存的就是数组中的最大值
代码实现:
public class ArrayTest02 {
public static void main(String[] args) {
//定义数组
int[] arr = {12, 45, 98, 73, 60};
//定义一个变量,用于保存最大值
//取数组中第一个数据作为变量的初始值
int max = arr[0];
//与数组中剩余的数据逐个比对,每次比对将最大值保存到变量中
for(int x=1; x<arr.length; x++) {
if(arr[x] > max) {
max = arr[x];
}
}
//循环结束后打印变量的值
System.out.println("max:" + max);
}
}