break
- switch 조건식과 반복문에서 사용
- 중첩 반복문에서는 자신이 포함된 가장 가까운 반복문을 빠져나가는 구문
continue
- 반복문 내에서만 사용 가능
- 특정 조건을 건너뛸 때 주로 사용
- 자신이 포함된 반복문의 끝으로 이동하여 다음 반복으로 넘어감
- for문의 경우 증감식으로 이동, while(do~while) 문은 조건식으로 이동
break문 예제1
- 사용자에게 문자열을 입력받고 문자열 길이 출력
- exit 입력 시 프로그램 종료
public void method1() {
String sInput = "";
Scanner s = new Scanner(System.in);
while(true) {
System.out.printf("Insert String: ");
sInput = s.nextLine();
if(sInput.equalsIgnoreCase("exit")) {
System.out.println("===Program EXIT===");
break;
}
System.out.printf("\"%s\" length is %d\n\n", sInput, sInput.length());
}
}
출력물
Insert String: Hello World!!
"Hello World!!" length is 13
Insert String: EXIT
===Program EXIT===
break문 예제2
- 1 ~ 임의의 값(1~10)까지의 합계를 반복문을 통해 출력
- 단, 랜덤 값이 5가 나오면 프로그램 종료
public void method2() {
int nRandom = 0;
int nSum = 0;
while(true) {
nSum = 0;
nRandom = ((int)(Math.random()*10)+1);
System.out.println("nRandom: " + nRandom);
if(nRandom == 5) {
System.out.println("Program EXIT");
break;
}
for(int i = 1; i <= nRandom; i++) {
nSum += i;
System.out.printf("i: %d, nSum: %d\n", i, nSum);
}
System.out.printf("Total: %d\n\n", nSum);
}
}
출력물
nRandom: 1
i: 1, nSum: 1
Total: 1
nRandom: 8
i: 1, nSum: 1
i: 2, nSum: 3
i: 3, nSum: 6
i: 4, nSum: 10
i: 5, nSum: 15
i: 6, nSum: 21
i: 7, nSum: 28
i: 8, nSum: 36
Total: 36
nRandom: 3
i: 1, nSum: 1
i: 2, nSum: 3
i: 3, nSum: 6
Total: 6
nRandom: 4
i: 1, nSum: 1
i: 2, nSum: 3
i: 3, nSum: 6
i: 4, nSum: 10
Total: 10
nRandom: 5
Program EXIT
countinue 문 예제1
- 1 ~ 100까지의 정수들의 합 출력
- 단, 5의 배수는 제외한 덧셈 연산
public void method1() {
int nSum = 0;
for(int i = 1; i <= 100; i++) {
if(i % 5 == 0) continue;
nSum += i;
}
System.out.println("Total: " + nSum);
}
출력물
Total: 4000
countinue 문 예제2
- 2 ~ 9단까지의 구구단 가로로 출력
- 단, 홀수단은 제외하고 출력
public void method2() {
int nTimes = 2;
int nNum = 0;
for(nNum = 0; nNum <= 9; nNum++) {
for(nTimes = 2; nTimes <= 9; nTimes++) {
if(nTimes % 2 != 0) continue;
if(nNum == 0) System.out.printf("[ %d Times ]\t", nTimes);
else System.out.printf("%d * %d = %2d\t", nTimes, nNum, (nTimes * nNum));
}
System.out.println();
}
}
출력물
[ 2 Times ] [ 4 Times ] [ 6 Times ] [ 8 Times ]
2 * 1 = 2 4 * 1 = 4 6 * 1 = 6 8 * 1 = 8
2 * 2 = 4 4 * 2 = 8 6 * 2 = 12 8 * 2 = 16
2 * 3 = 6 4 * 3 = 12 6 * 3 = 18 8 * 3 = 24
2 * 4 = 8 4 * 4 = 16 6 * 4 = 24 8 * 4 = 32
2 * 5 = 10 4 * 5 = 20 6 * 5 = 30 8 * 5 = 40
2 * 6 = 12 4 * 6 = 24 6 * 6 = 36 8 * 6 = 48
2 * 7 = 14 4 * 7 = 28 6 * 7 = 42 8 * 7 = 56
2 * 8 = 16 4 * 8 = 32 6 * 8 = 48 8 * 8 = 64
2 * 9 = 18 4 * 9 = 36 6 * 9 = 54 8 * 9 = 72
'Developer TABLE > Java' 카테고리의 다른 글
배열(Array) (0) | 2021.08.27 |
---|---|
난수 생성 Math.random (0) | 2021.08.26 |
반복문 do ~ while (0) | 2021.08.26 |