Share
Explore

Level 2 Student Learning Lab Notebook: Introduction to KOTLIN Programming Level 2 Skills

Introduction:

In this level 2 lab notebook, you will learn how to accept user input, create reusable functions, and call those functions in a Kotlin program. We will build on the concepts learned in the level 1 lab notebook, which covered handling variables, if-then statements, for and while loops, and output statements.

Learning Outcomes:

By the end of this lab, you will be able to:
Accept user input in a Kotlin program
Create reusable functions
Call functions in your code

Prerequisites:

Before starting this lab, make sure you have completed the Level 1 lab notebook and have a basic understanding of Kotlin syntax, including variables, if-then statements, for and while loops, and output statements.

Part 1: Accepting User Input

In this section, you will learn how to accept user input using the readLine() function.
Open your Kotlin development environment (e.g., IntelliJ IDEA or Kotlin Playground).
Create a new Kotlin file and name it "UserInput".
In the main function, add the following code:
kotlin
Copy code
fun main() {
print("Enter your name: ")
val name = readLine()
println("Hello, $name!")
}
Run the program and enter your name when prompted.

Part 2: Creating Reusable Functions

In this section, you will learn how to create reusable functions in Kotlin.
In the same "UserInput" file, add the following function below the main function:
kotlin
Copy code
fun greet(name: String) {
println("Hello, $name!")
}
This function, greet, takes a single parameter, a String called name. It then prints a greeting using the provided name.

Part 3: Calling Functions

In this section, you will learn how to call the greet function from the main function.
Modify the main function in your "UserInput" file as follows:
kotlin
Copy code
fun main() {
print("Enter your name: ")
val name = readLine()
greet(name!!)
}
The greet function is called with the user's name as an argument, which is passed to the greet function as name.
Run the program again, and you should see the same output as before, but now the greeting is generated by the greet function.

Conclusion:

In this level 2 lab notebook, you learned how to accept user input using the readLine() function, create reusable functions, and call those functions in your Kotlin program.
This knowledge will help you create more complex and modular Kotlin programs in the future.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.