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