조건문 switch
조건문의 또 다른 메소드로
switch문의 경우 괄호의 숫자가 주어지면 해당 숫자의case들이 끝까지 실행된다.
예를 들어 switch2 라면 case2 부터 존재하는 case 까지 전부 실행하게 된다
System.out.println("switch(1)");
switch(1){
case 1:
System.out.println("one");
case 2:
System.out.println("two");
case 3:
System.out.println("three");
}
System.out.println("switch(2)");
switch(2){
case 1:
System.out.println("one");
case 2:
System.out.println("two");
case 3:
System.out.println("three");
}
System.out.println("switch(3)");
switch(3){
case 1:
System.out.println("one");
case 2:
System.out.println("two");
case 3:
System.out.println("three");
}
결과
(*
switch(1)
one
two
three
switch(2)
two
three
switch(3)
three
)
break
break를 이용하면 실행이 즉시 중단된다
System.out.println("switch(1)");
switch(1){
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
case 3:
System.out.println("three");
break;
}
System.out.println("switch(2)");
switch(2){
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
case 3:
System.out.println("three");
break;
}
System.out.println("switch(3)");
switch(3){
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
case 3:
System.out.println("three");
break;
}
결과
(*
switch(1)
one
switch(2)
two
switch(3)
three)
break를 만나 해당하는 case까지만 실행된 뒤 멈췄다
default
case가 없을때 default가 실행된다
switch(4){
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
case 3:
System.out.println("three");
break;
default:
System.out.println("default");
break;
}
결과
(*
switch(4)
default)
// switch문에 case4는 존재하지 않는다. 그러므로
defalut가 실행된다.
'프로그래밍 > Java (기초)' 카테고리의 다른 글
반복문(while, for) (0) | 2016.03.18 |
---|---|
논리 연산자 (and, or, not) (0) | 2016.03.18 |
조건문 - if (0) | 2016.03.18 |
비교와 Boolean(불리언) (0) | 2016.03.18 |
연산자, 그리고 삼항 연산자 (0) | 2016.03.18 |