I am trying to generate an array of random numbers. Each array entry will have a number between 0 and 31. I am trying to get the code to generate a random number and then check to see if that number exists in the array. If it does, it then generates a fresh random number and checks from the beginning again.
I thought I had it sussed with the code below:
public class HelloWorld{
public static void main(String []args){
int[] randArray = new int[10];
boolean firstNumber = true;
int randNum = 0;
for (int j=0; j < randArray.length; j++) {
if(firstNumber) {
randNum = (int)(Math.random() * 31 + 1);
randArray[j] = randNum;
firstNumber = false;
} else {
for (int k=0; k < randArray.length;) {
randNum = (int)(Math.random() * 31 + 1);
if(randArray[k] == randNum) {
k=0;
} else {
k++;
}
}
randArray[j] = randNum;
System.out.println(j);
}
}
System.out.println("-------");
for(int i=0; i < randArray.length; i++) {
System.out.println(randArray[i]);
}
}
}
But this is what it prints out:
1 2 3 4 5 6 7 8 9 ------- 25 17 19 20 24 4 26 30 6 24
As you can see, 24 is repeated twice. If I run the code again, you can see numbers being stored that are repeated.
Logically I cannot figure out why it is doing this. It may be something simple but I just can't see it.
I'm new to programming and this is something I thought I would test my knowledge with.