Groovy用户指南(8)

类别:Java 点击:0 评论:0 推荐:

8、循环

1whiledo 循环

l         Groovy支持Java相同的while和do 循环

x = 0

y = 5

while ( y-- > 0 ) {

    x++

}

assert x == 5

 

x = 0

y = 5

do {

       x++

}

while ( --y > 0 )

assert x == 5

2for循环

l         Groovy的for循环更简单,而且能够和各种类型的数组、集合、Map等一起工作

// iterate over a range

x = 0

for ( i in 0..9 ) {

    x += i

}

assert x == 45

 

// iterate over a list

x = 0

for ( i in [0, 1, 2, 3, 4] ) {

    x += i

}

assert x == 10

 

// iterate over an array

array = (0..4).toArray()

x = 0

for ( i in array ) {

    x += i

}

assert x == 10

 

// iterate over a map

map = ['abc':1, 'def':2, 'xyz':3]

x = 0

for ( e in map ) {

    x += e.value

}

assert x == 6

 

// iterate over values in a map

x = 0

for ( v in map.values() ) {

    x += v

}

assert x == 6

 

// iterate over the characters in a string

text = "abc"

list = []

for (c in text) {

    list.add(c)

}

assert list == ["a", "b", "c"]

本文地址:http://com.8s8s.com/it/it15132.htm