Groovy - if/else 語句



接下來我們將看到的決策制定語句是if/else 語句。此語句的一般形式如下 −

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

此語句的一般工作方式是先在if 語句中評估條件。如果條件為真,則執行其後的語句,並在 else 條件之前停止並退出迴圈。如果條件為假,則執行 else 語句塊中的語句,然後退出迴圈。下圖顯示了if 語句的流程。

If Statements

下面是一個 if/else 語句的示例 −

class Example { 
   static void main(String[] args) { 
      // Initializing a local variable 
      int a = 2
		
      //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 { 
         //If the condition is false print the following statement 
         println("The value is greater than 100"); 
      } 
   } 
}

在上面的示例中,我們首先將一個變數初始化為值 2。然後我們評估該變數的值,然後決定應執行哪個println 語句。上述程式碼的輸出將是

The value is less than 100.
groovy_decision_making.htm
廣告
© . All rights reserved.