I feel like it\'s a simple concept, but I\'m having trouble with inclusive and exclusive: particularly concerning random number generator.
For instance, if I wanted
For instance, if I wanted a value 2-8 (including 2 and 8), that would be inclusive, correct?
Yes. Inclusive includes; Exclusive excludes.
The range 2-8
inclusive is 7 unique values (2,3,4,5,6,7,8); and Random.nextInt(int) excludes the specified value. So you want something like
Random rand = new Random();
int min = 2;
int max = 8;
// ...
int r = rand.nextInt((max - min) + 1) + min;
Inclusive means it includes the number. Exclusive means it does not. The Random.nextInt(limit)
is inclusive of 0, and exclusive of the limit. This approach allows using, e.g., the size of an array in a random number:
int[] arr = new int[6]; //size will be 6
Random rnd = new Random();
int i = arr[rnd.nextInt(arr.length)); //will return between [0] and [5]
For a value between 2 and 8, you know that the .nextInt(limit)
will return between 0 and limit, so .nextInt(7) + 2
will give a random number between 0 (inclusive) and 7 (exclusive, which is 6). Adding + 2 will be between 2 and 8 (inclusive of both), since it will be between (0 + 2) and (6 + 2).