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

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.

kotlin control flow, kotlin if else, kotlin for loop

通过在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 = 4
    var b = 5

    var max = a
    if (a < b)
        max = b

    if (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 = 5
    b = 4


    //if else returns a value in Kotlin
    max = if (a > b) a else b

    print("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")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值