Groovy -> Groovy 流程控制语句

判断语句

def x = 10

if (x > 0) {
    println "x is positive"
} else if (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"

分支语句

// 分支语句判断数据类型
def checkType(value) {
    switch (value) {
        case Integer:
            println "The value is an Integer."
            break
        case Double:
            println "The value is a Double."
            break
        case Float:
            println "The value is a Float."
            break
        case String:
            println "The value is a String."
            break
        case List:
            println "The value is a List."
            break
        case Map:
            println "The value is a Map."
            break
        case Boolean:
            println "The value is a Boolean."
            break
        default:
            println "The value is of an unknown type."
            break
    }
}

// 测试不同类型的数据
checkType(10)          // Integer
checkType(20.1d)        // Double
checkType(20.5f)        // Float
checkType("Groovy")    // String
checkType([1, 2, 3])            // List
checkType([key: 'value']) // Map
checkType(true)        // Boolean
checkType(new Date())  // 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 = 0
while (count < 5) {
    println "Count is $count"
    count++
}

// do-while 循环
def count = 0

do {
    println "Count is $count"
    count++
} while (count < 5)

// for循环
def count = 0

for (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

你可能感兴趣的:(Groovy,开发语言,gradle,idea)