Generating Unique Random Numbers in Java

后端 未结 21 2605
不思量自难忘°
不思量自难忘° 2020-11-21 07:45

I\'m trying to get random numbers between 0 and 100. But I want them to be unique, not repeated in a sequence. For example if I got 5 numbers, they should be 82,12,53,64,32

21条回答
  •  猫巷女王i
    2020-11-21 08:08

    I have made this like that.

        Random random = new Random();
        ArrayList arrayList = new ArrayList();
    
        while (arrayList.size() < 6) { // how many numbers u need - it will 6
            int a = random.nextInt(49)+1; // this will give numbers between 1 and 50.
    
            if (!arrayList.contains(a)) {
                arrayList.add(a);
            }
        }
    

提交回复
热议问题