1.遍历-普通for循环
int [] nums_1 = {1,2,3,4,5};
for (int i = 0; i < nums_1.length; i++) {
System.out.println(nums_1[i]);
}
// 执行结果
1
2
3
4
5
2.遍历-增强for循环
int[] nums_2 = {11,22,33,44,55};
for (int num : nums_2) {
System.out.println(num);
}
// 执行结果
11
22
33
44
55
3.数组作为方法的参数
// 数组作为方法的参数:定义一个方法
public static void printArray(int[] array){
if (array != null && array.length > 0){
for (int i : array) {
System.out.println(i);
}
}else{
System.out.println("当前数组为空");
}
}
// 下面是在main方法中调用上述方法
public static void main(String[] args) {
int[] nums_3 = {111,222,333,444,555};
printArray(nums_3);
}
//执行结果
111
222
333
444
555
4.数组作为方法的返回值
//数组作为返回值:定义了一个方法,
//该方法的作用是将数组进行反转
public static int[] reverseArray(int[] array){
int[] resArray = new int[1];
if (array!= null && array.length > 0){
// 下面是把数组进行反转一下
resArray = new int[array.length]; // 创建一个相同长度的数组
for (int i = 0,j = array.length-1; i < array.length; i++,j--) {
// 核心算法:输出的数组的下标 与 输入数组的正好相反
resArray[j] = array[i];
}
}
return resArray;
}
// 数组作为方法的参数:定义一个方法
public static void printArray(int[] array){
if (array != null && array.length > 0){
for (int i : array) {
System.out.println(i);
}
}else{
System.out.println("当前数组为空");
}
}
// 在main方法中 调用 数组作为返回值的方法,并调用数组作为参数的方法
public static void main(String[] args) {
//数组作为返回值
int[] nums_4 = {100,200,300,400,500,600};
int[] reverseNum = reverseArray(nums_4);
printArray(reverseNum);
}
//执行结果
600
500
400
300
200
100
5.完成
Congratulations!
You are one step closer to succes!