Kotlin-基础语法练习二

接上一篇博客

每个 Kotlin 程序都是由两种部分组成的:

  • 1、表达式(Expressions) :用于计算值 的部分,比如 2 + 3函数调用变量赋值等,它们通常会返回一个结果。
  • 2、语句(Statements) :用于执行动作 的部分,比如 if 条件判断for 循环println() 打印语句等,它们主要是完成某种操作,而不一定返回值。

这些表达式和语句可以被组织在一起,形成所谓的 代码块(Blocks)
代码块就是一组用大括号 {} 包起来的代码,通常用在函数、控制结构(如 if、when、for)等地方。

Example:

kotlin 复制代码
fun sumOf(a:Int,b:Int): Int{
    return a+b
}

fun main(args: Array<String>){
    val a = 10
    val b = 5
    var sum = sumOf(a,b)
    var mul = a * b
    println(sum)
    println(mul)
}

Output:

kotlin 复制代码
15
50

Kotlin if expression -Kotlin if表达式:

语法规则

kotlin 复制代码
if(condition) 
       condition met! 
else 
       condition not met!

Example:

kotlin 复制代码
fun main(args: Array<String>){
    val a = 1000
    val b = 999
    var c = 1122
    var max1 = if(a > b) a else b
    var max2 = if(c > a) c else a
    println("The maximum of ${a} and ${b} is $max1 " )
    println("The maximum of ${c} and ${a} is $max2 " )
}

Output:

kotlin 复制代码
The maximum of 1000 and 999 is 1000 
The maximum of 1122 and 1000 is 1122 

Kotlin Statement

Example:

kotlin 复制代码
fun main(args: Array<String>){
    val sum: Int
    sum = 100
    
    // single statement
    println(sum)                             
    
    // Multiple statements
    println("Hello");println("Geeks!")       
}

Output:

kotlin 复制代码
100
Hello
Geeks!

Kotlin Block

Example:

kotlin 复制代码
// Start of main block or outer block
fun main(args: Array<String>) {              
    val array = intArrayOf(2, 4, 6, 8)
    
    // Start of inner block
    for (element in array) {                
       println(element)
    }                                   
    // End of inner block
    
}                                           
// End of main block

Output:

kotlin 复制代码
2
4
6
8

Control Flow-控制语句

Kotlin if-else expression

  • if statement

    • 语法规则
    kotlin 复制代码
    	if(condition) {
    	
    	       // code to run if condition is true
    	}
    • 流程图

      Example:
    kotlin 复制代码
    fun main(args: Array<String>) {
        var a = 3
        if(a > 0){
            print("Yes,number is positive")
        }
    }

    Output:

    kotlin 复制代码
    Yes, number is positive
  • if-else statement

    • 语法规则
    kotlin 复制代码
    if(condition) { 
            // code to run if condition is true
    }
    else { 
           // code to run if condition is false
    }
    • 流程图

      Example:

      kotlin 复制代码
      fun main(args: Array<String>) {
          var a = 5
          var b = 10
          if(a > b){
              print("Number 5 is larger than 10")
          }
          else{
              println("Number 10 is larger than 5")
          }
      }

      Output:

      kotlin 复制代码
      	Number 10 is larger than 5

      Example:

      kotlin 复制代码
      fun main(args: Array<String>) {
          var a = 50
          var b = 40
      
          // here if-else returns a value which 
          // is to be stored in max variable
          var max = if(a > b){                  
              print("Greater number is: ")
              a
          }
          else{
              print("Greater number is:")
              b
          }
          print(max)
      }

      Output:

      kotlin 复制代码
      Greater number is: 50
  • if-else-if ladder expression

    • 语法规则

      kotlin 复制代码
      if(Firstcondition) { 
          // code to run if condition is true
      }
      else if(Secondcondition) {
          // code to run if condition is true
      }
      else{
      }
    • 流程图

      Example:

      kotlin 复制代码
      import java.util.Scanner
      
      fun main(args: Array<String>) {
         
          // create an object for scanner class
          val reader = Scanner(System.`in`)       
          print("Enter any number: ")
      
          // read the next Integer value
          var num = reader.nextInt()             
          var result  = if ( num > 0){
              "$num is positive number"
          }
          else if( num < 0){
              "$num is negative number"
          }
          else{
              "$num is equal to zero"
          }
          println(result)
      
      }

      Output:

      kotlin 复制代码
      Enter any number: 12
      12 is positive number
      
      Enter any number: -11
      -11 is negative number
      
      Enter any number: 0
      0 is zero
  • nested if expression

    • 语法规则
    kotlin 复制代码
    if(condition1){
                // code 1
          if(condition2){
                      // code2
          }
    }
    • 流程图

      Example:

      kotlin 复制代码
      import java.util.Scanner
      
      fun main(args: Array<String>) {
       
          // create an object for scanner class
          val reader = Scanner(System.`in`)       
          print("Enter three numbers: ")
      
          var num1 = reader.nextInt()
          var num2 = reader.nextInt()
          var num3 = reader.nextInt()
      
          var max  = if ( num1 > num2) {
              if (num1 > num3) {
                  "$num1 is the largest number"
              }
              else {
                  "$num3 is the largest number"
              }
          }
          else if( num2 > num3){
              "$num2 is the largest number"
          }
          else{
              "$num3 is the largest number"
          }
          println(max)
      
      }

      Output:

      kotlin 复制代码
      Enter three numbers: 123 231 321
      321 is the largest number

