if, if-else, else-if)이 무엇인지 학습합니다.switch 문이 무엇인지 학습합니다.---
if - 조건 수식이 참일 때 실행if-else - 조건 수식이 거짓일 때 실행else-if - 여러 개의 조건을 제어할 때 활용switch - 특정 값에 따라 여러 동작을 실행컴퓨터는 스스로 판단할 수 없습니다. 하지만 미리 정의된 조건을 활용하면 프로그램이 특정 조건에 맞게 동작할 수 있습니다. 예를 들어, 신호등을 보고 우리가 행동을 결정하는 것처럼, 프로그램도 특정 조건에 따라 다르게 동작하도록 만들 수 있습니다.
조건 수식 부분이 참(true) 혹은 거짓(false) 인지에 따라 명령문 실행 여부가 결정됩니다.
if 문 구조if (조건수식) {
// 실행할까? 말까?
명령문;
}
if (1 < 2) { // true
System.out.println("This statement will execute.");
}
if (2 < 1) { // false
System.out.println("This statement will not execute.");
}
if, if-else, else-if 문if 문조건이 참일 때만 실행됩니다.
public class Main {
public static void main(String[] args) {
String light = "green";
if (light.equals("green")) {
System.out.println("Go!");
}
}
}
if-else 문조건이 거짓일 때 실행할 코드 추가
public class Main {
public static void main(String[] args) {
String light = "red";
if (light.equals("green")) {
System.out.println("Go!");
} else {
System.out.println("Stop!");
}
}
}
else-if 문여러 개의 조건을 처리할 때 사용됩니다.
public class Main {
public static void main(String[] args) {
String light = "yellow";
if (light.equals("green")) {
System.out.println("Go!");
} else if (light.equals("yellow")) {
System.out.println("Caution!");
} else {
System.out.println("Stop!");
}
}
}
light = "green" → Go!light = "yellow" → Caution!light = "red" → Stop!switch 문switch 문은 값에 따라 여러 동작을 실행할 때 사용됩니다. 괄호 안에 단일 값만 들어갈 수 있으며, 조건식은 사용할 수 없습니다.
switch 문 구조switch (단일값) {
case 값1:
// 값1일 때 실행할 코드
break;
case 값2:
// 값2일 때 실행할 코드
break;
default:
// 위 값들과 일치하지 않을 때 실행할 코드
}
switch 문 예제public class SwitchNumber {
public static void main(String[] args) {
int number = 1;
switch (number) {
case 1:
System.out.println("Number is 1.");
break;
case 2:
System.out.println("Number is 2.");
break;
default:
System.out.println("Number is neither 1 nor 2.");
}
}
}
fall-through 현상 주의break 문을 생략하면 다음 case 문이 실행될 수 있습니다.
public class SwitchNumber {
public static void main(String[] args) {
int number = 1;
switch (number) {
case 1:
System.out.println("Number is 1.");
// break; 확인해보세요!
case 2:
System.out.println("Number is 2.");
break;
default:
System.out.println("Number is neither 1 nor 2.");
}
}
}
break가 없을 경우)Number is 1.
Number is 2.
이처럼 break 문을 사용하지 않으면 다음 case 문까지 실행되는 현상(fall-through)이 발생할 수 있으므로 주의해야 합니다.
이제 조건문을 활용하여 프로그램의 선택지를 만들어 보세요! 🚀