I have an array that I populate with 6 randomly generated numbers. First it generates a random number between 1 and 49 and then checks it against the numbers in the array. If it finds a duplicate it should generate a random number again and then perform the check once again. If there are no duplicates then the number is added to the array.
Here's the code:
public void populateArray()
{
for(int i = 0; i < numberLine.length; i++)
{
randomNumber = 1 + randomGen.nextInt(49);
for(int j = 0; j < i; j++)
{
if (numberLine[j] == randomNumber)
{
i--;
}
else
{
continue;
}
}
if(i >= 0)
{
numberLine[i] = randomNumber;
}
else
{
continue;
}
}
Arrays.sort(numberLine);
}
However, for some reason this still lets in a duplicate, though rarely (about 1 in 50 arrays), such as 6 6 16 24 34 46. But when I try to duplicate this by taking out the random number element and using a number like 30, I am unable to reproduce the result. What's going wrong?
j < ipart, that can loop, because both i and j start as 0, therefore j is not less than i.