If - Else
Coddy Java 여정의 기초 섹션에 포함된 레슨 — 73개 중 28번째.
if는 조건이 충족되면 특정 코드를 실행할 수 있게 해주지만, 조건이 충족되지 않으면 다른 것을 실행하고 싶다면 어떻게 할까요?
이를 위해 else 문이 있습니다:
int age = 15;
String status = "None";
if (age >= 18) {
status = "Adult";
} else {
status = "Young";
}위의 예제에서, age는 18보다 작아서 else 코드로 들어가며, status는 "Young"을 저장합니다.
우리는 else if 문을 사용하여 이를 더 심오하게 만들 수도 있습니다:
int age = 68;
String status = "None";
if (age < 18) {
status = "Young";
} else if (age >= 18 && age <= 65) {
status = "Adult";
} else {
status = "Old";
}여기서 age가 18보다 작은지 확인합니다. 그렇지 않으면 다음 조건으로 진행하여 age가 18과 65 사이인지 확인합니다. 그 조건도 만족되지 않으면 status를 "Old"로 설정합니다.
우리는 원하는 만큼 많은 else if 문을 추가할 수 있습니다:
if (condition1) {
code;
} else if (condition2) {
code;
} else if (condition3) {
code;
}
...챌린지
초급입력으로 바람 속도를 나타내는 숫자를 받아 wind라는 변수에 저장하는 코드를 제공받았습니다.
참고: 다음 레슨에서 사용자 입력을 받는 방법을 배울 것입니다. 현재는 첫 번째 줄을 건드리지 마세요.
조건에 따라 status 변수를 초기화하는 것이 당신의 작업입니다:
wind가8보다 작으면"Calm",wind가8과31사이(8과 31 포함)일 때"Breeze".wind가32과63사이(32와 63 포함)일 때"Gale"- 그 외에는
"Storm"
모든 입력과 예상 출력을 확인하려면 테스트 케이스를 확인하세요
치트 시트
else를 사용하여 if 조건이 만족되지 않을 때 코드를 실행하세요:
if (age >= 18) {
status = "Adult";
} else {
status = "Young";
}else if를 사용하여 여러 조건을 확인하세요:
if (age < 18) {
status = "Young";
} else if (age >= 18 && age <= 65) {
status = "Adult";
} else {
status = "Old";
}여러 else if 문을 연결할 수 있습니다:
if (condition1) {
code;
} else if (condition2) {
code;
} else if (condition3) {
code;
}직접 해보기
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int wind = scanner.nextInt(); // 이 줄을 변경하지 마세요
String status = "unset";
// 아래에 코드를 입력하세요
// 아래 줄을 변경하지 마세요
System.out.println("status = " + status);
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