I have a doubt if I leave my index++ inside ifn as it is in the code below, the program does not execute, however if I put it at the beginning the program never generates new numbers if the ones already generated are the same, I really don't know where my mistake is
Note: I'm doing it in Windows Builder
private int[] number = new int[] { -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1};
private int index;
private int randomNumber;
private boolean numberRepeated;
Random random = new Random();
index = 0;
while(index < 10) {
randomNumber = random.nextInt(9);
numberRepeated = false;
for(int i = 0 ; i < index; i++) {
if(number[i] == randomNumber) {
numberRepeated = true;
break;
}
}
if(!numberRepeated) {
number[index] = randomNumber;
index++;
}
}
I've already tried changing index++, but when I do this the program doesn't generate new values if the same values have already been entered.
The first problem is that
Random.nextInt(9)gives values from 0 upto 8.The
numberRepeatedwill happen ever more, the larger isindex. There even is no 100% guarantee that the last digit will ever by found by Random.Better and much faster would be
This will swap at least every element once, sometimes with itself (good!).
This might be done otherwise with newer java constructs, like for 0 .. 9:
or:
or;