zoukankan      html  css  js  c++  java
  • 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开始。

  • 相关阅读:
    GridView编辑删除操作
    hdu 4857 逃生 拓扑排序+PQ,剥层分析
    每日回顾Shell —cat,tail,head
    uva:10700
    Unity多玩家网络游戏开发教程1章Unity带有网络功能
    android com.handmark.pulltorefresh 使用技巧
    Jsoup 抓取和数据页 认识HTTP头
    JDK8在Java转让Javascript脚本引擎动态地定义和运行代码
    2013-2014约半学期的学习和规划研究综述
    Javascript 设计模式 辛格尔顿
  • 原文地址:https://www.cnblogs.com/yaoyuan2/p/5719189.html
Copyright © 2011-2022 走看看