Groovy User Guide (8)

xiaoxiao2021-03-06  44

8, cycle

(1) While and DO cycles

l Groovy supports the same While and DO loops in Java

X = 0

Y = 5

While (y -> 0) {

X

}

askERT X == 5

X = 0

Y = 5

Do {

X

}

While (--y> 0)

askERT X == 5

(2) for loop

l Groovy's For loop is simpler, and can work with various types, collections, map, etc.

// Iteerate over a Range

X = 0

For (i in 0..9) {

X = i

}

askERT X == 45

// Iterage over a list

X = 0

For (I IN [0, 1, 2, 3, 4) {

X = i

}

askERT X == 10

// Iterage over an Array

Array = (0..4) .toarray ()

X = 0

For (i in array) {

X = i

}

askERT X == 10

// Iteerate over a MAP

Map = ['ABC': 1, 'DEF': 2, 'XYZ': 3]

X = 0

For (e IN map) {

X = E.Value

}

askERT X == 6

// Itereate over Values ​​in A MAP

X = 0

FOR (Vin map.values ​​()) {

X = V

}

askERT X == 6

// Iterage over the Characters in A String

Text = "ABC"

List = []

For (c in text) {

List.add (c)

}

askERT LIST == ["A", "B", "C"]

转载请注明原文地址:https://www.9cbs.com/read-112650.html

New Post(0)