How to generate random numbers in a given range in Android on Kotlin?
Hi everyone! I'm a beginner in Android development and writing an app in Kotlin. I need to generate a random number in a specific range, for example, from 1 to 10 (inclusive) or from 5 to 50. I tried using `Random().nextInt()`, but it returns a random number from 0 to the maximum value, and I need it exactly in my range.
Here's what I wrote:
```kotlin
val randomNumber = Random().nextInt(10) // gives a number from 0 to 9
```
I want the number to be, say, from 1 to 10 or from 10 to 20. I tried adding an offset, but sometimes it goes out of bounds. Please advise how to do this correctly in Kotlin? Preferably, the code should be compatible with Android API 21+ (this is the minimum version in my project). Thanks in advance! Also, I'm interested if there is a difference between `java.util.Random` and `kotlin.
No answers yet.
Log in to leave an answer