Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Random number but not zero

int num = 10;
Random rand = new Random();
int ran = rand.nextInt(num);
if (ran==0){          
  ran= ran+1;
}
System.out.println("random : "+ran);  

This is what i have coded so far, is there a better way to do this? I feel that this is hard coding when random is 0, I added 1.

like image 617
newbieprogrammer Avatar asked May 02 '13 07:05

newbieprogrammer


People also ask

How do you generate a random number excluding 0 in Java?

int num = 10; Random rand = new Random(); int ran = rand. nextInt(num); if (ran==0){ ran= ran+1; } System. out. println("random : "+ran);

Does Java random include 0?

random() can never generate 0 because it starts with a non-zero seed. Set the seed to zero, the function does not work, or throws an error. A random number generator always returns a value between 0 and 1, but never equal to one or the other.

Does nextInt include 0?

The nextInt(int n) method is used to get a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.


2 Answers

The problem with that code is that 1 is twice as likely as other numbers (as your effective result is 1 when nextInt() returns 0 or 1).

The best solution is to just always add 1 and request random numbers from a smaller range:

int rnd = rand.nextInt(num - 1) + 1;
like image 121
Joachim Sauer Avatar answered Oct 09 '22 00:10

Joachim Sauer


I guess you are trying to get a random number between 1 and 'num'.

a more generic way can be :

int Low = 1;
int High = 10;
int R = r.nextInt(High-Low) + Low;

This gives you a random number in between 1 (inclusive) and 10 (exclusive). ( or use High=11 for 10 inclusive)

like image 44
Lav Avatar answered Oct 09 '22 00:10

Lav