278

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
  • 11,316
  • 11
  • 73
  • 98
Mohit Kanada
  • 14,284
  • 8
  • 29
  • 41
  • With [Kotlin](https://stackoverflow.com/a/45687695/8583692) you can do this: `val r = (0..10).random()` – Mahozad Aug 26 '21 at 11:14

2 Answers2

516
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
  • 35,562
  • 12
  • 75
  • 123
Ishtar
  • 11,322
  • 1
  • 22
  • 30
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.

Saeid Yazdani
  • 13,065
  • 50
  • 172
  • 279
Vivien Barousse
  • 20,145
  • 2
  • 57
  • 64