Java randomly extracts n numbers that are not repeated within the specified range

1、 How to generate random numbers in Java 1. Use math in J2SE Random() makes the system randomly select a double decimal between 0 and 1 and multiply it by a number, such as 25, to get a random number in the range of 0 ~ 25, which is not available in J2ME;

2. There is a currenttimemillis () method in the system class. This method returns a long type millisecond from 0:0:0:0 on January 1, 1970 to the present. It can be used as a random number. It can also be modeled on some numbers to limit the range of random numbers; In this way, when multiple random numbers are generated simultaneously in the loop, they will be the same value, which has certain limitations!

3. Using Java util. Random class to generate a random number generator, which is also a method of taking random numbers often used in J2ME programs. It has two forms of constructors, random () and random (long seed). Random() uses the current time, system Currenttimemillis() is used as the seed of the generator, and random (long seed) uses the specified seed as the seed of the generator. After the random number generator (random) object is generated, different types of random numbers are obtained by calling different methods: nextint(), nextlong(), nextfloat(), nextdouble(). If two random objects use the same seed (for example, 25) and call the same functions in the same order, their return values are exactly the same.

2、 N non repeated numbers in a random given range 1. Method 1: the simplest and most understandable double cycle de duplication

2. Method 2: only different values can be stored by using the characteristics of HashSet

3. Method 3: exclude random numbers

Call instance:

3、 Sample code

The above is the whole content of this article. I hope it will help you learn java programming.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>