1부터 100까지 중 3의 배수이면 "Fizz", 5의 배수이면 "Buzz", 둘 다이면 "FizzBuzz", 아니면 숫자를 출력하되, 한 줄에 10개씩 공백으로 구분해 출력하세요. (힌트: % 와 삼항/if, i % 10 == 0에서 줄바꿈)
public class Exercise1 {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
String out;
if (i % 15 == 0) out = "FizzBuzz"; // 3과 5의 공배수 = 15의 배수. 먼저 검사!
else if (i % 3 == 0) out = "Fizz";
else if (i % 5 == 0) out = "Buzz";
else out = String.valueOf(i);
System.out.print(out + (i % 10 == 0 ? "\n" : " "));
}
// 출력: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz
// 출력: 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz
// ... (10줄)
}
}월(112)을 받아 switch 표현식으로 계절을 반환하는 메서드 5 봄, 6season(int month)를 작성하세요. 38 여름, 911 가을, 12·1·2 겨울, 그 외는 IllegalArgumentException을 던지세요.
public class Exercise2 {
static String season(int month) {
return switch (month) {
case 3, 4, 5 -> "봄";
case 6, 7, 8 -> "여름";
case 9, 10, 11 -> "가을";
case 12, 1, 2 -> "겨울";
default -> throw new IllegalArgumentException("잘못된 월: " + month);
};
}
public static void main(String[] args) {
System.out.println(season(4)); // 출력: 봄
System.out.println(season(12)); // 출력: 겨울
try {
season(13);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage()); // 출력: 잘못된 월: 13
}
}
}구구단을 2단부터 9단까지 출력하되, 각 단에서 결과가 30을 넘는 순간 그 단을 중단하고 다음 단으로 넘어가세요. 또한 결과가 홀수인 줄은 출력하지 마세요. (힌트: continue, break)
public class Exercise3 {
public static void main(String[] args) {
for (int dan = 2; dan <= 9; dan++) {
for (int i = 1; i <= 9; i++) {
int result = dan * i;
if (result > 30) break; // 안쪽 for만 탈출 → 다음 단
if (result % 2 != 0) continue; // 홀수 건너뜀
System.out.println(dan + " x " + i + " = " + result);
}
System.out.println("--- " + dan + "단 끝 ---");
}
// 출력: 2 x 1 = 2
// 출력: 2 x 2 = 4
// ... 2 x 9 = 18
// 출력: --- 2단 끝 ---
// 출력: 3 x 2 = 6
// ... (3단은 3x9=27까지, 짝수만)
// 출력: 9 x 2 = 18
// 출력: --- 9단 끝 --- (9x4=36 > 30 에서 중단)
}
}