Bug in random numbers in Android

TreeSet myNumbers = new TreeSet();
Random randGen = new Random();

for (int i = 1; i <= 16; i++) {
    // number generation here
    int randNum = randGen.nextInt(16 - 1) + 1;
    for (;;) {
        if (myNumbers.add(randNum))
            break;
        else
            randNum = randGen.nextInt();

    }
    Toast.makeText(getApplicationContext(), "" + randNum, 100).show();
}

I want to generate random numbers between 1 and 16 and the same number should not be repeated.

The code above gives me output like:

2, 5, 7, 9, 1, 4, 10.4109446, -448831, 98824724, 11, 13, ...

I do not know why it gives me random numbers not in the 1-16 range, please help me out.

Jon Skeet
people
quotationmark

You're only generating one number in the range 1-15. You're then generating subsequent numbers with just nextInt:

if (myNumbers.add(randNum))
    break;
else
    randNum = randGen.nextInt();

That should be:

if (myNumbers.add(randNum))
    break;
else
    randNum = randGen.nextInt(16) + 1;

... and fix the initial call to nextInt to remove the "-1". (You don't need the 16 - 1, as explained in Josh's answer.)

people

See more on this question at Stackoverflow