How to generate n different random numbers in Java?

You can use the Random class in Java to generate random numbers, and combine it with a Set collection to ensure that the generated random numbers are unique. Here is an example code:

import java.util.*;

public class RandomNumbers {
    public static void main(String[] args) {
        int n = 10; // 生成n个不同的随机数
        Set<Integer> set = new HashSet<>();
        Random rand = new Random();

        while (set.size() < n) {
            int num = rand.nextInt(100); // 生成0到99之间的随机数
            set.add(num);
        }

        for (int num : set) {
            System.out.println(num);
        }
    }
}

The above code will generate 10 unique random numbers and print them out. You can adjust the value of n and the range for generating the random numbers as needed.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds