i want to random numbers only at once. i searched to get this and learned there is shuffle function. it is ok but i wonder what is wrong here. this code doesn't work it generates same numbers.
public class panel {
boolean[] generated = new boolean[5];
int[] grid = new int[5];
panel() {
for (int i = 0; i < 5 i ) {
int x = generaterandom();
generated[x] = true;
grid[i] = x;
System.out.println(grid[i]);
}
}
public int generaterandom() {
int r = random.nextInt(5);
if (generated[r]) generaterandom();
return r;
}
}
CodePudding user response:
When you recurse, you calculate a new r which is returned .ok.
But you don't use it within the caller.
So you always return the r of the very first step.
Try
if (generated[r]) r = generaterandom();
return r;