From java.util.Random
:
Random rand = new Random();
rand.nextInt(X);
//returns an `int` in range: [0,X)
So, if you have a
, b
, ..., n
, to get a number in between 0 and the sum of the variables, we do:
rand.nextInt(a + b + ... + n + 1); //returns an `int` in range [0, sum(a,b,...,n)]
As other users have suggested, you can also use Math.random()
; however, Math.random()
returns a double
in range: [0,1)
. So, if you have min = 0
, max = 9
, and want a number between [0,9]
, then you need:
Min + (int)(Math.round((Math.random() * (Max - Min))))
//need to cast to int since Math.round(double returns a long)
or you could do:
Min + (int)(Math.random() * (Max - Min + 1))