Share
Explore

KOTLIN DRILLS

Kotlin can get input from the user at the command line. Below is a complete example of a guessing game in Kotlin where the program generates a random number between 1 and 100, and the user tries to guess the number. The program will provide feedback on whether the guessed number is too high, too low, or correct.
### Kotlin Guessing Game
#### Objective: Create a guessing game where the user tries to guess a randomly generated number between 1 and 100.
#### Steps: 1. Generate a random number between 1 and 100. 2. Prompt the user to enter a guess. 3. Compare the user's guess with the generated number. 4. Provide feedback to the user (too high, too low, or correct). 5. Repeat until the user guesses the correct number.
Here's the complete code for the guessing game:

image.png
### Explanation:

1. **Import Statements**:

- `import kotlin.random.Random`: This imports the Random class for generating random numbers. - `import kotlin.system.exitProcess`: This allows us to exit the program once the user guesses correctly.

2. **Main Function**:

- `val targetNumber = Random.nextInt(1, 101)`: Generates a random number between 1 and 100. - `var userGuess: Int? = null`: Initializes a nullable integer to store the user's guess.

3. **Game Loop**:

- `while (userGuess != targetNumber)`: Continues to prompt the user for guesses until the correct number is guessed. - `print("Enter your guess: ")`: Prompts the user to enter a guess. - `userGuess = readLine()?.toIntOrNull()`: Reads the user input from the command line and converts it to an integer.
- The `when` statement provides feedback based on the user's guess:
- `userGuess < targetNumber -> println("Too low. Try again.")` - `userGuess > targetNumber -> println("Too high. Try again.")` - `userGuess == targetNumber -> println("Congratulations! You've guessed the correct number: $targetNumber")` and exits the program.

This code will give students a hands-on experience with reading input, generating random numbers, and using control flow statements to create an interactive guessing game.
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.