switch 문
- 조건식 하나로 처리해야 하는 경우의 수가 많을 때 사용
- 조건식의 결과는 정수 또는 문자열
- case문의 값은 정수, 상수(문자 포함), 문자열만 가능
- default는 모든 조건식이 불일치 시 실행하며 생략가능
- break문이나 switch문의 끝을 만나면 조건문 종료
예제
switch (조건식) {
case 값1 :
// 조건식의 결과가 값1과 만족할 경우 수행
break; // switch문을 벗어난다.
...
default :
// 조건식이 모두 만족하지 않을 때 수행
}
과일 가격 출력
public void method1() {
String sFruit ="";
int nPrice = 0;
Scanner s = new Scanner(System.in);
System.out.printf("Tell me what fruit you want to eat: ");
sFruit = s.nextLine();
switch(sFruit) {
case "peach" :
nPrice = 800;
break;
case "watermelon" :
nPrice = 3800;
break;
case "orange" :
nPrice = 450;
break;
case "apple" :
nPrice = 300;
break;
default :
System.out.println("SOLD OUT!!");
}
System.out.printf("%s costs ₩%d\n", sFruit, nPrice);
}
출력값
Tell me what fruit you want to eat: apple
apple costs ₩300
Tell me what fruit you want to eat: banana
SOLD OUT!!
월의 마지막 일수 출력
public void method2() {
int nMonth = 0;
Scanner s = new Scanner(System.in);
System.out.printf("Insert Month(1~12): ");
nMonth = s.nextInt();
if(nMonth < 1 || nMonth > 12) {
System.out.println("Are your eyes twisted?, God damn");
return;
}
switch(nMonth) {
case 1 :
case 3 :
case 5 :
case 7 :
case 8 :
case 10 :
case 12 :
System.out.printf("The Month you insert is 31st\n");
break;
case 4 :
case 6 :
case 9 :
case 11 :
System.out.printf("The Month you insert is 30st\n");
break;
case 2:
System.out.printf("The Month you insert is 28 or 29st\n");
break;
}
}
출력값
Insert Month(1~12): 1
The Month you insert is 31st
Insert Month(1~12): 9
The Month you insert is 30st
Insert Month(1~12): 2
The Month you insert is 28 or 29st
Insert Month(1~12): 13
Are your eyes twisted?, God damn