How can I generate random number in specific range in Android?
To generate a random number in a specific range in Android, you can use the nextInt
method of the java.util.Random
class.
Here is an example of how to generate a random number between 0 and 100:
Random random = new Random();
int randomInt = random.nextInt(101); // generates a random number between 0 and 100
If you want to generate a random number between a different range, you can use the following formula:
Random random = new Random();
int min = 10;
int max = 20;
int randomInt = random.nextInt((max - min) + 1) + min; // generates a random number between 10 and 20
This will generate a random number between min
and max
, inclusive.
You can also use the nextInt
method of the android.os.SystemClock
class, which is optimized for generating random numbers on Android. Here is an example:
int randomInt = android.os.SystemClock.nextInt(101); // generates a random number between 0 and 100