public static void main(String[] args) {
int num;
Scanner sc = new Scanner(System.in);
System.out.println("숫자 입력: ");
num = sc.nextInt();
switch(num) {
case 1 : System.out.println("1입니다"); break;
case 2 : System.out.println("2입니다"); break;
case 3 : System.out.println("3입니다"); break;
default : System.out.println("1~3이 아닙니다");
}
System.out.println("switch~case 공부중");
System.out.println("과일명 입력: ");
String fruit = sc.next();
switch(fruit) {
case "apple" : System.out.println("사과"); break;
case "grape" : System.out.println("포도"); break;
case "peach" : System.out.println("복숭아"); break;
default : System.out.println("그 밖의 과일");
}
sc.close();
}
switch~case도 if문과같이 조건문이라고 할수 있다
위를 예로들면 num의경우 int이기때문에 scanner을 이용해 1을 입력하게된다면 case 1에 있는 1입니다가 출력하게 되며
fruit의 경우 string은 문자열이여서 apple을 입력하게 되며 사과라는 단어가 뜨게된다
String fruit = sc.next();은 int가 nextint인것처럼 String을 사용할시에는 next로 작성하면된다
break문의 경우 강제로 멈춘다는것을 의미하는데 break문을 사용할시 switch문을 강제로 빠져나와 그 뒤에있는 코드를 실행시키게하는 역할이다
sc.close의 경우 scanner을 종료함을 의미한다
'JAVA' 카테고리의 다른 글
13. For문(제어문)2 (0) | 2023.07.27 |
---|---|
12. For문(제어문) (0) | 2023.07.27 |
10. IF문(제어문) (0) | 2023.07.27 |
9. 증감연산자, 삼항연산자 (0) | 2023.07.27 |
8. JAVA 관계 논리 (0) | 2023.07.26 |