How can I generate random number in specific range in Android?

JavaAndroidKotlinRandom

Java Problem Overview


I want to generate random number in a specific range. (Ex. Range Between 65 to 80)

I try as per below code, but it is not very use full. It also returns the value greater then max. value(greater then 80).

Random r = new Random();
int i1 = (r.nextInt(80) + 65);

How can I generate random number between a range?

Java Solutions


Solution 1 - Java

Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;

This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79.

Solution 2 - Java

int min = 65;
int max = 80;

Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;

Note that nextInt(int max) returns an int between 0 inclusive and max exclusive. Hence the +1.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMohit KanadaView Question on Stackoverflow
Solution 1 - JavaIshtarView Answer on Stackoverflow
Solution 2 - JavaVivien BarousseView Answer on Stackoverflow