网上有关于foreach用法的详细介绍,小白并看不懂,自己简单理解了一下遍历数组时候的用法:
package foreach;
public class foreach {
public static void main(String[] args) {
// TODO Auto-generated method stub
foreach exam = new foreach();
exam.test01();
exam.test02();
exam.test03();
}
public void test01(){
int arr1[]={1,2,3,4,5};
for(int x : arr1){
System.out.print(x+" "); //按顺序输出arr1数组的数值
}
System.out.println();
}
public void test02(){
int arr2[][]={{1,2},{3,4},{5,6},{6,7},{8,9}};
for (int y[] : arr2){
System.out.print(y[0]+" "); //相当于遍历5个一维数组的第一个数
}
System.out.println();
}
public void test03(){
int arr3[][]={{1,2},{3,4},{5,6},{6,7},{8,9}};
for (int y : arr3[0]){
System.out.print(y +" "); //只输出第一个数组数字
}
System.out.println();
}
}
结果为
1 2 3 4 5
1 3 5 6 8
1 2