kotlin 循环

In this tutorial, we’ll be covering an important aspect of programming, namely Kotlin Control Flow statements.
We’ll look into the if else, range, for, while, when repeat, continue break keywords that form the core of any programming language code.

在本教程中,我们将介绍编程的一个重要方面,即Kotlin Control Flow语句。
我们会调查的if elserangeforwhilewhen repeatcontinue break形成的任何编程语言代码的核心关键词。

Let’s get started with each of these operators by creating a Kotlin project in our IntelliJ Idea.

通过在IntelliJ Idea中创建一个Kotlin项目,让我们开始与每个操作员一起开始。

Kotlin (Kotlin if else)

In Kotlin, if else operators behave the same way as it does in Java.
if executes a certain section of code if the condition is true. It can have an optional else clause.
Following code is from the Test.kt class in our IntelliJ Project.

在Kotlin中,运算符的行为方式与Java中相同。
if条件为真, if执行代码的特定部分。 它可以具有可选的else子句。
以下代码来自IntelliJ项目中的Test.kt类。

fun main(args: Array<String>) {var a = 4var b = 5var max = aif (a < b)max = bif (a > b) {max = a} else {max = b}println("a is $a b is $b max is $max")
}

In Kotlin, if else can be used as expressions too in order to return a value.

在Kotlin中,是否还可以将其用作表达式以返回值。

a = 5b = 4//if else returns a value in Kotlinmax = if (a > b) a else bprint("a is $a b is $b max is $max")

This way Kotlin eliminates the use of ternary operator by using if else as expressions.

这样Kotlin通过使用if else作为表达式来消除三元运算符的使用。

In another view, the last statement present in an if-else condition is returned as the value.
The below example demonstrates the same.

在另一个视图中,以if-else条件存在的最后一条语句作为值返回。
下面的示例演示了相同的内容。

max = if(a>b){println("a is greater than b")println("max is a")a}else{println("b is greater than a")println("max is b")b}println("max is $max")//Following is printed on the log console.a is greater than b
max is a
max is 5

Kotlin for循环 (Kotlin for loop)

The syntax of for loop in Kotlin is different from the one in Java.
For loop is used to iterate over a list of items based on certain conditions.
Following is the implementation of for loops in Kotlin to print numbers 0 to 5.

Kotlin中的for循环语法与Java中的语法不同。
For循环用于根据特定条件遍历项目列表。
以下是Kotlin中for循环的实现,以打印数字0到5。

for (i in 0..5) {print(i)
}

Few inferences from the above syntax are listed below:

下面列出了从上述语法中得出的少量推论:

  • Kotlin saves us from declaring the type of iKotlin使我们免于声明i的类型
  • The lower and upper (including) limits are be defined on either side of .. operator.上下限(包括)在..运算符的两侧定义。
  • in keyword is used to iterate over the range.in关键字用于迭代范围。

Another case for you, where we iterate over an array using for-in loop.

您的另一种情况是,我们使用for-in循环遍历数组。

val items = listOf(10, 20, 30, 40)for (i in items)println("value is $i")//Following is printed to the console.
value is 10
value is 20
value is 30
value is 40

To print the index of the elements, we invoke the indices method on the arrays.

要打印元素的索引,我们在数组上调用indices方法。

val items = listOf(10, 20, 30, 40)for (i in items.indices)println("value is $i")//Following is printed to the console:
value is 0
value is 1
value is 2
value is 3

To access the index and value of the element in the iteration, withIndex() function is used.

要访问迭代中元素的索引和值,请使用withIndex()函数。

val items = listOf(10, 20, 30, 40)for ((i,e) in items.withIndex())println("the index is $i and the element is $e")//Following is printed on the console:
the index is 0 and the element is 10
the index is 1 and the element is 20
the index is 2 and the element is 30
the index is 3 and the element is 40

Kotlin forEach循环 (Kotlin forEach loop)

ForEach loop repeats a set of statements for each iterable as shown below.

ForEach循环为每个可迭代项重复一组语句,如下所示。

(2..5).forEach{println(it)}//or(2..5).forEach{i ->  println(i)}//Following is printed on the console:
2
3
4
5

it is the default iterable variable that holds the value of the current iterator.
In the second case, we’d use our custom variable.

it是默认的可迭代变量,用于保存当前迭代器的值。
在第二种情况下,我们将使用自定义变量。

Kotlin山脉 (Kotlin Range)

We’ve seen in the above sections that .. operators represents a range.

在以上各节中,我们已经看到..运算符代表一个范围。

(2..4).forEach{println(it)}//Following gets printed on the console:
2
3
4

To check whether an element exists or doesn’t exist in a range we use the in and !in keywords as shown below.

要检查某个元素在范围内是否存在,我们使用in!in关键字,如下所示。

