JAVA

5일차// 조건문 switch 문

aesup 2021. 1. 15. 12:01
728x90

if 의 조건 부분은 boolean 값(참인지, 거짓인지에 의해 결과값이 결정된다.

Switch 문은 변수 또는 식에 의해 결과값이 결정된다.

 

switch 

if 문과 비슷하다
값이 명확해야 한다
실수를 사용할 수 없다( double은 사용 불가능)
범위를 지정할 수 없다

 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
        
public class SwitchMainClass {
    public static void main(String[] args) {
        /*
        
        switch :if 문과 비슷하다
                값이 명확해야 한다
                실수를 사용할 수 없다( double은 사용 불가능)
                범위를 지정할 수 없다
                
                if(num == 1){
                }
                else if(num == 2){
                } //이거랑같다
                
                
                
                형식: 
                    switch(대상이 되는 변수){
                    
                        case 값1:
                            처리1
                            break;
                    
                        case 값2:
                            처리2
                            break;
                        default :   == else
                            처리n
                    
                    }
                    */
        int number = 4;
        
        switch(number) {
        case 1:    //if(number == 1)
            System.out.println("number는 1입니다");
            break;         //탈출 구문 break를 안쓰면 뒤에까지 처리
        case 2:    //else if(number == 2)        
            System.out.println("number는 2입니다");
            break;
        case 3//else if(number == 3)
            System.out.println("number는 3입니다");
            break;
        default : //else
            System.out.println("number는 1,2,3도 아닙니다");
            
        
        }
        
        char c = 'B';
        
        switch(c) {
        case 'A' :
            System.out.println("A입니다");
            break;
        
        case 'B' :
            System.out.println("B입니다");
            break;
            
        }
        
        
        String str = "hello";
        //str =str + "llo"; 이렇게 하면 안된다 if에서는 !!!
        //equals 함수를 써서 비교  
        
        
        
        if(str == "hello") {
            System.out.println("str은 hello입니다");
        }
        
        
        // switch문에서는 str == "hello"가 된다.
        switch(str) {
        case "hello" :
            System.out.println("hello");
            break;
        }
        
        
        
        
        
        
    }
}
 
        
 
cs

 

728x90