Groovy - 巢狀 If 語句



有時需要將多個 if 語句巢狀在一塊兒。

此語句的一般形式為 -

if(condition) { 
   statement #1 
   statement #2 
   ... 
} else if(condition) { 
   statement #3 
   statement #4 
} else { 
   statement #5 
   statement #6 
}

以下是巢狀的 if/else 語句示例 -

class Example { 
   static void main(String[] args) { 
      // Initializing a local variable 
      int a = 12 
		
      //Check for the boolean condition 
      if (a>100) {
         //If the condition is true print the following statement 
         println("The value is less than 100"); 
      } else 
         // Check if the value of a is greater than 5 
			
      if (a>5) { 
         //If the condition is true print the following statement 
         println("The value is greater than 5 and greater than 100"); 
      } else { 
         //If the condition is false print the following statement 
         println("The value of a is less than 5"); 
      }  
   } 
}	     

在以上示例中,我們首先初始化的值為 12。在第一個 if 語句中,我們檢查 a 的值是否大於 100。如果不是,則進入第二個 for 迴圈,檢查 a 的值是否大於 5 或小於 5。以上程式碼的輸出將為 -

The value is greater than 5 and greater than 100
groovy_decision_making.htm
廣告
© . All rights reserved.