본문 바로가기
Coding Note/Java

Java 3-4) continue문 / for, while문에서 사용해보기

by 푸린이 2021. 12. 10.

continue : skip (생략)

- loop문과 같이 사용

 

// 형식

while (조건문) {

     처리1

     처리2

     if (조건) {

          continue;

     }

     처리3

}

  → if문의 조건이 true면 처리3은 생략 → 다시 위로 올라감

 

// for문에서 continue 사용하기

for(int i = 0; i < 10; i++) {
	System.out.println("i = " + i);

	System.out.println("for start");

	if(i > 3 || i < 1) {
		System.out.println();
		continue;		// continue문 뒤부터는 다 생략
	}

	System.out.println("for end");
	System.out.println();
}

- i가 0, 4, 5, 6, 7, 8, 9인 경우 if 조건이 true기 때문에 continue 작동됨(뒷부분 생략되고 다시 앞으로) → "for end"는 출력되지 않는다.

- System.out.println(); 는 가독성을 위해 넣어봤다.

 

// while문에서 continue 사용시 무한루프

int w = 0;
while(w < 10) {
	System.out.println("w = " + w);

	System.out.println("while start");

	if (w > 3) {
		continue;
	}

	System.out.println("while end");
	w++;
}

- if문의 조건에 해당될 때부터(w = 4) 뒷부분 생략

- if문 뒤쪽 증감식 w++가 생략되기 때문에 while의 조건 (4 < 10)에 계속 해당

- w = 4

  while start 출력 무한루프됨

댓글