I have to do this in Java:
Write a method fillArray() that takes three integers: (s, min, max), and returns an array of size s having random integers with values between min and max.
This is the code I wrote
public static void fillArray(int s, int min, int max) {
int[] random = new int[s];
for (int i = 0; i < s; i++) {
int n = (int) (Math.random()*100 %s);
if (n > min && n < max) {
random[i] = n;
}
}
System.out.printf("Here's an array of size %d, whose elements vary between %d and %d: \n", s, min, max);
System.out.print(Arrays.toString(random));
}
The problem is, when I implement my method in the main, fillArray(10, 10, 20)
, it gives me arrays of size 10, with elements at 0.
I tried playing around with this specific expression in the code
int n = (int) (Math.random()*100 %s);
and changing what I do after *100.
Sometimes it works for most elements, but I still get some elements which are 0, which is wrong since the minimum is 10.
Any idea how I could fix that?