Get random integer in range (x, y]?
Possible Duplicate:
Java: generating random number in a range
How do I generate a random integer i
, such that i
belongs to (0,10]
?
I tried to use this:
Random generator = new Random();
int i = generator.nextInt(10);
but it gives me values between [0,10)
.
But in my case I need them to be (0,10]
.
Random generator = new Random();
int i = generator.nextInt(10) + 1;
怎么样:
Random generator = new Random();
int i = 10 - generator.nextInt(10);
Just add one to the result. That turns [0, 10) into (0,10] (for integers). [0, 10) is just a more confusing way to say [0, 9], and (0,10] is [1,10] (for integers).
链接地址: http://www.djcxy.com/p/17660.html上一篇: 为Random.nextInt()指定max和min?
下一篇: 获取范围(x,y)中的随机整数?