Bug in random numbers in Android

后端 未结 3 1897
我在风中等你
我在风中等你 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:34

    To generate a random number in a range, it is like:

    int min = ...
    int max = ...
    int randNumber = min + new Random().nextInt(max - min + 1);
    

    So in your example where you want to generate a random number from [1, 16], it would look like:

    int randNumber = 1 + new Random().nextInt(16 - 1 + 1);
    

    Or if you choose to simplify:

    int randNumber = 1 + new Random().nextInt(16);
    

    Also, you should really be using a while loop instead of an infinite for loop:

        final TreeSet myNumbers = new TreeSet<>();
        final Random rand = new Random();
        for(int i = 0; i < 16; i++){
            int n = 1 + rand.nextInt(16);
            while(!myNumbers.add(n))
                n = 1 + rand.nextInt(16);
        }
    

提交回复
热议问题