Java continue 문은 루프의 현재 반복을 건너뛰기 위해 사용됩니다. Java에서 continue 문은 for
, while
, do-while
루프와 함께 사용할 수 있습니다.
Java continue 문
중첩된 루프에서 continue 문을 사용할 때, 이는 내부 루프의 현재 실행만을 건너뜁니다. Java continue 문은 레이블과 함께 사용하여 외부 루프의 현재 반복을 건너뛸 수도 있습니다. 몇 가지 continue java 문 예제를 살펴보겠습니다.
Java continue for loop
정수 배열이 주어지고 짝수만 처리하려는 경우, 여기서 continue 루프를 사용하여 홀수 처리를 건너뛸 수 있습니다.
package com.journaldev.java;
public class JavaContinueForLoop {
public static void main(String[] args) {
int[] intArray = { 1, 2, 3, 4, 5, 6, 7 };
// 짝수 항목만 처리하려고 함
for (int i : intArray) {
if (i % 2 != 0)
continue;
System.out.println("Processing entry " + i);
}
}
}
Java continue while loop
배열이 주어지고 인덱스 번호가 3으로 나누어 떨어지는 항목만 처리하려는 경우, 여기서 while 루프와 함께 java continue 문을 사용할 수 있습니다.
package com.journaldev.java;
public class JavaContinueWhileLoop {
public static void main(String[] args) {
int[] intArray = { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
int i = 0;
while (i < 10) {
if (i % 3 != 0) {
i++;
continue;
}
System.out.println("Processing Entry " + intArray[i]);
i++;
}
}
}
자바 continue do-while 루프
위의 while 루프 코드를 다음과 같이 do-while 루프로 쉽게 대체할 수 있습니다. continue 문의 결과와 효과는 위의 이미지와 동일합니다.
do {
if (i % 3 != 0) {
i++;
continue;
}
System.out.println("Processing Entry " + intArray[i]);
i++;
} while (i < 10);
자바 continue 레이블
외부 루프 처리를 건너뛰기 위한 자바 continue 레이블 예제를 살펴보겠습니다. 이 예제에서는 이차원 배열을 사용하고 모든 요소가 양수인 경우에만 요소를 처리합니다.
package com.journaldev.java;
import java.util.Arrays;
public class JavaContinueLabel {
public static void main(String[] args) {
int[][] intArr = { { 1, -2, 3 }, { 0, 3 }, { 1, 2, 5 }, { 9, 2, 5 } };
process: for (int i = 0; i < intArr.length; i++) {
boolean allPositive = true;
for (int j = 0; j < intArr[i].length; j++) {
if (intArr[i][j] < 0) {
allPositive = false;
continue process;
}
}
if (allPositive) {
// 배열 처리
System.out.println("Processing the array of all positive ints. " + Arrays.toString(intArr[i]));
}
allPositive = true;
}
}
}
자바 continue의 중요한 포인트
자바 continue 문에 대한 몇 가지 중요한 포인트는 다음과 같습니다;
- 간단한 경우에는 continue 문을 if-else 조건문으로 쉽게 대체할 수 있지만 여러 if-else 조건문이 있는 경우에는 continue 문을 사용하는 것이 코드를 더 읽기 쉽게 만듭니다.
- continue 문은 중첩된 루프와 특정 레코드를 처리하지 않고 건너뛸 때 유용합니다.
I have made a short video explaining java continue statement in detail, you should watch it below. https://www.youtube.com/watch?v=udqWkqhc2kw Reference: Oracle Documentation
Source:
https://www.digitalocean.com/community/tutorials/java-continue-statement