JAVA를 자바
[7] switch 문
지식보부상님
2020. 12. 29. 16:03
C언어의 switch 문의 사용과 매우 유사합니다!
switch( choice ){
case 1: <statement 1> break;
case 2: <statement 2> break;
case 3: <statement 3> break;
:
:
default: <statement N> break;
}
와 같은 형식으로 사용하면
choice 에 case를 결정지어주는 식이 존재하고,
결정된 case에 맞게 case가 실행되고,
모든 case에 경우가 없다면 default 를 실행하게 됩니다!
다음과 같은 예시 코드를 보면,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
System.out.println("Enter a number");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
switch (n % 5) {
case 0:
System.out.println("n % 5 = 0");
break;
case 1:
System.out.println("n % 5 = 1");
break;
case 2:
System.out.println("n % 5 = 2");
break;
default:
System.out.println("n % 5 = 3 or 4");
}
|
cs |
위와 같은 코드가 있다고 하면
다음과 같은 결과를 얻을 수 있습니다!