Kotlin while loop

  • 语法规则

    kotlin 复制代码
    while(condition) {
    
               // code to run
    }
  • 流程图

    Example:

    kotlin 复制代码
    fun main(args: Array<String>) {
        var number = 1
    
        while(number <= 10) {
            println(number)
            number++;
        }
    }

    Output:

    kotlin 复制代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

    Example:

    kotlin 复制代码
    fun main(args: Array<String>) {
        var names = arrayOf("Praveen","Gaurav","Akash","Sidhant","Abhi","Mayank")
        var index = 0
    
        while(index < names.size) {
            println(names[index])
            index++
        }
    }

    Output:

    kotlin 复制代码
    	Praveen
    	Gaurav
    	Akash
    	Sidhant
    	Abhi
    	Mayank

Kotlin do-while loop

  • 语法规则

    kotlin 复制代码
    do {
          // code to run
    }
    while(condition)
  • 流程图

    Example:

    kotlin 复制代码
    fun main(args: Array<String>) {
        var number = 6
        var factorial = 1
        do {
            factorial *= number
            number--
        }while(number > 0)
        println("Factorial of 6 is $factorial")
    }

    Output:

    kotlin 复制代码
    Factorial of 6 is 720

Kotlin for loop

  • 语法规则

    kotlin 复制代码
    for(item in collection) {
           // code to execute
    }
  • Range Using a for loop-使用for循环

    Example1:

    kotlin 复制代码
    fun main(args: Array<String>)
    {
        for (i in 1..6) {
            print("$i ")
        }
    }
    kotlin 复制代码
    1 2 3 4 5 6

    Example2:

    kotlin 复制代码
    fun main(args: Array<String>)
    {
        for (i in 1..10 step 3) {
            print("$i ")
        }
    }
    kotlin 复制代码
    1 4 7 10

    Example3:

    kotlin 复制代码
    fun main(args: Array<String>)
    {
    	    for (i in 5..1) {
    	        print("$i ")
    	    }
    	    println("It prints nothing")
    }
    kotlin 复制代码
    It prints nothing

    Example4:

    kotlin 复制代码
    fun main(args: Array<String>)
    {
        for (i in 5 downTo 1) {
            print("$i ")
        }
    }
    kotlin 复制代码
    5 4 3 2 1

    Example5:

    kotlin 复制代码
    fun main(args: Array<String>)
    {
        for (i in 10 downTo 1 step 3) {
            print("$i ")
        }
    }
    kotlin 复制代码
    10 7 4 1
  • Array using for loop-使用for循环的数组
    Example1:

    kotlin 复制代码
    fun main(args: Array<String>) {
        var numbers = arrayOf(1,2,3,4,5,6,7,8,9,10)
    
        for (num in numbers){
            if(num%2 == 0){
                print("$num ")
            }
        }
    }
    kotlin 复制代码
    2 4 6 8 10

    Example2:

    kotlin 复制代码
    fun main(args: Array<String>) {
    	
    	    var planets = arrayOf("Earth", "Mars", "Venus", "Jupiter", "Saturn")
    	
    	    for (i in planets.indices) {
    	        println(planets[i])
    	    }
    	}
    kotlin 复制代码
    Earth
    Mars
    Venus
    Jupiter
    Saturn

    Example3:

    kotlin 复制代码
    fun main(args: Array<String>) {
        var planets = arrayOf("Earth", "Mars", "Venus", "Jupiter", "Saturn")
    
        for ((index,value) in planets.withIndex()) {
            println("Element at $index th index is $value")
        }
    }
    	
    kotlin 复制代码
    Element at 0 th index is Earth
    Element at 1 th index is Mars
    Element at 2 th index is Venus
    Element at 3 th index is Jupiter
    Element at 4 th index is Saturn
  • String using a for loop-使用for循环的字符串
    Example1:

    kotlin 复制代码
    fun main(args: Array<String>) {
        var name = "Geeks"
        var name2 = "forGeeks"
        
        // traversing string without using index property
        for (alphabet in name)   print("$alphabet ")
    
        // traversing string with using index property
        for (i in name2.indices) print(name2[i]+" ")
        println(" ")
        
        // traversing string using withIndex() library function
        for ((index,value) in name.withIndex())
        println("Element at $index th index is $value")
    }

    Output:

    kotlin 复制代码
    G e e k s f o r G e e k s  
    Element at 0 th index is G
    Element at 1 th index is e
    Element at 2 th index is e
    Element at 3 th index is k
    Element at 4 th index is s
  • collection using for loop-使用for循环的集合
    Example:

    kotlin 复制代码
    fun main(args: Array<String>) {
    
        // read only, fix-size
        var collection = listOf(1,2,3,"listOf", "mapOf", "setOf")
    
        for (element in collection) {
            println(element)
        }
    }

    Output:

    kotlin 复制代码
    1
    2
    3
    listOf
    mapOf
    setOf

