288

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?

Mahozad
  • 18,032
  • 13
  • 118
  • 133
Mohit Kanada
  • 15,274
  • 8
  • 31
  • 41
  • 1
    With [Kotlin](https://stackoverflow.com/a/45687695/8583692) you can do this: `val r = (0..10).random()` – Mahozad Aug 26 '21 at 11:14
  • You can write `val randomNumber = (min..max).random()` where `min` and `max` are the edges of the specified range. Refer [Kotlin – Generate a Random Number in specific Range](https://kotlinandroid.org/kotlin/kotlin-generate-a-random-number-in-specific-range/) – arjun Jun 14 '23 at 09:48

2 Answers2

523
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.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Ishtar
  • 11,542
  • 1
  • 25
  • 31
308
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.

Dumbo
  • 13,555
  • 54
  • 184
  • 288
Vivien Barousse
  • 20,555
  • 2
  • 63
  • 64