Kotlin Programming: Controlling Program Flow PDF

Document Details

ThrilledIridium

Uploaded by ThrilledIridium

Minia University

Tags

kotlin programming control flow programming languages computer science

Summary

This document is a lecture on controlling program flow in Kotlin. It covers various control structures like when statements, while loops, do-while loops, for loops. Examples are included for each to illustrate their usage.

Full Transcript

Controlling Program Flow LECTURE TWO  Program statements are executed sequentially by default, one after the other, in a linear fashion.  There are constructs that can cause programs to deviate from a linear flow.  Some can cause the flow to fork or branch, and other constructs can cau...

Controlling Program Flow LECTURE TWO  Program statements are executed sequentially by default, one after the other, in a linear fashion.  There are constructs that can cause programs to deviate from a linear flow.  Some can cause the flow to fork or branch, and other constructs can cause the program flow to go around in circles, like in a loop. These constructs are the subject of this section. The when Statement  Kotlin doesn’t have a switch statement, but it has the when construct. Its form and structure is strikingly similar to the switch statement. In its simplest form, it can be implemented like this: 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") }  when matches the argument (the variable day) against all branches sequentially until it encounters a match; note that unlike in switch statements, when a match is found, it doesn’t flow through or cascade to the next branch—hence, we don’t need to put a break statement. The when construct can also be used as an expression, and when it’s used as such, each branch becomes the returned value of the expression. See the code example: 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" }  Just remember to include the else clause when when is used as an expression. The compiler thoroughly checks all possible pathways and it needs to be exhaustive, which is why the else clause becomes a requirement. How to Write Branches Inside the When Construct 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) } The while Statement  The while and do.. while statements work exactly as they do in Java—and like in Java, these are also statements and not expressions. We won’t spend too much time on while and do.. while loops here.  A basic usage of the while loop is shown here, just as a refresher. fun main(args: Array) { var count = 0 val finish = 5 while (count++ < finish) { println("counter = $count") } } Flowchart of while Loop Example of Compute sum of Natural Numbers // Program to compute the sum of natural numbers from 1 to 100. fun main(args: Array) { var sum = 0 var i = 100 while (i != 0) { sum += i // sum = sum + i; --i } println("sum = $sum") } do...while Loop  The do...while loop is similar to while loop with one key difference.  The body of do...while loop is executed once before the test expression is checked.  Its syntax is:  do { // codes inside body of do while loop  } while (testExpression); Flowchart of do...while Loop The program below calculates the sum of numbers entered by the user until user enters 0. fun main(args: Array) { var sum: Int = 0 var input: String do { print("Enter an integer: ") input = readLine()!! sum += input.toInt() } while (input != "0") println("sum = $sum") } for loops  fun main(args: Array) {  val words = "The quick brown fox".split(" ") ➊  for(word in words) { ➋  println(word) ➌  }  }  If you need to work with numbers on the for loop, you can use Ranges. A range is a  type that represents an arithmetic progression of integers. Ranges are created with the var zeroToTen =  rangeTo() function, but we usually use it in its operator form (.. ). To 0..10 create a range of  integers from 1 to 10, we write like this: if (9 in zeroToTen) println("9 is in  We can use the in keyword to perform a test of membership. zeroToTen") To use ranges in for loops, we can start with something that looks like the code shown  fun main(args: Array) {  for (i in 1..10) {  println(i)  }  } Exception Handling  Kotlin’s exception handling is very similar to Java: it also uses the try-catch-finally construct.  Whatever we’ve learned about Java’s exception handling commutes nicely to Kotlin.  However, Kotlin simplifies exception handling by simply using unchecked exceptions. What that means is writing try-catch blocks is now optional. You may or may not do it. import java.io.FileReader ➊ fun main(args: Array) { var fileReader = FileReader("README.txt") ➋ var content = fileReader.read() ➌ println(content) } import java.io.FileNotFoundException import java.io.FileReader import java.io.IOException fun main(args: Array) { var fileReader: FileReader try { fileReader = FileReader("README.txt") var content = fileReader.read() println(content) } catch (ffe: FileNotFoundException) { println(ffe.message) } catch(ioe: IOException) { println(ioe.message) } } In this program, we will perform an arithmetic operation and handle arithmetic exceptions using a try-catch block. import kotlin.ArithmeticException fun main(args : Array) { var x = 10 var y = 3 try{ println("10/3: " + x/y) x = 10 y = 0 println("10/0: " + x/y) } catch(e: ArithmeticException){ // caught and handles it println("Divide by zero exception") } } Kotlin program of using try-catch as an expression fun DivideOperation(x: Int, y: Int) : Any { return try { x/y } catch(exp:Exception){ println(exp) "Divide by zero exception occured" } } // Main function fun main(args: Array) { // Call DivideOperation() functions // to use try-catch as an exception var res1 = DivideOperation(10, 3) println(res1) var res2 = DivideOperation(10, 0) println(res2) } Handling Nulls  In Kotlin, when we declare a variable like:  var str: String = "Hello"  str = null // won't work  we will never be able to set the value of this variable to null.  We may assign it a different String value, but Kotlin guarantees that str will never be null. If, for some reason, you really need this variable to be null, you have to explicitly tell Kotlin that str is a Nullable type.  To make a String (or any type) Nullable, we use the question mark symbol as postfix to the type, like var str: String? = "Hello"  After declaring a type as Nullable, we now have to do some things that Kotlin used to do for us. For non-Nullable types, Kotlin ensures that it’s pretty safe to use them in operations such as assignment, printing, inclusion in expressions, etc. When we make types Nullable, Kotlin assumes that we know what we’re doing and that we’re responsible enough to write the necessary guard conditions to prevent NullPointerExceptions. Demonstration of Nullable Types fun main(args: Array) { var a = arrayOf(1,2,3) printArr(null) } fun printArr(arr: Array?) { ➊ if(arr != null) { ➋ arr.forEach { i -> println(i) } ➌ } }  Kotlin introduced an operator that we can use to handle Nullable types. It’s called the safe-call operator, which is written as the question mark symbol followed by a dot ?.  We can replace the entire if block, which performs the null checking, with just one statement:  arr?.forEach { i -> println(i) } Safe Call Operator  fun main(args: Array) {  var a = arrayOf(1,2,3)  printArr(null)  }  fun printArr(arr: Array?) {  arr?.forEach { i -> println(i) }  } Example  Given a string, we have to check whether it is an empty, blank or NULL string. package com.includehelp.basic //Main Function, entry Point of Program fun main(args: Array) { ///Nullable String val s1: String?=null //Empty String val s2: String="" //Blank String, Contained only white spaces val s3=" " println("String s1 is isNullOrEmpty : ${s1.isNullOrEmpty()}") println("String s2 is isEmpty : ${s2.isEmpty()}") println("String s3 is isBlank : ${s3.isBlank()}") }

Use Quizgecko on...
Browser
Browser