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
  • 1
    With Kotlin you can do this: val r = (0..10).random() Commented Aug 26, 2021 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 Commented Jun 14, 2023 at 9:48

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.

Sign up to request clarification or add additional context in comments.

7 Comments

it won't work for negative numbers
If you need a negative number, use this and multiply by -1. You need a float, I think.
@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 ;)
simpler as possible: int myRandomInt = new Random().nextInt(80 - 65) + 65;
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 👍
|
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.