今天我遇到了這個難題。顯然,這是不正確的風格,但我仍然好奇爲什麼沒有產出。爲什麼我的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」。這裏發生了什麼?
謝謝!
哈哈......'else'適用於最內層的嵌套層次。 – Mysticial