var x = 5if(x in 1..10){print("x exists in range") //this gets printed}else{print("x does not exist in range")}x = 15if(x !in 1..10){print("x does not exist in range") //this gets printed}else{print("x does exist in range") }

And the following should work the same way. Right?

并且以下应该以相同的方式工作。 对?

var x = 5if(x in 10..1){print("x exists in range")}else{print("x does not exist in range") //Ironically, this gets printed.}for (i in 5..0)
print(i) //prints nothing

NO.
The Range .. can’t be used in the reverse order.
This is where we use the downTo keyword.

没有。
范围..不能以相反的顺序使用。
这是我们使用downTo关键字的地方。

The below code would work:

下面的代码将起作用:

var x = 5if(x in 10 downTo 1){print("x exists in range") //this gets printed}else{print("x does not exist in range")}for (i in 5 downTo 0)
print(i) //543210

To exclude the last element from the range we use the keyword until.

为了从范围中排除最后一个元素,我们使用关键字until

for (i in 1 until 4) {print(i)
}
//prints 123

To traverse the range in steps we use the keyword step.

要逐步遍历范围,我们使用关键字step

for (i in 1..5 step 3) print(i) // prints 14for (i in 4 downTo 1 step 2) print(i) // prints 42

Kotlin while循环 (Kotlin while loop)

while and do-while loops in Kotlin behave the same way as they do in Java.

Kotlin中的whiledo-while循环的行为与Java中的相同。

var i = 0do {i+=5println("Value of i is $i") //prints 5} while(i<1)i=0while(i<=5) {print(i)i++}//prints 012345

Kotlin打破并继续 (Kotlin break and continue)

break is used to exit the loop there and then.
continue is used to go to the next iteration of the loop.
Kotlin gives us the luxury to attach a label to the break and continue statements to indicate the loop on which their actions are triggered as shown below.

break用于退出循环,然后再退出。
continue用于转到循环的下一个迭代。
Kotlin让我们可以在中断处贴上标签并继续声明,以指示触发其操作的循环,如下所示。

customLabel@ for(y in 10 downTo 5) { // applying the custom labelif(y == 6) {print("x is $y breaking here")break@customLabel //specifing the label} else {print("continue to next iteration")continue@customLabel}}

Kotlin重覆以及何时 (Kotlin repeat and when)

repeat allows us to execute the statements in the loop N number of times(where N is the number specified as the argument).
The following code snippet would print the group of statements 3 times.

repeat允许我们在循环中执行N次语句(其中N是指定为参数的数字)。
以下代码段将打印该语句组3次。

repeat(3) {println("Hello World!")println("Kotlin Control Flow")}

when in Kotlin is equivalent to switch in other languages, though with a different syntax and more power!
A basic example of when operator is given below.

when在Kotlin相当于switch的其他语言,但有一个不同的语法和更多的权力!
下面给出了when运算符的基本示例。

var num = 10when (num) {0 -> print("value is 0")5 -> print("value is 5")else -> {print("value is neither 0 nor 5") //this gets printed.}}

The when operator matches the argument with all the branches. If it matches with none, the else statement is printed. The else statement is similar to default in switch.
when operator can be used to return values too, similar to if else.

when运算符将参数与所有分支匹配。 如果不匹配,则打印else语句。 else语句与switch中的default相似。
when运算符也可以用于返回值,类似于if。

var valueLessThan100 = when(101){in 1 until 101 -> trueelse -> {false}}print(valueLessThan100) //false

Going further, we can use Any type to check the branch as shown below.

更进一步,我们可以使用Any类型来检查分支,如下所示。

fun month(month: Any)
{when(month){1 -> print("January")2-> print("February")"MAR" -> print("March")else -> { print("Any other month or it is invalid. when operator takes generic type Any") }}
}month(1) //"January"
month("MAR") //"March"

Kotlin控制流语句示例 (Kotlin Control Flow Statements Example)

Summing up the control flow in our Kotlin project, this is how our Kotlin class file looks:

总结我们Kotlin项目中的控制流,这就是我们Kotlin类文件的外观:

fun main(args: Array<String>) {var a = 4var b = 5var max = aif (a < b)max = bif (a > b) {max = a} else {max = b}println("a is $a b is $b max is $max")a = 5b = 4//if else returns a value in Kotlinmax = if (a > b) a else bprintln("a is $a b is $b max is $max")max = if(a>b){println("a is greater than b")println("max is a")a}else{println("b is greater than a")println("max is b")b}println("max is $max")val items = listOf(10, 20, 30, 40)for ((i,e) in items.withIndex())println("index is $i and element is $e")(2..5).forEach{print(it)}var x = 5if(x in 10 downTo 1){print("x exists in range")}else{print("x does not exist in range")}var i = 0do {i+=5println("Value of i is $i")} while(i<1)i=0while(i<=5) {print(i)i++}customLabel@ for(y in 10 downTo 5) { // appling the custom labelif(y == 6) {print("x is $y breaking here")break@customLabel //specifing the label} else {print("continue to next iteration")continue@customLabel}}repeat(3) {println("Hello World!")println("Kotlin Control Flow")}var num = 10when (num) {0 -> print("value is 0")5 -> print("value is 5")else -> {print("value is neither 0 nor 5")}}var valueLessThan100 = when(101){in 1 until 101 -> trueelse -> {false}}print(valueLessThan100) //falsemonth(1)month("MAR")}fun month(month: Any)
{when(month){1 -> print("January")2-> print("February")"MAR" -> print("March")else -> { print("Any other month or it is invalid. when operator takes generic type Any") }}
}

This brings an end to this tutorial
References: Kotlin Official Doc, Range API Doc

本教程到此结束
参考: Kotlin官方文档 , Range API文档

翻译自: https://www.journaldev.com/18483/kotlin-control-flow-if-else-for-while-range

kotlin 循环

kotlin 循环_Kotlin控制流–否则,用于循环,同时,范围相关推荐

  1. java for if嵌套_for循环嵌套if语句怎么循环-for 循环嵌套if语句-for循环语句嵌套使用的实例...

    for循环嵌套里怎幺用if语句控制外循环? 修改如下 int Su(int x) { int i,j; for(i=x;i>=2;i--) { for(j=2;j<=i>=i> ...

  2. 武汉大学提出ARGAN:注意力循环生成对抗模型用于检测、去除图像阴影 | ICCV 2019...

    作者 | 王红成 出品|AI科技大本营(ID:rgznai100) [导读]如何去除一张图像中的阴影部分?在ICCV 2019会上,武汉大学的一篇论文针对这一问题提出了一种用于阴影检测和去除的注意循环 ...

  3. 武汉大学提出ARGAN:注意力循环生成对抗模型用于检测、去除图像阴影 | ICCV 2019

    [导读]如何去除一张图像中的阴影部分?在ICCV 2019会上,武汉大学的一篇论文针对这一问题提出了一种用于阴影检测和去除的注意循环生成对抗网络--ARGAN.论文中通过生成一张更加准确的注意力图,用 ...

  4. python中用于循环结构的关键字_详解Python的循环结构知识点

    循环结构的应用场景 如果在程序中我们需要重复的执行某条或某些指令,例如用程序控制机器人踢足球,如果机器人持球而且还没有进入射门范围,那么我们就要一直发出让机器人向球门方向奔跑的指令.当然你可能已经注意 ...

  5. java跳转kotlin页面_Kotlin:return与跳转

    Kotlin有两种跳转:循环跳转(break与continue)和返回跳转(return). Label label语法:labelName@ label可以放在任何表达式之前,用来标记表达式.如lo ...

  6. for循环递减_讲讲关于循环的那些事

    每个人一生中都至少应该获得一次全场起立鼓掌的机会,因为我们都曾胜过这个世界.-R.J.帕拉西奥<奇迹男孩> 导言:希腊哲学家Zeno曾经说"运动是不可能的.由于运动的物体在到达目 ...

  7. python当型循环_对python while循环和双重循环的实例详解

    废话不多说,直接上代码吧! #python中,while语句用于循环执行程序,即在某个条件下,循环执行某段程序,以处理需要重复处理的相同任务. #while是"当型"循环结构. i ...

  8. c语言for循环加法,BigDecimal 在for循环中相加注意事项

    public static void main(String[] args) { BigDecimal bigDecimal = new BigDecimal(1); for (int i = 0; ...

  9. pythonwhile循环结束语句_Python while循环语句

    Python While 循环语句 Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务.其基本形式为: while判断条件:执行语句- ...

最新文章

  1. ruby(wrong number of arguments (1 for 2) )
  2. phpstudy(小皮面板)Deepin安装脚本
  3. bash: ./make_ext4fs: No such file or directory 错误解决方法
  4. SQL Server 2008 R2的发布订阅配置实践
  5. HH SaaS电商系统的商品系统设计
  6. python switch高效替代_Python中用什么代替switch
  7. springboot 循环引用问题
  8. 省赛模拟一 又一道简单题
  9. 201521145048 《Java程序设计》第3周学习总结
  10. 使用线程池管理线程!
  11. C++ const修饰指针变量的位置不同代表的意义
  12. 高级商务办公软件应用【4】
  13. IAR软件的使用讲解
  14. java基础-面向对象
  15. 【大牛分享】人机工程简史
  16. 抚琴成一快-电吉他内录(Zoom G3为例)
  17. python获取本机IP
  18. html访问域名跳转,根据访问的域名跳转到指定目录的代码
  19. MATLAB算法实战应用案例精讲-【智能优化算法】黑寡妇算法-BWO(附matlab代码)
  20. 装X指南之用 Xposed 把某宝资产改成100w

热门文章

  1. 性能优化–查找和解决僵尸对象
  2. MyEclipse7.0及JDK1.6.0的安装及配置过程(修改)
  3. [转载] Python 继承
  4. [转载] Java基础知识面试题(2020最新版)
  5. [转载] python 命名空间
  6. Xshell连接VMware的linux系统
  7. 百度前端技术学院-精选笔记-1 HTML学习笔记
  8. 1002: Prime Path
  9. 【ROS学习笔记】(六)客户端Client的编程实现
  10. 局域网ip冲突检测工具_“网络工程师培训”基础教程五:局域网