Bug in random numbers in Android

后端 未结 3 1945
我在风中等你
我在风中等你 2021-01-26 03:14
TreeSet myNumbers = new TreeSet();
Random randGen = new Random();

for (int i = 1; i <= 16; i++) {
    // number generation here
    int randNum = randGen.nextInt(16          


        
3条回答
  •  野性不改
    2021-01-26 03:43

    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.)

提交回复
热议问题