Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- MacOS
- python
- function
- php
- github
- DATAPATH
- for
- XML
- CSS
- data structure
- MIPS
- system
- control
- Pipelining
- mysql
- Java
- Class
- Linux
- html
- computer
- DS
- react
- architecture
- DB
- javascript
- instruction
- Algorithm
- web
- DoM
- while
Archives
- Today
- Total
YYYEJI
[JAVA] If 문이란? 본문
728x90
If문이란?
If의 뜻은 '만약에'입니다.
이처럼 if문은 조건문에 따라 결과가 다르게 작동합니다.
① If문
if(Boolean_Expression)
Action; // execute only if true
public static void main(String[] args) {
int num = 10;
if(num == 10)
System.out.println("The number is 10.");
num++;
}
If문의 조건문(Boolean_Expression)이 참이면 if문 안에 있는 code가 실행됩니다.
② If-else문
if(Boolean_Expression){
Action1 // execute only if true
} else {
Action2 // execute only if false
}
public static void main(String[] args) {
int num = 0;
if(num == 10) {
System.out.println("The number is 10.");
} else {
num++;
}
System.out.println("The result is " + num + ".");
}
If문의 조건문(Boolean_Expression)이 true이면 if문 안에 있는 code가 실행되지만,
이 code에 있는 if문은 false이기 때문에 else문이 실행됩니다.
③ if-else if문
if(Boolean_Expression_1){
Action1
} else if(Boolean_Expression_2){
Action2
} else if(Boolean_Expression_3){
Action3
} else if(Boolean_Expression_4){
Action4
}
public static void main(String[] args) {
int score = 90;
char grade = 'A';
if (score >= 90) {
grade = 'A';
} else if (score>=80) {
grade = 'B';
} else if (score>=70) {
grade = 'C';
} else if (score>=60) {
grade = 'D';
}
System.out.println("Your grade is " + grade + ".");
}
여러개의 조건문(Boolean_Expression) 중에 true가 되는 if(or else if)문이 실행됩니다.
④ if-else if-else문
if(Boolean_Expression_1){
Action1
} else if(Boolean_Expression_2){
Action2
} else if(Boolean_Expression_3){
Action3
} else if(Boolean_Expression_4){
Action4
} else {
Action5
}
public static void main(String[] args) {
int score = 0;
char grade = 'A';
if (score >= 90) {
grade = 'A';
} else if (score>=80) {
grade = 'B';
} else if (score>=70) {
grade = 'C';
} else if (score>=60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Your grade is " + grade + ".");
}
if-else if문과 동일합니다.
다른점은 모든 조건문(Boolean_Expression)이 false일 경우에 else문이 실행된다는 점입니다.
◡̈
'Java' 카테고리의 다른 글
[JAVA] Switch 문이란? (0) | 2022.12.24 |
---|---|
[JAVA] 조건부 연산자(Conditional operator) (0) | 2022.12.24 |
[JAVA] Flow of Control (0) | 2022.12.24 |
[JAVA] Scanner 클래스 (0) | 2022.12.24 |
[JAVA] 변수(variable)란? (0) | 2022.12.23 |