자바 브레이크
Java에서 Break 문은 주로 다음 두 가지 경우에 사용됩니다.- Break는 루프를 종료하고 루프 밖으로 점프합니다(for 및 while 모두).
- Break 문은 switch 문에서 case를 종료합니다.
통사론
break;
예
public class Driver1 {
public static void main(String[] args) {
// Testing break statement in while loop
System.out.println("Test Break statement in While loop");
int i = 0;
while (i < 5) {
if (i == 2) {
break;
}
System.out.println(i++);
}
}
}
산출
While 루프 0 1의 Test Break 문
자바 계속
Java의 continue 문은 일반적으로 다음과 같은 경우에 사용됩니다.- 다음 명령문을 건너뛰고 for 루프의 다음 반복으로 이동합니다.
- while 루프에서 계속해서 다음 문을 건너뛰고 조건문으로 건너뜁니다.
통사론
continue;
예
public class Driver2 {
public static void main(String[] args) {
// Testing continue statement in while loop
System.out.println("Test Continue in While loop");
int i = 0;
while (i < 5) {
if (i == 2) {
i++;
continue;
}
System.out.println(i++);
}
}
}
산출
While 루프에서 테스트 계속 0 1 3 4
계속과 중단의 차이점
중단과 계속의 중요한 차이점은 중단이 한 번에 루프를 종료한다는 것입니다. break 문이 실행되면 루프는 다시 실행되지 않습니다. 그러나 continue 문을 실행한 후에는 현재 반복에 대해서만 다음 코드 줄을 건너뜁니다. 루프가 다시 실행되기 시작합니다.While 루프에서 끊고 계속하기
Break 및 Continue는 둘 다 while 루프 에서 사용할 수 있습니다 . 명확한 이해를 위해 아래 예를 살펴보겠습니다.예
public class Driver {
public static void main(String[] args) {
// Testing both break and continue statements side by side
String [] weekdays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
System.out.println("Test Break statement in While loop");
System.out.println("\nWorking Days:\n");
int i = 0;
while (i < weekdays.length ) {
if (weekdays[i].equals("Saturday") || weekdays[i].equals("Sunday")) {
i++;
break;
// Not any working day will be printed
// because the loop breaks on Sunday
// once the loop breaks it moves out of the loop
}
System.out.println(weekdays[i++]);
}
System.out.println("\nTest Continue statement in While loop");
System.out.println("\nWorking Days:\n");
int j = 0;
while (j < weekdays.length ) {
if (weekdays[i].equals("Saturday") || weekdays[i].equals("Sunday")) {
j++;
continue;
// All the working/business days will be printed
// when the loop encounters Saturday or Sunday
// it skips that iteration and continues to the next iteration
}
System.out.println(weekdays[i++]);
}
// A test case for continue statement using for loop
System.out.println("\nTest Continue in For loop");
for (int x = 0; x < 5; x++) {
if (x == 2)
continue;
System.out.println(x);
}
}
}
산출
While 루프의 테스트 Break 문 근무일: While 루프의 테스트 Continue 문 근무일: 월요일 화요일 수요일 목요일 금요일 For 루프의 테스트 계속 0 1 3 4