Home > Java > JavaBase > Generate unique random numbers java

Generate unique random numbers java

angryTom
Release: 2019-11-11 13:40:47
Original
2966 people have browsed it

Generate unique random numbers java

Generate non-repeating random numbers java

java can use the method in the Math class to generate random numbers. If it is not random, you can use List for judgment storage. (Recommended tutorial: java tutorial )

1. Call the random() method in the Math class below java.lang to generate random numbers

Create a new file with the suffix name java, and the file name is MyRandom. Write the following code in this class:

public class MyRandom {
    public static void main(String[] args) {
        int radom = (int)(Math.random()*10);
        System.out.println(radom);
    }
}
Copy after login

Math.random() //Produces 0~1 a random decimal between.

To generate an integer between 0 and 9 is: (int)(Math.random()*10);

To generate an integer between 1 and 10 you can write: (int)(Math.random()*10 1);

And so on: to generate a number between 0 and n, it should be written as: Math.random()*n;

For example: Generate an int type array with a length of 50, and insert numbers between 0-50 into it randomly, and they cannot be repeated.

2. Use the contains method of List to make repeated judgments

public class MyRandom {
public static void main(String[] args) {
    int[] intRandom = new int[50];
    List mylist = new ArrayList(); //生成数据集,用来保存随即生成数,并用于判断
    Random rd = new Random();
    while(mylist.size() < 50) {
        int num = rd.nextInt(51);
        if(!mylist.contains(num)) {
        mylist.add(num); //往集合里面添加数据。
    }
    }
    for(int i = 0;i <mylist.size();i++) {
        intRandom[i] = (Integer)(mylist.get(i));
    }
}
}
Copy after login

The above is the detailed content of Generate unique random numbers java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template