Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number between -5 and 5

Tags:

java

random

Im trying to get random number between -5 and 5. Im using this code:

random.nextInt(10)-5;  

but it doesnt give me number 5 and if i use random.nextInt(10)-4; then I never get -5.

So how can I get random between -5 and 5?

like image 472
Rohit Malish Avatar asked Nov 28 '22 14:11

Rohit Malish


2 Answers

random.nextInt(11) - 5

You have 11 integers in the interval so you need 11 different values.

like image 169
Ivaylo Strandjev Avatar answered Dec 14 '22 15:12

Ivaylo Strandjev


The end of the range is exclusive in Random, so you have to use:

random.nextInt(11) - 5
like image 33
NPE Avatar answered Dec 14 '22 14:12

NPE