开发者

How can I generate random number in specific range in Android? [duplicate]

开发者 https://www.devze.com 2023-03-06 16:50 出处:网络
This question already has answers here: How do I generate random integers within a specific range in Java?
This question already has answers here: How do I generate random integers within a specific range in Java? (72 answers) Closed 3 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消