FIF's 코딩팩토리

자바 기초 NCS교육과정(5)-분기문 switch~case 본문

Back-End/국비 NCS교과과정

자바 기초 NCS교육과정(5)-분기문 switch~case

FIF 2019. 7. 3. 09:45
반응형

오늘은 switch~case문에 대하여 공부 해보겠습니다.

 

 

 

Java025_switch.java

  switch(식){
    case 값1 : 문장1; break;
    case 값2 : 문장2; break;
    case 값3 : 문장3; break;
    default : 문장4;
  }
  
  식의 결과 타입 : byte, short, char, int
             enum(jdk7버전),String(jdk7버전)
             
  switch~case에서 break을 만나면 현재 수행중인 조건문을 완전히 빠져나와 다음 문장을 수행한다.            
 

if~else문을  switch~case문으로 대체하여 쓸 수 있습니다.

public class Java025_switch {
public static void main(String[] args) {
int jumsu = 100;
char res;
//jumsu >= 90 'A' jumsu>=80 'B' jumsu>=70 'C'
//jumsu >= 60 'D' jumsu<60 'F
if(jumsu>=90) {
res = 'A';
}else if (jumsu>=80) {
res = 'B';
}else if(jumsu>=70) {
res = 'C';
}else if(jumsu>=60) {
res = 'D';
}else {
res = 'F';
}
switch(jumsu/10) {
case 10: //break없는 경우 다음걸로 실행
case 9 : res='A'; break;
case 8 : res='B'; break;
case 7 : res='C'; break;
case 6 : res='D'; break;
default : res='F';
}
System.out.printf("%d점수는 %c학점입니다.\n",jumsu,res);
}//end main()
}//end class

 

Java026_switch.java

public class Java026_switch {
public static void main(String[] args) {
int month = 12; // 월
int lastDay = 31;// 마지막일
if (month < 1 || month > 12) {
System.out.println("1~12까지만 입력하세요.");
return;
}
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
lastDay = 31;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
lastDay = 30;
} else if (month == 28) {
lastDay = 28;
}
System.out.printf("%d월의 마지막 일은 %d입니다.\n", month, lastDay);
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
lastDay = 31;
break;
case 4:
case 6:
case 9:
case 11:
lastDay = 30;
break;
case 2:
lastDay = 28;
}
System.out.printf("%d월의 마지막 일은 %d입니다.\n", month, lastDay);
}//end main()
}//end class

 

Java027_switch.java

public class Java027_switch {
public static void main(String[] args) {
char code = 'B';
if(code=='A') {
System.out.println("식품류");
}else if(code=='B') {
System.out.println("육류");
}else if(code=='C') {
System.out.println("야채류");
}else {
System.out.println("기타");
}
System.out.println("코드별 제품종류 체크");
char code1 = 'B';
switch(code1) {
case 'A' :
System.out.println("식품류");
break;
case 'B':
System.out.println("육류");
break;
case 'C':
System.out.println("야채류");
break;
default:
System.out.println("기타");
}
System.out.println("코드별 제품종류 체크");
}//end main()
}//end class
반응형
Comments