for (int x : arr) ;
System.out.println(x);
这两个语句合起来相当于
for(int x=0;x<arr.length;x++)
System.out.println(arr[x]);
输出结果是
1
2
3
4
5
7
作者: 黑马振鹏 时间: 2012-7-14 22:42
高级for循环,建议看张老师加强视频,讲解的非常透彻。作者: 彭超华 时间: 2012-7-14 23:02
class Xunhuan
{
public void xunhuan(int arr[])
{
for (int x : arr)
System.out.println(x);
}
}
class S1
{
public static void main(String[] args)
{
int arr[] = {1,2,3,4,5,7};
Xunhuan x = new Xunhuan();
x.xunhuan(arr);
}
}
这里for的作用是:遍历数组的的每个元素,每遍历一次,用变量X来接收,是For循环的增强。是Java.5.0的新特性,适合数组和集合遍历其中元素,不适合用于遍历基本数据。
格式为 for(元素类型 元素名:集合(或数组))
for (int x : arr)
System.out.println(x); 与下面的for循环效果相同
for(int x = 0, x<arr.length, x++){
System.out.println(x);
}
public static void main(String[] args)
{
int arr[] = {1,2,3,4,5,7};
Xunhuan x = new Xunhuan();
x.xunhuan(arr);
}
可以直接写为:
public static void main(String[] args)
{
int arr[] = {1,2,3,4,5,7};
for(int x : arr){
System.out.printlln(x);
}
}
作者: 尹善波 时间: 2012-7-14 23:54
class Xunhuan
{
public void xunhuan(int arr[])
{
for (int x : arr) // 高级for循环;格式:for(数据类型 变量名:被遍历的集合或数组){};
//在对数组进行遍历时和普通for循环相同,但在遍历集合时,只能获得元素
//而不能对集合进行操作;
System.out.println(x); //这两个语句合起来相当于;;for(int x=0;x<arr.length;x++)
// {System.out.println(arr[x]);}
}
}
class S1
{
public static void main(String[] args)
{
int arr[] = {1,2,3,4,5,7};
Xunhuan x = new Xunhuan();
x.xunhuan(arr);
}
}