Day 4: 조건문
조건문은 프로그램의 흐름을 제어하는 핵심 문법입니다. 특정 조건에 따라 다른 코드를 실행할 수 있게 해줍니다. Java에서는 if-else와 switch 두 가지 조건문을 제공합니다.
if-else 문
가장 기본적인 조건 분기입니다. 조건식의 결과가 true일 때 해당 블록을 실행합니다.
public class IfElseExample {
public static void main(String[] args) {
int score = 85;
// 단순 if
if (score >= 60) {
System.out.println("합격입니다!");
}
// if-else
if (score >= 90) {
System.out.println("A학점");
} else {
System.out.println("A학점이 아닙니다");
}
// if-else if-else (다중 분기)
if (score >= 90) {
System.out.println("학점: A");
} else if (score >= 80) {
System.out.println("학점: B");
} else if (score >= 70) {
System.out.println("학점: C");
} else if (score >= 60) {
System.out.println("학점: D");
} else {
System.out.println("학점: F");
}
// 중첩 if (가능하면 early return으로 대체)
boolean isMember = true;
int purchaseAmount = 50000;
if (isMember) {
if (purchaseAmount >= 30000) {
System.out.println("회원 할인 + 무료 배송");
} else {
System.out.println("회원 할인만 적용");
}
}
}
}
논리 연산자를 활용한 조건 결합
복잡한 조건을 &&, ||, ! 연산자로 결합할 수 있습니다.
public class CombinedCondition {
public static void main(String[] args) {
int age = 25;
boolean hasLicense = true;
boolean isDrunk = false;
// AND 조건: 모든 조건을 만족해야 함
if (age >= 18 && hasLicense && !isDrunk) {
System.out.println("운전할 수 있습니다.");
}
// OR 조건: 하나만 만족해도 됨
String day = "토요일";
if (day.equals("토요일") || day.equals("일요일")) {
System.out.println("주말입니다! 쉬세요.");
}
// 범위 체크
int temperature = 24;
if (temperature >= 20 && temperature <= 28) {
System.out.println("쾌적한 온도입니다.");
}
// 삼항 연산자로 간결하게
String result = (age >= 18) ? "성인" : "미성년자";
System.out.println(result);
}
}
switch 문
하나의 변수 값에 따라 여러 분기를 처리할 때 if-else if보다 깔끔합니다.
public class SwitchExample {
public static void main(String[] args) {
// 전통적인 switch
int month = 4;
String monthName;
switch (month) {
case 1:
monthName = "1월";
break;
case 2:
monthName = "2월";
break;
case 3:
monthName = "3월";
break;
case 4:
monthName = "4월";
break;
default:
monthName = "기타";
break;
}
System.out.println("현재 월: " + monthName);
// 여러 값을 하나의 case로 묶기
switch (month) {
case 3: case 4: case 5:
System.out.println("봄입니다");
break;
case 6: case 7: case 8:
System.out.println("여름입니다");
break;
case 9: case 10: case 11:
System.out.println("가을입니다");
break;
case 12: case 1: case 2:
System.out.println("겨울입니다");
break;
}
}
}
향상된 switch 표현식 (Java 14+)
Java 14부터 도입된 화살표 구문은 break 없이 간결하게 작성할 수 있습니다.
public class EnhancedSwitch {
public static void main(String[] args) {
String grade = "B";
// 화살표 구문 switch 표현식
String comment = switch (grade) {
case "A" -> "탁월합니다!";
case "B" -> "잘했습니다!";
case "C" -> "보통입니다.";
case "D" -> "좀 더 노력하세요.";
case "F" -> "재수강이 필요합니다.";
default -> "유효하지 않은 학점입니다.";
};
System.out.println(comment);
// 여러 값 매칭
int day = 3;
String type = switch (day) {
case 1, 2, 3, 4, 5 -> "평일";
case 6, 7 -> "주말";
default -> "잘못된 요일";
};
System.out.println("오늘은 " + type + "입니다.");
// yield로 복잡한 로직 처리
int score = 85;
String result = switch (score / 10) {
case 10, 9 -> "A";
case 8 -> "B";
case 7 -> "C";
default -> {
if (score >= 60) {
yield "D";
} else {
yield "F";
}
}
};
System.out.println("학점: " + result);
}
}
오늘의 연습문제
-
BMI 판정기: 키(cm)와 몸무게(kg)를 변수에 저장하고 BMI를 계산한 뒤, 18.5 미만이면 “저체중”, 18.5
24.9이면 “정상”, 2529.9이면 “과체중”, 30 이상이면 “비만”으로 판정하는 프로그램을 작성하세요. (BMI = 몸무게 / (키m * 키m)) -
요일 판단기: 정수(1~7)를 switch 표현식으로 요일 이름으로 변환하고, 추가로 평일/주말 여부도 출력하는 프로그램을 작성하세요.
-
놀이공원 요금 계산: 나이와 우대 여부(boolean)에 따라 요금을 계산하세요. 3세 이하 무료, 4
12세 15000원, 1364세 30000원, 65세 이상 무료. 우대 대상이면 50% 할인을 적용하세요.