Chavo Kim 2020. 9. 18. 13:48

수업 시간에 배운 신기한 것,

 

JAVA for-Each Loop

 

c++의 iteration 변수를 선언하는 것과 비슷한 듯한데,

 

보통 배열을 전체 순회하고자 한다면, 아래와 같이 선언할 수 있다.

 

public class Practice {
    public static void main(String[] args){
        char[] test = new char[]{'a', 'b', 'c'};
        int[] test2 = new int[]{0, 1, 2, 3, 4};

        for(int i = 0; i < test.length; i++){
            System.out.print(test[i] + " ");
        }
        System.out.println();

        for(int i = 0; i < test2.length; i++){
            System.out.print(test2[i] + " ");
        }
        System.out.println();
    }

}

출력

a b c 
0 1 2 3 4 

 

For-each loop을 사용하면 아래와 같이 간단하게 선언 가능하다.

 

public class Practice {
    public static void main(String[] args){
        char[] test = new char[]{'a', 'b', 'c'};
        int[] test2 = new int[]{0, 1, 2, 3, 4};

        for(char i : test){
            System.out.print(i + " ");
        }
        System.out.println();

        for(int i : test2){
            System.out.print(i + " ");
        }
        System.out.println();
    }

}

출력

a b c 
0 1 2 3 4 

 

iteration을 선언할 때 해당 배열의 type을 선언해줘야한다는 것을 잊지말자!

 

python의 반복문과 유사한 부분이 많은 것 같다.