티스토리 뷰

Java

Switch

Alledy 2019. 3. 18. 22:10
  • Switch

    package com.Hazel;
    
    public class Main {
    
        public static void main(String[] args) {
    	    int value = 1;
    //	    if(value == 1) {
    //            System.out.println("Value is 1");
    //        } else if(value== 2) {
    //            System.out.println("Value is 2");
    //        } else {
    //            System.out.println("Was not 1 or 2");
    //        }
    
    	    int switchValue = 4;
    	    switch (switchValue) {
                case 1:
                    System.out.println("Value was 1");
                    break;
    
                case 2:
                    System.out.println("Value was 2");
                    break;
    
                case 3: case 4: case 5: // 여러 케이스를 한 번에 쓸 수 있다. 
                    System.out.println("was a 3, or a 4, or a 5");
                    System.out.println("Actual value is " + switchValue);
                    break;
    
                default:
                    System.out.println("Was not 1 or 2");
            }
         }
    }
    

    switch문은 char, short, byte, int인 값에 대해 쓸 수 있다.

     

    package com.Hazel;
    
    public class Main {
    
        public static void main(String[] args) {
    
            String month = "january";
            switch(month) {
                case "January":
                    System.out.println("Jan");
                    break;
                case "June":
                    System.out.println("Jun");
                    break;
                default:
                    System.out.println("Not sure");
            }
         }
    }
    

    위 경우 'Not sure'을 출력한다. lowercase를 고려하지 못하기 때문.

        public static void main(String[] args) {
    
            String month = "janUaRy";
            switch(month.toLowerCase()) {
                case "january":
                    System.out.println("Jan");
                    break;
                case "june":
                    System.out.println("Jun");
                    break;
                default:
                    System.out.println("Not sure");
            }
         } // prints "Jan"
    

    switch 안에 month.toLowerCase() 는 입력되는 값을 전부 소문자로 바꾸어서 검사하는 것이다.

 

'Java' 카테고리의 다른 글

조건문  (0) 2019.04.24
자바의 특징, 변수 등  (0) 2019.04.23
Method Overloading  (0) 2019.03.14
Coding exercise - if else if문  (0) 2019.03.14
Expression, DRY, Return  (0) 2019.03.12
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함