- 조건식과 문장을 포함하는 블록{}으로 구성되어 있다.
- 조건식의 연산결과에 따라 프로그램의 실행흐름을 변경할 수 있다.
- 조건을 만족할때만 수행
if문
기본 구조
if(조건식){
조건식이 true일때 수행될 문장
}
예시
boolean power = true;
if(power == true){
System.out.println("켜져있음");
}
if-else
if(조건식){
조건식이 true일때 수행
}else{
조건식이 false일때 수행
}
예시
boolean power = true;
if(power){
System.out.println("켜져있음");
}else{
System.out.println("꺼져있음");
}
if-else if
if(조건식1){
조건식1이 true일때 수행
}else if(조건식2){
조건식1 = false 이고 조건식2 = true
}else{
조건식1과 조건식2가 모두 false일때 수행
}
예시
int a1 = 10;
if(a1>0){
System.out.println("양수");
}else if(a1<0){
System.out.println("음수");
}else{
System.out.println("0");
}
int score = (int)(Math.random()*101);
if(score >= 90){
System.out.print("A")
if(score >= 95){
System.out.println("+")
}else{
System.out.println("-")
}
}else if(score >= 80){
System.out.print("B")
if(score >= 85){
System.out.println("+")
}else{
System.out.println("-")
}
}else if(score >= 70){
System.out.print("C")
if(score >= 75){
System.out.println("+")
}else{
System.out.println("-")
}
}else if(score >= 60){
System.out.print("D")
if(score >= 65){
System.out.println("+")
}else{
System.out.println("-")
}
}else{
System.out.println("F")
}
switch-case문
- 조건의 경우의 수가 많을때는 if문 보다는 switch문을 사용하는 것이 좋다.
- 조건의 결과값으로 int형 범위의 정수값을 허용한다.
int a = 10;
switch(조건식-int형의 연산결과값이나 변수){
case 값1 :
조건식 == 값1일때 수행될 문장
break;
case 값2 :
조건식 == 값2일때 수행될 문장
break;
default :
조건식과 만족하는 값이 없을때 수행될 문장.
}
예시
int score = (int)(Math.random()*101);
switch(score/10){
case 10 :
System.out.println("A")
break;
case 9 :
System.out.println("A")
break;
case 8 :
System.out.println("B")
break;
case 7 :
System.out.println("C")
break;
case 6 :
System.out.println("D")
break;
default :
System.out.println("F")
}