for语句和for增强语句

 用for语句和for增强语句实现数组遍历

public class ForDemo {
        //遍历数组:for语句和增强for语句
	public static void main(String[] args) {
		int [] a={10,20,30,40,50};      //定义一个数组a
                
                //for语句
	        for(int i=0; i<a.length; i++){		//采用下标索引实现遍历
	            System.out.print(a[i]+" ");
	        }
	        System.out.println();

                //增强for语句
	        for(int x:a){
	            System.out.print(x+" ");	//增强的for语句,主要是对数组和集合进行迭代
	        }
	        System.out.println();

	        String [] names={"LiMing","Danny","Jenny","Lily"};
	        for(String s:names){	    //可以遍历任何类型的数组,这里遍历字符串数组
	            System.out.println(s+" ");
	        }

	}

}
发布了61 篇原创文章 · 获赞 61 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_42475914/article/details/100755052