수업 시간에 배운 신기한 것,
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의 반복문과 유사한 부분이 많은 것 같다.
'Computer Science > 컴퓨터 프로그래밍' 카테고리의 다른 글
Java inheritance(상속) (0) | 2020.10.01 |
---|---|
Java Encapsulation (0) | 2020.10.01 |
Java OOP(Object Oriented Programming) (0) | 2020.10.01 |
JAVA/C++ 반복문 탈출(break, label) (0) | 2020.09.18 |
JAVA 입력 받는 법(print, printf, println) (0) | 2020.09.18 |