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]
.
After generating the random number you've to put the "holes" back in the range. This can be achieved by incrementing the generated number as long as there are excluded numbers lower than or equal to the generated one. The lower exclude numbers are "holes" in the range before the generated number.
For example, in a dice game possible values can be between 1 to 6 only. Below is the code showing how to generate a random number between 1 and 10 inclusive. Random random = new Random(); int rand = 0; while (true){ rand = random. nextInt(11); if(rand !=
Random generator = new Random(); int i = generator.nextInt(10) + 1;
How about:
Random generator = new Random(); int i = 10 - generator.nextInt(10);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With