Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

random

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

like image 889
Dinara Avatar asked Nov 23 '11 01:11

Dinara


People also ask

How can I generate a random number within a range but exclude some?

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.

How do you generate a random number from 1 to 6 in Java?

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 !=


2 Answers

Random generator = new Random();  int i = generator.nextInt(10) + 1; 
like image 74
Dmitry B. Avatar answered Sep 20 '22 15:09

Dmitry B.


How about:

Random generator = new Random(); int i = 10 - generator.nextInt(10); 
like image 26
Nick Meyer Avatar answered Sep 19 '22 15:09

Nick Meyer