美文网首页我爱编程
2、Kotlin基础(字符串)

2、Kotlin基础(字符串)

作者: 北方素素 | 来源:发表于2018-06-20 15:13 被阅读0次

    字符串使用“”包围起来

    使用+进行字符串拼接

    使用$来进行数字输出

    val fish = 5

    "I have $fish"

    还可以在字符串中进行数字的数学运算($和{}):

    val fish = 5

    val plants = 12

    "I have ${fish+plants} fish and plants"

    布尔运算符与其它语言一样,例如==,!=等

    接下来是判断(if-else)

    val numOfFish=30

    val numOfPlants=23

    if (numOfFish>numOfPlants) println("good ratio")

    else

        println("unhealthy ratio")

    下面是范围判断(..)

    val fish=50

    if (fish in 1..100) println(fish)

    下面是和其它语言的switch一样的when:

    val numOfFish = 50

    when(numOfFish){

        0->println("empty tank")

        50->println("full tank")

        else->println("perfect")

    }

    有一道练习题:

    var welcomeMessage ="Hello and welcome to Kotlin"

    when (welcomeMessage.length) {

    0->println("Nothing to say?")

    in1..50->println("Perfect")

    else->println("Too long!")

    }

    结果应该是:Perfect

    习题1:

    Create three String variables fortrout,haddock, andsnapper.

    Use a String template to print whether you do or don't like to eat these kinds of fish.

    官方答案是:

    val trout ="trout"

    var haddock ="haddock"

    var snapper ="snapper"

    println("I like to eat $trout and $snapper, but not a big fan of $haddock.")

    习题2:

    whenstatements in Kotlin are likecaseorswitchstatements in other languages.

    Create awhenstatement with three comparisons:

    If the length of thefishNameis 0, print an error message.

    If the length is in the range of 3...12, print "Good fish name".

    If it's anything else, print "OK fish name".

    官方答案是:

    when(fishName.length){

    0-> println("Fish name cannot be empty")

    in 3..12-> println("Good fish name")

    else->println("OK fish name")

    }

    相关文章

      网友评论

        本文标题:2、Kotlin基础(字符串)

        本文链接:https://www.haomeiwen.com/subject/ldhxyftx.html