📋 반복문(while, do while, for, continue, break, for each)
✅ while
- 반복 횟수가 정해져 있지 않고 조건식이 true일 경우 반복.
package section05;
public class Ex0501 {
public static void main(String[] args) {
// 주의: DEBUG CONSOLE에서 실행하지 마시오!
int count = 0;
while (true) {
System.out.printf("무한 루프(Infinite loop) - %d\\n", ++count);
}
}
}
package section05;
public class Ex0502 {
public static void main(String[] args) {
// 1~10 출력
// 1 2 3 4 5 6 7 8 9 10
int number = 1;
while (number <= 10) {
System.out.printf("%d ", number);
number++;
}
}
}
package section05;
public class Ex0503 {
public static void main(String[] args) {
// 1~10 짝수 출력
// 2 4 6 8 10
int number = 1;
while (number <= 10) {
if (number % 2 == 0) {
System.out.printf("%d ", number);
}
number++;
}
}
}
package section05;
public class Ex0504 {
public static void main(String[] args) {
// Ex0503을 continue문으로 refactoring
int number = 0;
while (number < 10) {
number++;
if (number % 2 != 0) {
continue;
}
System.out.printf("%d ", number);
}
}
}
package section05;
public class Ex0505 {
public static void main(String[] args) {
// Ex0504를 break문으로 refactoring
int number = 0;
while (true) {
number++;
if (number % 2 != 0) {
continue;
}
System.out.printf("%d ", number);
if (number >= 10) {
break;
}
}
}
}
package section05;
public class Jump0501 {
public static void main(String[] args) {
int treeHit = 0;
while (treeHit < 10) {
treeHit++;
System.out.println("나무를 " + treeHit + "번 찍었습니다.");
if (treeHit == 10) {
System.out.println("나무가 넘어갑니다.");
}
}
}
}
package section05;
public class Jump0502 {
public static void main(String[] args) {
int coffee = 10;
int money = 300;
// 조건식에 비교, 관계 연산자 함께 사용 가능
while (money > 0 && coffee > 0) {
System.out.println("돈을 받았으니 커피를 줍니다.");
coffee--;
System.out.println("남은 커피의 양은 " + coffee + "입니다.");
if (coffee == 0) {
System.out.println("커피가 다 떨어졌습니다. 판매를 중지합니다.");
}
}
}
}
package section05;
public class Jump0503 {
public static void main(String[] args) {
int coffee = 10;
int money = 300;
// Jump0502를 break문으로 refactoring
while (money > 0) {
System.out.println("돈을 받았으니 커피를 줍니다.");
coffee--;
System.out.println("남은 커피의 양은 " + coffee + "입니다.");
if (coffee == 0) {
System.out.println("커피가 다 떨어졌습니다. 판매를 중지합니다.");
break;
}
}
}
}
✅ for
package section05;
public class Ex0506 {
public static void main(String[] args) {
// Ex0502를 for문으로 refactoring
for (int i = 1; i <= 10; i++) {
System.out.printf("%d ", i);
}
}
}
package section05;
public class Ex0507 {
public static void main(String[] args) {
// Ex0503을 for문으로 refactoring
// 1~10 짝수 출력
// 2 4 6 8 10
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
System.out.printf("%d ", i);
}
}
}
}
package section05;
public class Ex0508 {
public static void main(String[] args) {
// Ex0504를 for문으로 refactoring
// 2 4 6 8 10
for (int i = 1; i <= 10; i++) {
if (i % 2 != 0) {
continue;
}
System.out.printf("%d ", i);
}
}
}