def x =10if(x >0){
println "x is positive"}elseif(x <0){
println "x is negative"}else{
println "x is zero"}// log
x is positive
// 三元运算符def result =(x >0)?"positive":"non-positive"
println result // 输出 "positive"// log"positive"
分支语句
// 分支语句判断数据类型defcheckType(value){switch(value){case Integer:
println "The value is an Integer."breakcase Double:
println "The value is a Double."breakcase Float:
println "The value is a Float."breakcase String:
println "The value is a String."breakcase List:
println "The value is a List."breakcase Map:
println "The value is a Map."breakcase Boolean:
println "The value is a Boolean."breakdefault:
println "The value is of an unknown type."break}}// 测试不同类型的数据checkType(10)// IntegercheckType(20.1d)// DoublecheckType(20.5f)// FloatcheckType("Groovy")// StringcheckType([1,2,3])// ListcheckType([key:'value'])// MapcheckType(true)// BooleancheckType(newDate())// Unknown type// log
The value is an Integer.
The value is a Double.
The value is a Float.
The value is a String.
The value is a List.
The value is a Map.
The value is a Boolean.
The value is of an unknown type.
循环语句
// while循环def count =0while(count <5){
println "Count is $count"
count++}// do-while 循环def count =0do{
println "Count is $count"
count++}while(count <5)// for循环def count =0for(int i =0; i <5; i++){
println "Count is $count"}// log
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4// for-in循环def list =[1,2,3,4,5]for(item in list){
println "Item: $item"}// log
Item:1
Item:2
Item:3
Item:4
Item:5
异常处理
try{def result =10/0}catch(ArithmeticException e){
println "Caught an arithmetic exception: ${e.message}"}finally{
println "This block is always executed"}// log
Caught an arithmetic exception: Division by zero
This block is always executed