Posts List

2013년 5월 9일 목요일

[Java]Dangling else


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
    public static void main(String[] args) {
        int key = 1;
        
        System.out.println("no1");
        if(key == 1)
            if(key==1)
                System.out.println("key OK");
        else
            System.out.println("key nonono");
        
        
        System.out.println("no2");
        if(key == 2)
            if(key==2)
                System.out.println("key OK");
            else
                System.out.println("key nonono");
        
        
        
        System.out.println("no3");
        if(key == 1)
            if(key==2)
                System.out.println("key OK");
            else
                System.out.println("key nonono");
-->
no1
key OK
no2
no3
key nonono


if문을 2중으로 사용시 else가 { }가 없을 때의 문제점이다.

no1처럼 1번째 if문에 else가 속할까?
no2처럼 2번째 if문에 속할까? 

정답은 no2 이다.
{ }없이 사용하려면 no2처럼 tab 길이를 맞쳐놓으면 헷갈리지 않을 수 있으나
혹시 모르니 이럴 경우 {  } 써주는게 좋을듯 하다.

댓글 없음:

댓글 쓰기