Kotlin快速入门4-控制结构

Kotlin快速入门4-控制结构_第1张图片
图片.png

控制结构

控制结构默认顺序执行。

if

if (expression) statement
if (expression) {
    statements
}

expression解析为Boolean。如果表达式为true,则将执行statement。

>>> val theQuestion = "Doctor who"
>>> val answer = "Theta Sigma"
>>> val correctAnswer = ""
>>> if (answer == correctAnswer) println("You are correct")
>>> val correctAnswer = answer
>>> if (answer == correctAnswer) println("You are correct")
You are correct

if可以做表达式使用。

fun main(args: Array) {
    val theQuestion = "Doctor who"
    val answer = "Theta Sigma"
    val correctAnswer = ""
    var message = if (answer == correctAnswer) {
        "You are correct"
    }
    else{
        "Try again"
    }
    println(message)
    val answer2 = ""
    var message2 = if (answer2 == correctAnswer) "You are correct" else "Try again"
    println(message2)
}

执行结果:

Try again
You are correct

类似Python,Kotlin没有三元运算符,但if else能实现三元运算。

Kotlin快速入门4-控制结构_第2张图片
图片.png

参考资料

  • python测试开发项目实战-目录
  • python工具书籍下载-持续更新
  • python 3.7极速入门教程 - 目录
  • 讨论qq群630011153 144081101
  • 原文地址
  • 本文涉及的python测试开发库 谢谢点赞!
  • [本文相关海量书籍下载](https://github.com/china-testing/python-api-tesing/blob/master/books.md
  • Kotlin中文英文工具书籍下载 https://www.jianshu.com/p/12b7353ca628
Kotlin快速入门4-控制结构_第3张图片
图片.png

when

Kotlin没有switch语句,但有类似的when语句。

import java.util.*

fun main(args: Array) {
    val d = Date()
    val c = Calendar.getInstance()
    val day = c.get(Calendar.DAY_OF_WEEK)
    when (day) {
        1 -> println("Sunday")
        2 -> println("Monday")
        3 -> println("Tuesday")
        4 -> println("Wednesday")
        5 -> println("Thursday")
        6 -> println("Friday")
        7 -> println("Saturday")
    }
}

与switch语句不同,匹配后不会走到下一个分支。switch也可以做表达式使用,此时尽量记得必须补充上else。

import java.util.*

fun main(args: Array) {
    val d = Date()
    val c = Calendar.getInstance()
    val day = c.get(Calendar.DAY_OF_WEEK)
    var dayOfweek = when (day) {
        1 -> "Sunday"
        2 -> "Monday"
        3 -> "Tuesday"
        4 -> "Wednesday"
        else -> "Unknown"
    }
    print(dayOfweek)
}

更复杂的实例:

fun main(args: Array) {
    print("What is the answer to life? ")
    var response:Int? = readLine()?.toInt()
    val message = when(response){
        42 -> "So long, and thanks for the all fish"
        43, 44, 45 -> "either 43,44 or 45"
        in 46 .. 100 -> "forty six to one hundred"
        else -> "Not what I'm looking for"
    }
    println(message)
}

while

fun main(args: Array) {
    var count = 0
    val finish = 5
    while (count++ < finish) {
        println("counter = $count")
    }
}

for

Kotlin的for基本上是照搬了python。

fun main(args: Array) {
    val words = "The quick brown fox".split(" ")
    for(word in words) {
        println(word)
    }
    for (i in 1..10) {
        println(i)
    }
}

执行结果

The
quick
brown
fox
1
2
3
4
5
6
7
8
9
10

你可能感兴趣的:(Kotlin快速入门4-控制结构)