CodeGym/Java Blog/무작위의/Java의 중단 및 계속 문
John Squirrels
레벨 41
San Francisco

Java의 중단 및 계속 문

무작위의 그룹에 게시되었습니다
회원

자바 브레이크

Java에서 Break 문은 주로 다음 두 가지 경우에 사용됩니다.
  1. Break는 루프를 종료하고 루프 밖으로 점프합니다(for 및 while 모두).
  2. 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 문은 일반적으로 다음과 같은 경우에 사용됩니다.
  1. 다음 명령문을 건너뛰고 for 루프의 다음 반복으로 이동합니다.
  2. 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

결론

그것은 Java에서 중단 대 계속의 간단한 구현이었습니다. 위의 예를 통해 언제 무엇을 사용해야 하는지 이해할 수 있기를 바랍니다. 더 나은 학습을 위해 연습하는 것이 좋습니다. 또한 피드백이나 질문이 있으면 계속 알려주세요. 다음 시간까지 계속 배우고 계속 성장하십시오.
코멘트
  • 인기
  • 신규
  • 이전
코멘트를 남기려면 로그인 해야 합니다
이 페이지에는 아직 코멘트가 없습니다