目录

for-in 声明

for-in语句用于迭代一组值。 for-in语句通常以下列方式使用。

for(variable in range) { 
   statement #1 
   statement #2 
   … 
}

下图显示了此循环的图解说明。

对于In Loop

以下是for-in声明的示例 -

class Example { 
   static void main(String[] args) { 
      int[] array = [0,1,2,3]; 
      for(int i in array) { 
         println(i); 
      } 
   } 
}

在上面的例子中,我们首先初始化一个具有4个值0,1,2和3的整数数组。然后我们使用for循环语句首先定义一个变量i,然后迭代遍历数组中的所有整数并相应地打印值。 上述代码的输出将是 -

0 
1 
2 
3

for-in语句也可用于循环遍历范围。 以下示例说明了如何实现此目的。

class Example {
   static void main(String[] args) {
      for(int i in 1..5) {
         println(i);
      }
   } 
} 

在上面的例子中,我们实际上循环遍历从1到5定义的范围并打印范围中的每个值。 上述代码的输出将是 -

1 
2 
3 
4 
5 

for-in语句也可用于循环Map。 以下示例说明了如何实现此目的。

class Example {
   static void main(String[] args) {
      def employee = ["Ken" : 21, "John" : 25, "Sally" : 22];
      for(emp in employee) {
         println(emp);
      }
   }
}

在上面的示例中,我们实际上是循环遍历具有一组已定义的键值条目的映射。 上述代码的输出将是 -

Ken = 21 
John = 25 
Sally = 22 
↑回到顶部↑
WIKI教程 @2018