Line At A Time
Lesson 24: Find Five
Find Five Keep calling a function until it returns 5.
1import kotlin.random.Random
2
3fun main() {
4 var number = findFive()
5 while (number != 5) {
6 println(number)
7 number = findFive()
8 }
9 println(number)
10}
11
12fun findFive(): Int = Random.nextInt(10)
Terminal
$ kotlinc Main.kt -include-runtime -d Main.jar
$ java -jar Main.jar
(prints a random number, different every run)
Every line, explained
import kotlin.random.Random
import lines go at the very top of a Kotlin file and bring in extra tools. kotlin.random.Random is Kotlin's random-number helper; we need it for Random.nextInt below.
fun main() {
Every Kotlin program starts at the main function. When you run the program, Kotlin looks for fun main() and runs everything between its { and } from top to bottom.
var number = findFive()
This calls the findFive function we write below. It hands back a random whole number from 0 to 9, which is stored in number. It will change as we keep trying, so it is a var.
while (number != 5) {
A while loop repeats its block for as long as the condition in the round brackets is true. The condition is checked again before every trip around the loop. != means "not equal". The loop keeps running as long as number is NOT 5.
println(number)
println(...) prints whatever is inside the round brackets to the terminal, then moves to a new line. All lowercase, and no semicolon at the end; Kotlin does not need them. Prints each wrong guess.
number = findFive()
Asks findFive for a fresh random number and stores it, replacing the old one. Then the loop checks the condition again.
}
This } closes the while loop.
println(number)
println(...) prints whatever is inside the round brackets to the terminal, then moves to a new line. All lowercase, and no semicolon at the end; Kotlin does not need them. The loop only ends when number is finally 5, so this prints the 5 we were hunting for.
}
This closing curly brace } ends the main function. In Kotlin every opening brace { must have a matching closing brace }.
fun findFive(): Int = Random.nextInt(10)
A one-line function. The : Int says findFive hands back a whole number, and instead of { } with a return inside, a single = gives its result directly. Read it as: findFive is a function that returns Random.nextInt(10), a random number from 0 to 9.