如何实现一维和二维数组的遍历?

可使用for语句遍历数组元素,下面提供两种实现方式,一种是原有for循环,另一种是从JDK 5.0 开始提供的新式for 循环。
□ 原有for循环
String[] arr ={“tom”,“rose”,“sunny”};
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
□ 新式for循环
String[] arr ={“tom”,“rose”,“sunny”};
for(String s:arr){
System.out.println(s);
}
二维数组的遍历需要使用双重循环,具体代码如下:
String[][] arr ={{“tom”,“American”},
{“jack”,“England”},
{“张三”,“china”}};
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr[i].length;j++){
System.out.print(arr[i][j]);
}
//打印一个元素后,换一行
System.out.println();
}

猜你喜欢

转载自blog.csdn.net/weixin_42470710/article/details/85880147
今日推荐