Get random integer in range (x, y]? [duplicate]

2019-02-11 10:41发布

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].

标签: java random
3条回答
不美不萌又怎样
2楼-- · 2019-02-11 10:56

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).

查看更多
在下西门庆
3楼-- · 2019-02-11 10:59
Random generator = new Random(); 
int i = generator.nextInt(10) + 1;
查看更多
闹够了就滚
4楼-- · 2019-02-11 11:01

How about:

Random generator = new Random();
int i = 10 - generator.nextInt(10);
查看更多
登录 后发表回答