289

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?

2

2 Answers 2

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

7
  • 3
    it won't work for negative numbers Commented Jun 7, 2013 at 21:21
  • 7
    If you need a negative number, use this and multiply by -1. You need a float, I think.
    – Allison
    Commented Jan 4, 2014 at 23:36
  • @Sirens: He could even generate two more numbers, then count differente between them (it can be negative or positive number ;)), and finaly multiply the original random number ;)
    – TomeeNS
    Commented Sep 23, 2015 at 21:48
  • 2
    simpler as possible: int myRandomInt = new Random().nextInt(80 - 65) + 65;
    – Alecs
    Commented Jan 11, 2016 at 11:14
  • 8
    I've been writing Java in one way or another for about 8 years and I still copy and paste this code whenever I need it, cheers 👍 Commented Jun 19, 2017 at 9:17
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.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.