一、for循环遍历
通常遍历数组使用for循环来实现
遍历一维数组用一个for循环,遍历二维数组需要使用双层for循环,通过数组的length属性可获得数组的长度。
public class Wtf {
public static void main(String[] args) {
int[][]score={{4,5,3},{7,8,9},{12,19,30}};
for(int i=0;i<score.length;i++){
for(int j=0;j<3;j++){
System.out.print(score[i][j]+"\t");
}
System.out.println();
}
}
}
二、foreach语句遍历
使用foreach循环迭代数组元素时,并不能改变数组元素的值,因此不要对foreach的循环变量赋值。
主要针对二维数组举例说明
public class Wtf {
public static void main(String[] args) {
int[][]score={{4,5,3},{8,9},{12,19,30}};
for(int[] i:score){
for(int j:i){
System.out.print(j+"\t");
}
System.out.println();
}
}
}
三、.Arrays工具类中toString静态方法遍历
利用Arrays工具类中的toString静态方法可以将一维数组转化为集合形式并输出。
import java.util.Arrays;
public class Wtf {
public static void main(String[] args) {
int[]score={4,5,3};
System.out.println(Arrays.toString(score));
}
}