This question already has an answer here:
- Generate a random double in a range 5 answers
I'm a Java noob trying to generate a random double between -10 and 10 inclusive. I know with ints I would do the following:
Random r = new Random();
int i = -10 + r.nextInt(21);
However, with doubles, this doesn't work:
Random r = new Random();
double i = -10 + r.nextDouble(21);
Can someone please explain what to do in the case of doubles?
There is no
nextDouble(int)
method inRandom
. Use this:API reference
Try to use this for generate values in given range:
Or try to use this:
Try this:
Note: it should be 20.0 (not 21.0)
nextDouble doesn't take a parameter, you just need to multiply it by whatever your range is. Or more generally: