How to get a random number in Kotlin? (Int, Double, Long, Float)
Hello everyone! I just started learning Kotlin and switched from Java. In Java I used to use `Math.random()` or the `Random` class, but in Kotlin I see the syntax is a bit different.
I need to solve a simple problem: write a "Guess the number" game. The computer picks a number from 1 to 100, and the user tries to guess it. I tried writing this code:
```kotlin
fun main() {
val secretNumber = Math.random() * 100 + 1
println("Guess the number: $secretNumber")
}
```
But this gives a number with many decimal places, for example: `42.718293847`. I need an integer.
I looked into the `java.util.Random` class, but it seems too cumbersome for such a simple task. In the documentation I saw mentions of `kotlin.random.Random`, but I didn't quite understand how to use it correctly.
No answers yet.
Log in to leave an answer
Blogs
Java Application Security: Top 10 Vulnerabilities and How to Avoid Them