[英]The rules of Nested IF conditional statements without using curly braces
考慮到我已經有2年的編程經驗,這可能是一個非常初學者的問題,但是,嵌套IF條件語句及其在沒有花括號的情況下如何工作始終使我感到困擾。
我一直使用花括號來使編碼井井有條。 例如這樣。
public static void main(String[] args)
{
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("x <= 9 and z >= 7");
}
else
{
System.out.println("x <= 9 and z < 7");
}
}
我一直使用這種模式,因為它一直對我有用。
但是,為什么用這種格式寫的東西卻不能以同樣的方式工作呢?
public static void main(String[] args)
{
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("x <= 9 and z >= 7");
else
System.out.println("x <= 9 and z < 7");
}
第一個代碼將打印出x <= 9和z> = 7,但是第二個代碼將不打印任何內容。 (我假設else if和else語句位於初始if語句內)。
換句話說,當沒有花括號發生時,如上例所示,編譯器如何測試條件語句的規則是什么? 我曾嘗試過在線查找信息,但似乎找不到信息和/或不知道該如何專門稱呼此問題以研究我的疑慮。
編譯器不關心縮進。 的else
條款總是與最后一個關聯if
不已經有一個else
。 這個:
if (x > 9)
if (y > 8)
System.out.println("x > 9 and y > 8");
else if (z >= 7)
System.out.println("x <= 9 and z >= 7");
else
System.out.println("x <= 9 and z < 7");
與此相同:
if (x > 9)
{
if (y > 8)
{
System.out.println("x > 9 and y > 8");
}
else
{
if (z >= 7)
{
System.out.println("x <= 9 and z >= 7");
}
else
{
System.out.println("x <= 9 and z < 7");
}
}
}
另外,請注意else if(...) ...
實際上只是意味着else {if(...) {...}}
-它是else
和if
的組合,不是特殊功能。
第二,如果我在上面加上花括號,編譯器將像這樣。 因為else if
or else
發現if
。
if (x > 9) {
if (y > 8){
System.out.println("x > 9 and y > 8");
}else if (z >= 7) {
System.out.println("x <= 9 and z >= 7");
}else {
System.out.println("x <= 9 and z < 7");
}
}
如果必須復制,則應至少放置一個括號,例如:
if (x > 9) {
if (y > 8)
System.out.println("x > 9 and y > 8");
else if (z >= 7)
System.out.println("x <= 9 and z >= 7");
}else
System.out.println("x <= 9 and z < 7");
現在,如果可以肯定的話,Last else首先關閉。
這實際上不是花括號的問題,而是代碼格式的問題。 在Java(或C ++)中,空格並不重要。
因此,當您編寫此代碼時:
if (x > 9)
if (y > 8)
System.out.println("x > 9 and y > 8");
else if (z >= 7)
System.out.println("x <= 9 and z >= 7");
else
System.out.println("x <= 9 and z < 7");
這並不意味着它等同於您的原始代碼。 為了說明原因,這是如何更合理地格式化此代碼:
if (x > 9)
if (y > 8)
System.out.println("x > 9 and y > 8");
else if (z >= 7)
System.out.println("x <= 9 and z >= 7");
else
System.out.println("x <= 9 and z < 7");
我希望這可以說明這里發生的事情。
本質上,大括號可以使編譯器保持正常運行。 如果只有1個if和另外1個,例如:
if (x < 3)
// some code here
else
// something else here
當您在現實生活中遇到數學問題時,運算順序會告訴您首先執行括號中的內容,不是嗎? 大括號是一個分組符號,用於表示編譯器要執行的操作順序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.