The random values aren't stored because function Math.random()
generates values between 0.0 (inclusive) and 1.0 (exclusive) and hence, cast to int will always return 0. From official docs:
Returns a double value with a positive sign, greater than or equal to
0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.
Either multiply the Math.random()
result with some fixed integer value and cast to int or use a Random
instance's method random.nextInt()
as:
int rand = (int)(Math.random() * FIXED_INT_VAL);
or
Random r = new Random();
int rand = r.nextInt();
The latter approach is recommend due to reason explained in this post.
So, your code becomes:
public class ArrayStats {
public static void fillRandomArray(int [] a, int max) {
int [] randomArray = new int[max];
Random r = new Random();
for (int i=0; i < randomArray.length; i++){
randomArray[i] = r.nextInt();
}
}
}