在Java中,循环遍历数组主要有两种方法:
基于索引的循环(for 循环)
int[] array = {1, 2, 3, 4, 5};
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
基于元素的循环(foreach 循环)
int[] array = {1, 2, 3, 4, 5};
for (int element : array) {
System.out.println(element);
}
这两种方法都可以用来遍历数组,选择哪一种取决于你的具体需求。基于索引的循环可以让你访问数组的每个元素及其索引,而基于元素的循环则更简洁,直接遍历数组中的每个元素。