14 循环结构

1       循环结构

1.1  For 和while loops

groovy支持标准的java的for, for-each 和 while循环,然而并不支持do while 循环。

1.2  使用each方法

each() 可以应用于lists、maps、ranges。

each中的变量,可以使用自定义的,也可以使用groovy固有的it。

package structure

 

class EachLoop {

 

    static main(args) {

       def list = ["左","杨","王"];

       //使用自定义的变量firstName

       list.each { firstName ->

           println firstName;

       };

       println ("==============");

       //使用固有的it变量

       list.each {

           println it;

       }

    }

 

}

输出相同的结果,如下

==============

groovy也提供了eachWithIndex 方法,有2个参数,第一个参数是元素(element);第二个参数是索引(index)。

1.3  使用数值迭代(Iterative)

另外,也可以使用upto()downto()times() 这三个方法,实现循环,注意,一定是数值的。当然,你可以使用ranges(另外一种数据类型)来执行从起点数值到结束数值之间的循环。如下:

package structure

 

class NumberAndRangesLoop {

    static main(args) {

       println ("===========times");

       5.times {

           print "$it,";

       };

       println (" ===========upto");

       1.upto(3) {

           print it+",";

       };

       println (" ===========downto");

       4.downto(1) {

           print "$it,";

       }

       println (" ===========upto");

       def sum = 0;

       1.upto(100) {

           sum +=it;

       }

       print sum;

       println (" ===========each(ranges)");

        (1..6).each {

           print "$it,";

       };

    }

}

输出

===========times

0,1,2,3,4,

===========upto

1,2,3,

===========downto

4,3,2,1,

===========upto

5050

===========each(ranges)

1,2,3,4,5,6,

times:从0开始。

原文地址:https://www.cnblogs.com/yaoyuan2/p/5719189.html