一.普通for循环
案例
package com.nie.array;
public class Demo03 {
public static void main(String[] args) {
//普通for循环
int[] arrays = {1,2,3,4,5};
for (int i = 0; i < arrays.length ; i++) {
System.out.println(arrays[i]);
}
}
}
运行结果
二.for-each循环
案例
//for-each循环即增强型for循环
for (int array : arrays) {//快捷输入:arrays.for
System.out.println(array);
}
运行结果:同一。与一区别:for循环可以操作里面的元素,增强for适合打印输出,取不到下标。
三.数组作方法入参
案例
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 Demo03 {
public static void main(String[] args) {
int[] arrays = {1,2,3,4,5};
int[] reverse = reverse(arrays);
printArray(reverse);
}
//打印数组元素
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; i < arrays.length ; i++) {
result[arrays.length-i-1] = arrays[i];
}
return result;
}
}
结果