switch~case 구문
switch~case
이 문서에서는 switch~case 구문에 대해서 살펴본다.
형태
switch(변수){
case 값1: /* 실행할 코드 */
case 값2: /* 실행할 코드 */
case 값3: /* 실행할 코드 */
...
default: /* 실행할 코드 */
}
switch 구문은 if문과 다르게 변수의 값을 이용하여 이동 지점을 탐색하는 구문이다.
변수 자리에는 byte
, short
, char
, int
, String
형태의 변수만 사용할 수 있다.
데모 1 : 홀짝 판정 프로그램
import java.lang.*;
public class SwitchExample01 {
public static void main(String[] args){
int number = 50;
switch(number % 2){
case 0:
System.out.println("짝수");
break;
case 1:
System.out.println("홀수");
break;
}
}
}
if구문으로도 구현이 가능한 홀짝 판정 프로그램이다. switch의 경우 값을 기준으로 이동 위치를 판정하기 때문에 논리식이 아닌 number % 2
와 같은 값이 나오는 식을 작성하였으며, 각각의 나올 수 있는 값들의 경우를 case
라는 키워드 뒤에 정의하여 이동 지점을 명시하였다.
break
가 없을 경우 구문이 끝나지 않고 계속 실행되며, 원치 않는 결과가 나올 수 있으므로 case가 종료된 뒤 사용하여 탈출을 지시하였다.
if문으로 동일하게 구현하면 다음과 같다.
if(number % 2 == 0){
System.out.println("짝수");
}
else{
System.out.println("홀수");
}
데모 2 : 계절 판정 프로그램
import java.lang.*;
public class SwitchExample02{
public static void main(String[] args){
int month = 11;
switch(month){
case 12: case 1: case 2:
System.out.println("겨울");
break;
case 3: case 4: case 5:
System.out.println("봄");
break;
case 6: case 7: case 8:
System.out.println("여름");
break;
case 9: case 10: case 11:
System.out.println("가을");
break;
default:
System.out.println("잘못된 입력");
}
}
}
월을 3개씩 묶어 계절을 판정하는 프로그램이다. 별도의 처리를 하지 않을 경 다음과 같이 12개의 case
를 모두 구현해야 한다.
switch(month){
case 1:
System.out.println("겨울");
break;
case 2:
System.out.println("겨울");
break;
case 3:
System.out.println("봄");
break;
case 4:
System.out.println("봄");
break;
case 5:
System.out.println("봄");
break;
case 6:
System.out.println("여름");
break;
case 7:
System.out.println("여름");
break;
case 8:
System.out.println("여름");
break;
case 9:
System.out.println("가을");
break;
case 10:
System.out.println("가을");
break;
case 11:
System.out.println("가을");
break;
case 12:
System.out.println("겨울");
break;
default:
System.out.println("잘못된 입력");
break;
}
위의 코드는 중복된 내용이 너무 많기 때문에, 탈출에 사용되는 break
를 의도적으로 없에 다음과 같이 바꿀 수 있다.
switch(month){
case 12:
case 1:
case 2:
System.out.println("겨울");
break;
/* 이하 생략 */
}
switch
구문은 break
가 없을 경우 계속 실행된다는 특징을 이용하여 몇 개의 case
를 그룹처럼 묶을 수 있다.
모든 코드는 가로로 늘어놓을 수 있으므로 가독성을 위하여 다음과 같이 변경한다.(하지 않아도 좋다)
switch(month){
case 12: case 1: case 2:
System.out.println("겨울");
break;
/* 이하 생략 */
}
마지막 break
는 생략이 가능하므로 코드가 많이 감소되어 예제처럼 구현된다.
데모 3 : 월별 날짜 계산 프로그램
import java.lang.*;
public class SwitchExample03{
public static void main(String[] args){
int month = 5;
switch(month){
case 2:
System.out.println("28일");
break;
case 4: case 6: case 9: case 11:
System.out.println("30일");
break;
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
System.out.println("31일");
break;
default:
System.out.println("잘못된 입력");
}
}
}
1월부터 12월까지의 달을 다음 세 가지로 구분한다.
2월 : 28일까지 존재(윤년 제외)
4, 6, 9, 11월 : 30일까지 존재
1, 3, 5, 7, 8, 10, 12월 : 31일까지 존재
if문으로 작성할 경우 규칙이 없어 조건을 작성하기가 매우 까다롭다.
if(month == 2){
}
else if(month == 4 || month == 6 || month == 9 || month == 11){
}
else if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12){
}
else{
}
이럴 경우 switch를 사용하면 좀 더 간결한 코드 작성이 가능하다.
주의사항
switch~case 구문을 사용할 경우 주의할 점은 다음과 같다.
변수 위치에는
byte
,short
,char
,int
,String
형태의 변수만 사용 가능하다.case
에는 식을 적을 수 없고 값만 적을 수 있다.break
를 사용하여 탈출할 수 있으며, 사용하지 않을 경우 종료 시점까지 계속 진행된다.default
는 case를 제외한 나머지 경우를 처리한다
Last updated