for 和 foreach循环使用

foreach语句是java5的新特征之一,在遍历数组、集合方面,foreach为开发人员提供了极大的方便。

foreach 语法格式如下:

for(元素类型t 元素变量x : 遍历对象obj){ 
     引用了x的java语句; 
} 

以下实例,展示了 foreach 的用法

public class Main {
    public static void main(String[] args) {
        int[] intary = { 1,2,3,4};
        foreachDisplay(intary);
    }
    public static void foreachDisplay(int[] data){
        System.out.println("使用 foreach 循环数组");
        for (int a  : data) {
            System.out.print(a+ " ");
        }
    }
}

输出结果:

使用 foreach 循环数组
1 2 3 4


猜你喜欢

转载自blog.csdn.net/qq_28043563/article/details/80572527