위에서 아래로 흘러가는 코드의 흐름이 갑자기 돌거나 반복하거나 뛰어 넘을 수 있도록
조건에 따라 다른 문장이 수행되도록 함
if(조건식) {
true일 때 수행되는 코드}
else {
false일 때 수행되는 코드}
if(num % 2 == 0) {
System.out.println("짝수");}
else {
System.out.println("홀수");}
if(month == 1 || month == 2 || month == 12) {
season = "겨울";
} else if(month >= 3 && month <= 5) {
season = "봄";
} else if(month >= 6 && month <= 8) {
season = "여름";
} else if(month >= 9 && month <= 11) {
season = "가을";
} else {
season = "해당하는 계절이 없습니다.";
}
if (조건식1) {
if (조건식2) {
if (조건식3) {
수행될 코드;
} else if (조건식4) {
수행될 코드;
} else {
수행될 코드;
}
} else {
수행될 코드;
}
} else if (조건식5) {
수행될 코드;
} else {
수행될 코드;
}
if (month == 1 || month == 2 || month == 12) {
season ="겨울";
if (temperature <=-15) {
season += " 한파 경보";
} else if (temperature <=-12) {
season += " 한파 주의보";
}
} else if (month >= 3 && month <= 5) {
season ="봄";
} else if (month >= 6 && month <= 8) {
season ="여름";
if (temperature >= 35) {
season += " 폭염 경보";
} else if (temperature >= 33) {
season += " 폭염 주의보";
}
} else if (month >= 9 && month <= 11) {
season ="가을";
} else{
season ="해당하는 계절이 없습니다.";
}
조건식 하나로 많은 경우의 수 처리할 때 사용하며
이때 조건식의 결과는 정수 또는 문자, 문자열
조건식의 결과 값과 일치하는 case문으로 이동
default문은 일치하는 case문이 없을 때 수행(= else )
switch(num % 5) {
case 1: team = "1조"; break;
case 2: team = "2조"; break;
case 3: team = "3조"; break;
case 4: team = "4조"; break;
default: team = "다시";
}
switch(month){
case 1 :
case 3 :
case 5 :
case 7 :
case 8 :
case 10 :
case 12 : System.out.println(month + "월은 31일까지 있습니다."); break;
case 4 :
case 6 :
case 9 :
case 11 : System.out.println(month + "월은 30일까지 있습니다."); break;
case 2 : System.out.println(month + "월은 28일까지 있습니다."); break;
default : System.out.println(month + "월은 잘못 입력된 달입니다.");
}