2012-10-05 102 views
5

今天我遇到了這個難題。顯然,這是不正確的風格,但我仍然好奇爲什麼沒有產出。爲什麼我的if語句以這種方式表現?

int x = 9; 
int y = 8; 
int z = 7; 

if (x > 9) if (y > 8) System.out.println("x > 9 and y > 8"); 

else if (z >= 7) System.out.println("SHOULD OUTPUT THIS x <= 9 and z >= 7"); 

else 
    System.out.println("x <= 9 and z < 7"); 

以上運行時沒有輸出。但是,當我們爲if語句添加括號時,突然間邏輯的行爲就像我期望的那樣。

int x = 9; 
int y = 8; 
int z = 7; 

if (x > 9) { 
    if (y > 8) System.out.println("x > 9 and y > 8"); 
} 

else if (z >= 7) System.out.println("SHOULD OUTPUT THIS x <= 9 and z >= 7"); 

else 
    System.out.println("x <= 9 and z < 7"); 

這會輸出「應該輸出x < = 9且z> = 7」。這裏發生了什麼?

謝謝!

+3

哈哈......'else'適用於最內層的嵌套層次。 – Mysticial

回答

7

如果重寫這樣,第一種方式(這是它是如何表現),這是容易理解

if (x > 9) 
    if (y > 8) System.out.println("x > 9 and y > 8"); 
    else if (z >= 7) System.out.println("SHOULD OUTPUT THIS x <= 9 and z >= 7"); 
    else 
    System.out.println("x <= 9 and z < 7"); 

由於x不> 9,塊從不執行。

0

只是固定在你的代碼的縮進和問題變得清晰:

int x = 9; 
int y = 8; 
int z = 7; 

if (x > 9) 
    if (y > 8) 
     System.out.println("x > 9 and y > 8"); 
    else if (z >= 7) 
     System.out.println("SHOULD OUTPUT THIS x <= 9 and z >= 7"); 
    else 
     System.out.println("x <= 9 and z < 7"); 
4

此:

if (x > 9) ... if (y > 8) ... else if (z >= 7) ... else 

是模糊的,因爲解析else期間可能被綁定到第一if或第二個if。 (這被稱爲the dangling else problem)。 Java(和許多其他語言)處理這個問題的方式是使第一個含義非法,因此else子句總是綁定到最內層的語句。

+0

最佳答案,因爲它實際上解釋了問題的調用方式以及爲什麼會這樣。 +1 – Vulcan

0

因爲你使用的是其他人擋在最內側的水平

您的代碼被視爲下面的代碼

if (x > 9) // This condition is false, hence the none of the following statement will be executed 
{ 
    if (y > 8) 
    { 
     System.out.println("x > 9 and y > 8"); 
    } else if(z >= 7) 
    { 
     System.out.println("SHOULD OUTPUT THIS x <= 9 and z >= 7"); 
    } 
    else 
    { 
     System.out.println("x <= 9 and z < 7"); 
    } 
} 

與指定的第一個條件if語句是不是進入虛假和控制轉化爲與該條件相關的代碼,並簡單地到達程序的結尾並且不打印任何內容。

這就是爲什麼它的正常做法是用括號括住語句,即使您正在編寫單個語句。

相關問題