Find Fifty
Same hunt, bigger haystack: find 50 out of 100.
1import kotlin.random.Random
2
3fun main() {
4 var number = findFifty()
5 while (number != 50) {
6 println(number)
7 number = findFifty()
8 }
9 println(number)
10}
11
12fun findFifty(): Int = Random.nextInt(100)
$ 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 = findFifty()- Calls the findFifty function we write below and stores the random whole number (0 to 99) it hands back.
while (number != 50) {- 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. The loop keeps running as long as number is NOT 50. With 100 possibilities this usually takes a lot more tries than finding 5 out of 10!
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. Expect a lot of them.
number = findFifty()- Asks findFifty for a fresh random number, then the loop checks 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. Prints the 50 that finally ended the loop.
}- This closing curly brace } ends the main function. In Kotlin every opening brace { must have a matching closing brace }.
fun findFifty(): Int = Random.nextInt(100)- The same one-line style as before, but Random.nextInt(100) now hands back a random whole number from 0 to 99.