Nested If - Else
Coddy Java 여정의 기초 섹션에 포함된 레슨 — 73개 중 32번째.
우리는 if-else if-else 문을 서로 중첩할 수 있습니다. 이를 통해 계층적 의사결정 구조를 만들 수 있습니다.
깊게 중첩된
if 문은 코드가 읽기 어렵고 유지보수하기 어렵게 만들 수 있다는 점을 유의하세요.예를 들어:
if (age > 18) {
if (hasLicense) {
System.out.println("You can drive");
} else {
System.out.println("Get a license first");
}
} else {
System.out.println("Too young to drive");
}
무한히 중첩할 수 있습니다:
if (condition1) {
if (condition2) {
if (condition3) {
// condition1, condition2 및 condition3이 모두 true일 때만 실행됩니다
...
}
}
}챌린지
초급롤러코스터를 탈 수 있는지 확인하는 프로그램을 만드세요. 요구사항은 다음과 같습니다:
- 최소 12세 이상이어야 합니다
- 150cm 이상 키가 커야 합니다
- 두 가지 요구사항을 모두 충족하지만 15세 미만인 경우, 성인 감독이 필요합니다
각 경우에 대해 정확히 다음 메시지를 출력하세요:
- 너무 어린 경우:
Sorry, you're too young - 키가 충분하지 않은 경우:
Sorry, you're not tall enough - 15세 미만이고 성인 없음:
Sorry, you need an adult with you - 15세 미만이지만 성인 동반:
You can ride with adult supervision! - 15세 이상이고 키 충분:
You can ride by yourself!
치트 시트
if-else if-else 문을 서로 중첩하여 계층적 의사결정 구조를 만들 수 있습니다:
if (age > 18) {
if (hasLicense) {
System.out.println("You can drive");
} else {
System.out.println("Get a license first");
}
} else {
System.out.println("Too young to drive");
}
중첩은 무한정으로 수행할 수 있습니다:
if (condition1) {
if (condition2) {
if (condition3) {
// if condition1, condition2 and condition3 are true
...
}
}
}참고: 깊게 중첩된 if 문은 코드를 읽고 유지보수하기 어렵게 만들 수 있습니다.
직접 해보기
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt(); // 이 줄을 변경하지 마세요
int height = scanner.nextInt(); // 이 줄을 변경하지 마세요
boolean hasAdult = scanner.nextBoolean(); // 이 줄을 변경하지 마세요
// 아래에 코드를 작성하세요
scanner.close();
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
기초의 모든 레슨
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else