Kotlin when expression

  • when as a statement
    Example1:

    kotlin 复制代码
    fun main (args : Array<String>) {
    
        print("Enter the name of heavenly body: ")
        var name= readLine()!!.toString()
        
        when(name) {
        
            "Sun" -> print("Sun is a Star")
            "Moon" -> print("Moon is a Satellite")
            "Earth" -> print("Earth is a planet")
            else -> print("I don't know anything about it")
        }
    }
    kotlin 复制代码
    Enter the name of heavenly body: Sun
    Sun is a Star
    Enter the name of heavenly body: Mars
    I don't know anything about it

    Example2:

    kotlin 复制代码
    fun main (args : Array<String>) {
    
        print("Enter the name of heavenly body: ")
        var name= readLine()!!.toString()
        
        when(name) {
        
            "Sun" -> print("Sun is a Star")
            "Moon" -> print("Moon is a Satellite")
            "Earth" -> print("Earth is a planet")
        }
    }
    kotlin 复制代码
    Enter the name of heavenly body: Mars
    Process finished with exit code 0
  • when as an expression

    Example1:
    注意 作为表达式else不能缺失,否则会报错:Kotlin: 'when' expression must be exhaustive, add necessary 'else' branch

    kotlin 复制代码
    fun main(args : Array<String>) {
    
        print("Enter number of the Month: ")
        var monthOfYear  = readLine()!!.toInt()
        
        var month= when(monthOfYear) {
        
            1->"January"
            2->"February"
            3->"March"
            4->"April"
            5->"May"
            6->"June"
            7->"July"
            8->"August"
            9->"September"
            10->"October"
            11->"November"
            12->"December"
            else-> "Not a month of year"
        }
        
        print(month)
    }
    kotlin 复制代码
    Enter number of the Month: 8
    August

    Example2:

    kotlin 复制代码
    fun main (args :Array<String>) {
    
        print("Enter name of the planet: ")
        var name=readLine()!!.toString()
        
        when(name) {
        
            "Mercury","Earth","Mars","Jupiter"
                ,"Neptune","Saturn","Venus","Uranus" -> print("This is a planet")
            else -> print("This not a planet")
        }
    }

    Output:

    kotlin 复制代码
    Enter name of the planet: Earth
    This is a Planet

    Example3:

    kotlin 复制代码
    fun main (args:Array<String>) {
    
        print("Enter the month number of year: ")
        var num= readLine()!!.toInt()
        
        when(num) {
        
            in 1..3 -> print("Spring season")
            in 4..6 -> print("Summer season")
            in 7..8 -> print("Rainy season")
            in 9..10 -> print("Autumn season")
            in 11..12 -> print("Winter season")
            !in 1..12 -> print("Enter valid month of the year")
        }
    }
    kotlin 复制代码
    Enter the month number of year: 5
    Summer season
    Enter the month number of year: 14
    Enter valid month of the year

    Example4:

    kotlin 复制代码
    fun main(args: Array<String>) {
    
        var num: Any = "xx"
        
        when(num){
        
            is Int -> println("It is an Integer")
            is String -> println("It is a String")
            is Double -> println("It is a Double")
        }
    }

    Output:

    kotlin 复制代码
    It is a String

    Example5:

    kotlin 复制代码
    // returns true if x is odd
    	fun isOdd(x: Int) = x % 2 != 0
    	// returns true if x is evevn
    	fun isEven(x: Int) = x % 2 == 0
    	
    	fun main(args: Array<String>) {
    	
    	    var num = 8
    	    
    	    when{
    	    
    	        isOdd(num) ->println("Odd")
    	        isEven(num) -> println("Even")
    	        else -> println("Neither even nor odd")
    	    }
    	}

    Output:

    kotlin 复制代码
    Even

    Example6:

    kotlin 复制代码
    // Return s True if company start with "xx"
    fun hasPrefix(company: Any):Boolean{
    return when (company) {
        is String -> company.startsWith("xx")
        else -> false
      }
    }
    
    fun main(args: Array<String>) {
    
        var company = "xx is a computer science portal"
        var result = hasPrefix(company)
        
        if(result) {
        
            println("Yes, string started with xx")
        }
        else {
        
            println("No, String does not started with xx")
        }
    }

    Output:

    kotlin 复制代码
    Yes, string started with xx