The community reviewed whether to reopen this question 1 year ago and left it closed:
开发者_开发技巧Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
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?
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
.
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
.
精彩评论