1 选择结构
Groovy 中选择结构主要包含 if -else、switch 语句,并且可以返回结果。
1.1 if-else
Groovy">def score = 85
if (score >= 90) {println("优秀")
} else if (score >= 80) {println("良好")
} else if (score >= 60) {println("及格")
} else {println("不及格")
}
说明:如果 {} 里只有一条语句,可以省略 {},if-else 语句可以嵌套使用,其他流程控制语句也可以嵌套使用。不同于 Kotlin,Groovy 中 if-else 语句不能作为结果判断,即下面的语句是非法的。
Groovy">def score = 85
def res = if (score > 60) "及格" else "不及格"
1.2 switch
1)简单案例
Groovy">def grade = 'B'
switch (grade) {case 'A':println("优秀")breakcase 'B':println("良好")breakcase 'C':println("及格")breakdefault:println("不及格")break
}
说明:如果 {} 里只有一条语句,可以省略 {}。不同于 Kotlin,Groovy 中 when 语句不能作为结果判断。
2)多分支合并
Groovy">def grade = 'B'
switch (grade) {case 'A':case 'B':case 'C':println("及格")breakdefault:println("不及格")break
}
2 循环结构
Groovy 中循环结构主要包含 for、while、do-while 循环结构。另外,continue 语句可以控制跳过某次循环,break 语句可以控制跳出循环体。
2.1 for
for 循环可以对任何提供迭代器(iterator)的对象进行遍历。
1)遍历整数范围
Groovy">for (int i = 1; i < 5; i++) {println(i) // 打印: 1、2、3、4
}
for (i in 1..<5) {println(i) // 打印: 1、2、3、4
}
2)遍历数组 / 列表
Groovy">def items = ["aa", "bb", "cc"]
// def items = ["aa", "bb", "cc"] as String[]
for (item in items) {println(item) // 打印: aa、bb、cc
}
items.each {println(it) // 打印: aa、bb、cc
}
for (index in items.indices) {println("items[$index]=${items[index]}") // 打印: items[0]=aa、items[1]=bb、items[2]=cc
}
items.eachWithIndex { item, index ->println("items[$index]=$item") // 打印: items[0]=aa、items[1]=bb、items[2]=cc
}
2.2 while
Groovy">def i = 0
while(i < 5) {println(i)i++
}
2.3 do-while
Groovy">def i = 0
do {println(i)i++
} while (i < 5)
2.4 continue
使用 continue 语句,可以跳过循环体中 continue 后面的语句,继续执行下一轮循环。
1)单层循环
Groovy">for (i in 1..5) {if (i == 3) continueprintln(i) // 打印: 1、2、4、5
}
2)多层循环
Groovy">label: for (i in 1..3) {for (j in 4..6) {if (j == 5) continue labelprintln("($i,$j)") // 打印: (1,4)、(2,4)、(3,4)}
}
说明:label 可以修改为任何符合变量命名规范的名字。
2.5 break
使用 break 语句,可以跳出循环体,继续执行循环体后面的语句。
1)单层循环
Groovy">for (i in 1..5) {if (i == 3) breakprintln(i) // 打印: 1、2
}
2)多层循环
Groovy">label: for (i in 1..3) {for (j in 4..6) {if (j == 5) break labelprintln("($i,$j)") // 打印: (1,4)}
}
说明:label 可以修改为任何符合变量命名规范的名字。