Possible Duplicate:
Java: generating random number in a range可能的重复:Java:在一个范围内生成随机数
I want to generate random number in a specific range. (Ex. Range Between 65 to 80)
我想生成一个特定范围内的随机数。(例如,范围在65至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).
我按下面的代码尝试,但它不是很充分。它还返回大于max的值。值(大于80)。
Random r = new Random();
int i1 = (r.nextInt(80) + 65);
How can I generate random number in between range?
如何生成区间内的随机数?
2 个解决方案
#1
435
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
.
这给出了一个介于65(包括)和80(排除)之间的随机整数,65、66、……、78、79中的一个。
#2
280
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
.
注意,nextInt(int max)返回的int数介于0和max之间。因此,+ 1。
#1
435
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
.
这给出了一个介于65(包括)和80(排除)之间的随机整数,65、66、……、78、79中的一个。
#2
280
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
.
注意,nextInt(int max)返回的int数介于0和max之间。因此,+ 1。