1.用for循环遍历数组
public class text01 {
public static void main(String[] args) {
int[] arr = { 11, 24, 9, 16, 25 };
for (int i=0; i<arr.length; i++) {// for (int i = arr.length-1;i>=0;i--)倒序输出
int n = arr[i];
System.out.println(n);
}
}
}
输出
11
24
9
16
25
2.增强型for循环
for(元素类型 元素名称 : 遍历数组(集合)(或者能进行迭代的)){
语句
}
变量n直接拿到arr数组的元素
public class text02 {
public static void main(String[] args) {
int[] arr = { 11, 24, 9, 16, 25 };
for (int n : arr) {
System.out.println(n);
}
}
}
输出
11
24
9
16
25
在for (int n : arr)循环中,变量n直接拿到ns数组的元素,而不是索引。
增强型for循环更加简洁。但是,增强型for循环无法拿到数组的索引。
3.Arrays.toString(),快速打印数组
import java.util.Arrays;
public class text03 {
public static void main(String[] args) {
int[] arr = { 11, 24, 9, 16, 25 };
System.out.println(Arrays.toString(arr));
}
}