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