当前位置: 首页 > news >正文

Kotlin-基础语法练习二

接上一篇博客

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

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

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

Example:

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

Output:

15
50

Kotlin if expression -Kotlin if表达式:

语法规则

if(condition) condition met! 
else condition not met!

在这里插入图片描述

Example:

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

Output:

The maximum of 1000 and 999 is 1000 
The maximum of 1122 and 1000 is 1122 

Kotlin Statement

Example:

fun main(args: Array<String>){val sum: Intsum = 100// single statementprintln(sum)                             // Multiple statementsprintln("Hello");println("Geeks!")       
}

Output:

100
Hello
Geeks!

Kotlin Block

Example:

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

Output:

2
4
6
8

Control Flow-控制语句

Kotlin if-else expression

  • if statement

    • 语法规则
    	if(condition) {// code to run if condition is true}
    
    • 流程图
      在这里插入图片描述
      Example:
    fun main(args: Array<String>) {var a = 3if(a > 0){print("Yes,number is positive")}
    }
    

    Output:

    Yes, number is positive
    
  • if-else statement

    • 语法规则
    if(condition) { // code to run if condition is true
    }
    else { // code to run if condition is false
    }
    
    • 流程图
      在这里插入图片描述
      Example:

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

      Output:

      	Number 10 is larger than 5
      

      Example:

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

      Output:

      Greater number is: 50
      
  • if-else-if ladder expression

    • 语法规则

      if(Firstcondition) { // code to run if condition is true
      }
      else if(Secondcondition) {// code to run if condition is true
      }
      else{
      }
      
    • 流程图
      在这里插入图片描述
      Example:

      import java.util.Scannerfun main(args: Array<String>) {// create an object for scanner classval reader = Scanner(System.`in`)       print("Enter any number: ")// read the next Integer valuevar 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:

      Enter any number: 12
      12 is positive numberEnter any number: -11
      -11 is negative numberEnter any number: 0
      0 is zero
      
  • nested if expression

    • 语法规则
    if(condition1){// code 1if(condition2){// code2}
    }
    
    • 流程图
      在这里插入图片描述
      Example:

      import java.util.Scannerfun main(args: Array<String>) {// create an object for scanner classval 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:

      Enter three numbers: 123 231 321
      321 is the largest number
      

Kotlin while loop

  • 语法规则

    while(condition) {// code to run
    }
    
  • 流程图
    -
    Example:

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

    Output:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    

    Example:

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

    Output:

    	PraveenGauravAkashSidhantAbhiMayank
    

Kotlin do-while loop

  • 语法规则

    do {// code to run
    }
    while(condition)
    
  • 流程图
    在这里插入图片描述
    Example:

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

    Output:

    Factorial of 6 is 720
    

Kotlin for loop

  • 语法规则

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

    Example1:

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

    Example2:

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

    Example3:

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

    Example4:

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

    Example5:

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

    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 ")}}
    }
    
    2 4 6 8 10
    

    Example2:

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

    Example3:

    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")}
    }
    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:

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

    Output:

    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:

    fun main(args: Array<String>) {// read only, fix-sizevar collection = listOf(1,2,3,"listOf", "mapOf", "setOf")for (element in collection) {println(element)}
    }
    

    Output:

    1
    2
    3
    listOf
    mapOf
    setOf
    

Kotlin when expression

  • when as a statement
    Example1:

    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")}
    }
    
    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:

    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")}
    }
    
    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

    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)
    }
    
    Enter number of the Month: 8
    August
    

    Example2:

    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:

    Enter name of the planet: Earth
    This is a Planet
    

    Example3:

    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")}
    }
    
    Enter the month number of year: 5
    Summer season
    Enter the month number of year: 14
    Enter valid month of the year
    

    Example4:

    fun main(args: Array<String>) {var num: Any = "GeeksforGeeks"when(num){is Int -> println("It is an Integer")is String -> println("It is a String")is Double -> println("It is a Double")}
    }
    

    Output:

    It is a String
    

    Example5:

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

    Output:

    Even
    

    Example6:

    // Return s True if company start with "GeeksforGeeks"
    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:

    Yes, string started with xx
    
http://www.dtcms.com/a/341957.html

相关文章:

  • Android面试指南(四)
  • [新启航]机械深孔加工质控:新启航方案用激光频率梳破解 130mm 深度遮挡瓶颈
  • 闲聊汽车芯片的信息安全需求和功能
  • C# NX二次开发:反向控件和组控件详解
  • 智慧巡检新标杆:智能移动机器人——电力行业的守护者
  • 【数据结构】树与二叉树:结构、性质与存储
  • 解码欧洲宠物经济蓝海:跨境电商突围的战略逻辑与运营范式
  • Vue2+Vue3前端开发_Day5
  • 【PZ-A735T-KFB】璞致fpga开发板 Artix-7 系列之PA-Starlite-初学入门首选 开发板用户手册
  • 《Python 整数列表分类:巧妙将负数移到正数前面》
  • 力扣hot100:无重复字符的最长子串,找到字符串中所有字母异位词(滑动窗口算法讲解)(3,438)
  • LeetCode每日一题,2025-08-21
  • C++——C++重点知识点复习2(详细复习模板,继承)
  • 2.Shell脚本修炼手册---创建第一个 Shell 脚本
  • C++ string类(reserve , resize , insert , erase)
  • 鸿蒙中网络诊断:Network分析
  • 深入理解JVM内存结构:从字节码执行到垃圾回收的全景解析
  • 金山云Q2营收23.5亿元 AI战略激活业务增长新空间
  • Altium Designer 22使用笔记(8)---PCB电气约束设置
  • GitHub Copilot - GitHub 推出的AI编程助手
  • Pytorch框架学习
  • Bigemap APP 详细使用教程,入门学习PPT
  • element table 表格多选框选中高亮
  • KubeBlocks for ClickHouse 容器化之路
  • 【运维进阶】shell三剑客
  • DeepSeek大模型如何重塑AI Agent?从技术突破到行业落地
  • 环境搭建-dockerfile构建镜像时apt软件包出现exit100错误+ pip下载python库时下载过慢的解决方法
  • SpringWeb详解
  • CorrectNav——基于VLM构建带“自我纠正飞轮”的VLN:通过「视觉输入和语言指令」预测导航动作,且从动作和感知层面生成自我修正数据
  • 【LeetCode热题100道笔记+动画】三数之和