Generating Unique Random Numbers in Java

后端 未结 21 2576
不思量自难忘°
不思量自难忘° 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条回答
  •  情深已故
    2020-11-21 08:09

    This will work to generate unique random numbers................

    import java.util.HashSet;
    import java.util.Random;
    
    public class RandomExample {
    
        public static void main(String[] args) {
            Random rand = new Random();
            int e;
            int i;
            int g = 10;
            HashSet randomNumbers = new HashSet();
    
            for (i = 0; i < g; i++) {
                e = rand.nextInt(20);
                randomNumbers.add(e);
                if (randomNumbers.size() <= 10) {
                    if (randomNumbers.size() == 10) {
                        g = 10;
                    }
                    g++;
                    randomNumbers.add(e);
                }
            }
            System.out.println("Ten Unique random numbers from 1 to 20 are  : " + randomNumbers);
        }
    }
    

提交回复
热议问题