Kotlin 简明教程
Kotlin - While Loop
只要指定条件 true ,Kotlin while 循环就会一直执行其主体。
Kotlin while loop executes its body continuously as long as the specified condition is true.
Syntax
Kotlin while 循环的语法如下:
The syntax of the Kotlin while loop is as follows:
while (condition) {
// body of the loop
}
当 Kotlin 程序到达 while 循环时,它会检查给定的 condition ,如果给定条件为 true ,则执行循环的主体,否则,程序开始执行 while 循环的主体后面的代码。
When Kotlin program reaches the while loop, it checks the given condition, if given condition is true then body of the loop gets executed, otherwise program starts executing code available after the body of the while loop .
Example
以下是一个示例,在这个示例中,只要计数器变量 i 大于 0,while 循环就会继续执行循环的主体:
Following is an example where the while loop continue executing the body of the loop as long as the counter variable i is greater than 0:
fun main(args: Array<String>) {
var i = 5;
while (i > 0) {
println(i)
i--
}
}
当你运行上述 Kotlin 程序时,它将生成以下输出:
When you run the above Kotlin program, it will generate the following output:
5
4
3
2
1
Kotlin do…while Loop
do..while 与 while 循环类似,不同的是,在检查条件是否为真之前,此循环将执行一次代码块,然后只要条件为真,就会重复该循环。
The do..while is similar to the while loop with a difference that the this loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
Syntax
Kotlin do…while 循环的语法如下:
The syntax of the Kotlin do…while loop is as follows:
do{
// body of the loop
}while( condition )
当 Kotlin 程序到达 do…while 循环时,它直接进入循环主体并在检查给定条件之前执行可用代码。如果它发现给定条件为真,则它会重复执行循环主体,并持续到给定条件为真为止。
When Kotlin program reaches the do…while loop, it directly enters the body of the loop and executes the available code before it checks for the given condition. If it finds given condition is true, then it repeats the execution of the loop body and continue as long as the given condition is true.
Example
以下是一个示例,在这个示例中,只要计数器变量 i 大于 0,do…while 循环就会继续执行循环的主体:
Following is an example where the do…while loop continue executing the body of the loop as long as the counter variable i is greater than 0:
fun main(args: Array<String>) {
var i = 5;
do{
println(i)
i--
}while(i > 0)
}
当你运行上述 Kotlin 程序时,它将生成以下输出:
When you run the above Kotlin program, it will generate the following output:
5
4
3
2
1