| |
| 1 Looping |
| |
| Groovy supports the usual while {...} and do {...} while loops like Java. |
| |
| {code:groovy} |
| x = 0 |
| y = 5 |
| |
| while ( y-- > 0 ) { |
| x++ |
| } |
| |
| assert x == 5 |
| |
| x = 0 |
| y = 5 |
| |
| do { |
| x++ |
| } |
| while ( --y > 0 ) |
| |
| assert x == 5 |
| {code} |
| |
| 1.1 for loop |
| |
| The for loop in Groovy is much simpler and works with any kind of array, collection, Map etc. |
| |
| {code:groovy} |
| // 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 the characters in a string |
| text = "abc" |
| list = [] |
| for (c in text) { |
| list.add(c) |
| } |
| assert list == ["a", "b", "c"] |
| {code} |