Theme. break문
반복문에서 break문은 자신이 포함된 가장 가까운 반복문을 벗어난다.
아래 코드를 살펴보자.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
package test;
public class MainClass {
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
System.out.println("for loop " + i);
if(i == 5) {
System.out.println("i == 5입니다.");
break; // for문을 벗어난다.
}
}
}
}
|
cs |
for문을 통해 i가 0부터 4까지 출력이 되다가,
i = 5일 때, if문의 조건식이 참이 되어 "i == 5입니다."라는 문장이 출력된다.
그 후, break문을 통해 for문을 벗어나게 된다.
< console >
break문을 활용한 코드를 살펴보자.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
package test;
public class MainClass {
public static void main(String[] args) {
int[] number = {13,45,27,-36,78}; // number 배열 생성
// number 배열에서 음수가 나오기 전까지만 출력해보자!
for ( int i = 0; i < number.length; i++) {
// 첫 번째 ~ 세 번째 요소는 양수이므로 그대로 출력된다.
if(number[i] < 0) { // 네 번째 요소인 -36은 음수이므로 if문의 조건식이 참이 된다.
break; // if의 조건식이 참이므로 break문을 통해 for문을 벗어난다.
}
System.out.println("number[" + i + "] = " + number[i]);
}
}
}
|
cs |
아래 코드는 반복문에서 break문은 자신이 포함된 가장 가까운 반복문을 벗어난다는 성질에 대해 이해할 수 있는 코드이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package test;
public class MainClass {
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
System.out.println("i = " + i);
for (int j = 0; j < 8; j++) {
System.out.println("\tj = " + j);
if(i == 5 && j == 4) { //i가 5일 때, j는 0부터 4까지만 출력된다.
break; // break문은 내부 for문만을 탈출한다.
} // 따라서, i가 6일 때도 계속 loop 돌아간다.
}
}
}
}
|
cs |
< console >
위의 코드에서 발생한 문제를 해결하고자 적절하게 break문을 사용하는 방법에 대해 알아보자.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
package test;
public class MainClass {
public static void main(String[] args) {
// break문을 설정하는 방법
// 1. loop문 수에 맞춰서 break를 설정한다.
boolean b = false; // 초기화(임의로 값 넣어놓음)
for(int i = 0; i < 10; i++) {
System.out.println("i = " + i);
for (int j = 0; j < 8; j++) {
System.out.println("\tj = " + j);
if(i == 5 && j == 4) {
b = true;
}
if(b == true) {
break; // 내부의 for문을 벗어남
}
}
if(b == true) {
break; // 외부의 for문을 벗어남
}
}
System.out.println();
// 2. 지정된 break 사용
loopout: for(int i = 0; i < 10; i++) { //임의로 for문에 loopout이라고 지정
System.out.println("i = " + i);
for (int j = 0; j < 8; j++) {
System.out.println("\tj = " + j);
if(i == 5 && j == 4) {
break loopout; // 지정된 loopout이라는 for문(외부)을 벗어남
} // 외부 for문을 벗어난 것은 전체 for문을 벗어난 것!
}
}
}
}
|
cs |
< console >
Theme. continue문
continue문은 반복문 내에서만 사용될 수 있으며, 반복이 진행되는 도중에 continue문을 만나면 반복문의 끝으로 이동하여 다음 반복으로 넘어간다. for문의 경우 증감식으로 이동하며, while문의 경우 조건식으로 이동한다.
즉, continue는 "skip(생략)"의 느낌을 통해 이해할 수 있다.
먼저, for문에서의 continue문을 살펴보자.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
package test;
public class MainClass {
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
System.out.println("i = " + i);
System.out.println("for 처리1");
if(i > 5) {
continue; // i가 6부터는 처리2가 안되고 처리1만 됨
}
System.out.println("for 처리2"); // continue문에 의해 생략되는 부분
}
}
}
|
cs |
i가 0부터 5일 때까지는 처리1, 처리2가 출력되지만, i가 6일 때부터는 continue문에 의해 처리 2는 생략되고, 처리1만 출력된다.
< console >
for문에서 continue문을 사용한 코드들을 더 살펴보자.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
package test;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
// 배열 중 양수만 출력하는 코드
int[] array = {2,-6,3,-4,5};
for(int i = 0; i < array.length; i++) {
if(array[i] <= 0 ) {
continue; // if의 조건식이 참이면, 아래 처리를 하지 않고, for문의 증감식으로 이동
}
System.out.println("array[" + i + "] = " + array[i]);
}
Scanner sc = new Scanner(System.in);
int number;
for(int i = 1; i < 4; i++) {
System.out.print("number " + i + "번째 = ");
number = sc.nextInt();
if(number <= 0) {
continue;
}
System.out.println("number: " + number); //continue문에 의해 생략될 수 있는 문장
}
}
}
|
cs |
이제 while문에서의 continue문을 살펴보자.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
package test;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
int number;
Scanner sc = new Scanner(System.in);
int w = 0;
while(w < 3) {
System.out.print("number " + (w+1) + "번째 = ");
number = sc.nextInt();
if(number <= 0) {
continue; //continue되면 아래 처리, 증감식 다 생략하고 조건식 부분으로 이동
} //w가 증가가 안되므로 양수를 입력하지 않으면 계속 반복해서 입력해야 함
// 즉, 양수를 입력해야 w가 증가하면서 넘어간다.
System.out.println("number: " + number);
w++;
}
}
}
|
cs |
w가 증가할 때마다 number를 입력받는데, 그 number가 0보다 작거나 같으면, continue문 아래의 처리해야할 문장, 증감식이 생략되게 된다. 그래서 아래 결과와 같이 -1을 넣으면 출력은 되지 않고, 반복해서 입력만 할 수 있는 결과만 출력되는 것이다.
< console >
while문을 이용하여 양수의 숫자 5개를 입력받고, 이를 배열에 저장해 출력하는 코드를 작성해보자.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
package test;
import java.util.Arrays;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 입력 받을 배열 준비
int[] numArr = new int[5];
// loop로 입력
int w = 0;
while(w < numArr.length) {
System.out.print((w+1) + "번째 수 = ");
int num = sc.nextInt();
// 제어(continue)
if(num <= 0) {
System.out.println("양수를 입력해 주십시오.");
continue;
}
numArr[w] = num;
w++;
}
//배열 출력
System.out.println(Arrays.toString(numArr));
}
}
|
cs |
< console >
'Java' 카테고리의 다른 글
예외(Exception) 처리 (0) | 2022.12.26 |
---|---|
함수 사용 (4) | 2022.12.26 |
반복문 - for, while, do - while (2) | 2022.12.22 |
조건문 - if, switch (0) | 2022.12.22 |
형변환 (0) | 2022.12.21 |