# Java Random Number Details

Source: Internet
Author: User
 Method 1(Data Type) (minimum value + math. Random () * (maximum value-Minimum value + 1 ))Example:(INT) (1 + math. Random () * (10-1 + 1 ))INT-type numbers from 1 to 10Method 2Obtain Random NumberFor (INT I = 0; I <30; I ++){System. Out. println (INT) (1 + math. Random () * 10 ));}(INT) (1 + math. Random () * 10)Use the random method of the Java. Math package to obtain the random number of int values 1-10.Formula: Minimum value --- Random Number of the maximum value (integer)(Type) Minimum value + math. Random () * Maximum ValueMethod 3Random Ra = new random ();For (INT I = 0; I <30; I ++){System. Out. println (RA. nextint (10) + 1 );}Use the nextint method of the random class in the Java. util package to obtain a random number of 1-10 int

Several Methods for Java to generate random numbers
I. in j2se, we can use math. the random number generated by the random () method is a double between 0 and 1. We can multiply it by a certain number, for example, by 100, it is a random value of less than 100, which is not found in j2s.

II. in Java. the util package provides a random class. We can create a new random object to generate a random number. It can generate random integers, random float, random double, random long, this is also a method that we often use to retrieve random numbers in the j2's program.

III. there is a currenttimemillis () method in our system class. This method returns a millisecond value from 00:00:00, January 1, January 1, 1970. The return type is long. We can use it as a random number, we can use him to modulo some numbers to limit him to a certain range.

In fact, the default construction method of random also uses the third method to generate random numbers.

The random class in method 2 is described as follows:

The Java. util. Random class can be constructed in either of the following ways: With or without seeds

Without seeds:
This method will return random numbers with different running results

Public class randomtest {
Public static void main (string [] ARGs ){
Java. util. Random r = new java. util. Random ();
For (INT I = 0; I <10; I ++ ){
System. Out. println (R. nextint ());
}

}
Seed:
In this way, no matter how many times the program runs, the returned results are the same.

Public static void main (string [] ARGs ){
Java. util. Random r = new java. util. Random (10 );
For (INT I = 0; I <10; I ++ ){
System. Out. println (R. nextint ());
}
}

The difference between the two methods is that

(1) first open Java Doc and we will see the description of the random class:

An instance of this type is used to generate a pseudo-random number stream. This class uses a 48-bit seed, which can be modified using a linear same formula (see the art of computer programming in Donald knuth, volume 2, section 3.2.1 ).

If two random instances are created with the same seed, the same method call sequence is performed for each instance. they generate and return the same numerical sequence. To ensure the implementation of this feature, we specify a specific algorithm for the class random. To ensure full portability of Java code, Java implementation must allow the class random to use all the algorithms shown here. However, to allow sub-classes of the random class to use other algorithms, you only need to comply with the common protocols of all methods.

Java Doc has clearly explained the random class and our tests have also proved this.

(2) If the number of seeds is not provided, the number of seeds in the random instance will be the number of milliseconds in the current time. You can use system. currenttimemillis () to obtain the number of milliseconds in the current time. Open the source code of JDK and we can see this clearly.

/**
* Creates a new random number generator. Its seed is initialized
* A value based on the current time:
* Random () {This (system. currenttimemillis ();} java. Lang. System # currenttimemillis ()

*/
Public random () {This (system. currenttimemillis ());}

Description of the nextint () and nextint (int n) Methods of the random object:

Int nextint ()
Returns the next pseudo-random number, which is the int value uniformly distributed in the sequence of the random number generator.
Int nextint (int n)
Returns a pseudo-random number, which is an int value that is obtained from the sequence of the random number generator and evenly distributed between 0 (inclusive) and the specified value (excluded.

Java random number Summary

Random numbers are widely used in practice. For example, a fixed-length string or number must be generated immediately. You can also generate a number with an indefinite length or make a simulated random selection. Java provides the most basic tools to help developers achieve this.

I. Method of Generating Java random numbers

In Java, there are three types of random numbers in a broad sense.

1. Use System. currenttimemillis () to obtain a long number in milliseconds.

2. Return a double value between 0 and 1 through math. Random.

3. Generate a random number through the random class. This is a professional random tool class with powerful functions.

Ii. Random APIs

1. Java API description

An instance of the random class is used to generate a pseudo-random number stream. This class uses a 48-bit seed and uses a linear Coordinator formula to modify it (see section 3.2.1 of the art of computer programming, Volume 2 of Donald knuth ).

If two random instances are created with the same seed, the same method call sequence is performed for each instance. they generate and return the same numerical sequence. To ensure the implementation of attributes, a specific algorithm is specified for the class random.

Many applications will find that the random method in the math class is easier to use.

2. method summary

Random ()

Create a new random number generator.

Random (long seed)

Use a single long seed to create a new random number generator: Public random (long seed) {setseed (SEED);} next to use it to save the status of the random number generator.

Protected int next (INT bits)

Generate the next pseudo-random number.

Boolean nextboolean ()

Returns the next pseudo-random number, which is a Boolean value that is evenly distributed from the sequence of the random number generator.

Void nextbytes (byte [] bytes)

Generate random bytes and place them in the byte array provided by the user.

Double nextdouble ()

Returns the next pseudo-random number, which is a double value that is obtained from the sequence of the random number generator and evenly distributed between 0.0 and 1.0.

Float nextfloat ()

Returns the next pseudo-random number, which is a float value that is obtained from the sequence of the random number generator and evenly distributed between 0.0 and 1.0.

Double nextgaussian ()

Returns the next pseudo-random number, which is a double value that is obtained from the sequence of the random number generator in Gaussian ("normal") distribution. The average value is 0.0, and the standard deviation is 1.0.

Int nextint ()

Returns the next pseudo-random number, which is the int value uniformly distributed in the sequence of the random number generator.

Int nextint (int n)

Returns a pseudo-random number, which is an int value that is obtained from the sequence of the random number generator and evenly distributed between 0 (inclusive) and the specified value (excluded.

Long nextlong ()

Returns the next pseudo-random number, which is a long value that is evenly distributed from the sequence of the random number generator.

Void setseed (long seed)

Use a single long seed to set the seed of the random number generator.

Iii. Random usage instructions

1. What is the difference between a random class with and without seeds is that the random class uses instances with and without seeds.

In general, the difference between the two is: the results generated by each running are the same.

Without seeds, each running generates random and irregular data.

2. Create a random object without seeds

Random random = new random ();

3. There are two methods to create a random object without seeds:

1) random = new random (555l );

2) random = new random (); random. setseed (555l );

Iv. Test

Use an example to describe the above usage

Import java. util. Random;

/**

* Java random number Test

* User: leizhimin

* Date: 17:52:50

*/

Public class testrandomnum {

Public static void main (string [] ARGs ){

Randomtest ();

Testnoseed ();

Testseed1 ();

Testseed2 ();

}

Public static void randomtest (){

System. Out. println ("-------------- test ()--------------");

// Returns the current time in milliseconds.

Long R1 = system. currenttimemillis ();

// Return the double value with the positive number, which is greater than or equal to 0.0 and less than 1.0.

Double r2 = math. Random ();

// Obtain the next random integer through the random class

Int R3 = new random (). nextint ();

System. Out. println ("R1 =" + R1 );

System. Out. println ("R3 =" + R2 );

System. Out. println ("R2 =" + R3 );

}

Public static void testnoseed (){

System. Out. println ("-------------- testnoseed ()--------------");

// Create a test random object without seeds

Random random = new random ();

For (INT I = 0; I <3; I ++ ){

System. Out. println (random. nextint ());

}

}

Public static void testseed1 (){

System. Out. println ("-------------- testseed1 ()--------------");

// Create a testing random object with seeds

Random random = new random (555l );

For (INT I = 0; I <3; I ++ ){

System. Out. println (random. nextint ());

}

}

Public static void testseed2 (){

System. Out. println ("-------------- testseed2 ()--------------");

// Create a testing random object with seeds

Random random = new random ();

Random. setseed (555l );

For (INT I = 0; I <3; I ++ ){

System. Out. println (random. nextint ());

}

}

}

Running result:

-------------- Test ()--------------

R1 = 1227108626582

R3 = 0.5324887850155043

R2 =-368083737

-------------- Testnoseed ()--------------

809503475

1585541532

-645134204

-------------- Testseed1 ()--------------

-1367481220

292886146

-1462441651

-------------- Testseed2 ()--------------

-1367481220

292886146

-1462441651

Process finished with exit code 0

We can see from the results of testseed1 () and testseed2 () methods that the two printed results are the same, because they have the same seeds and run them again, and the results are the same, this is the feature of random numbers with seeds.

Without seeds, the results of each operation are random.

5. Comprehensive Application

The following shows the usage using a recently written random number tool class:

Import java. util. Random;

/**

* Random number, instant string Tool

* User: leizhimin

* Date: 9:43:09

*/

Public class randomutils {

Public static final string allchar = "0123456789 abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz ";

Public static final string letterchar = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz ";

Public static final string numberchar = "0123456789 ";

/**

* Returns a random string with a fixed length (only including uppercase and lowercase letters and numbers)

*

* @ Param length: Random String Length

* @ Return random string

*/

Public static string generatestring (INT length ){

Stringbuffer sb = new stringbuffer ();

Random random = new random ();

For (INT I = 0; I <length; I ++ ){

SB. append (allchar. charat (random. nextint (allchar. Length ())));

}

Return sb. tostring ();

}

/**

* Returns a fixed-length random pure letter string (only including uppercase and lowercase letters)

*

* @ Param length: Random String Length

* @ Return random string

*/

Public static string generatemixstring (INT length ){

Stringbuffer sb = new stringbuffer ();

Random random = new random ();

For (INT I = 0; I <length; I ++ ){

SB. append (allchar. charat (random. nextint (letterchar. Length ())));

}

Return sb. tostring ();

}

/**

* Returns a random string of uppercase and lowercase letters with a fixed length)

*

* @ Param length: Random String Length

* @ Return random string

*/

Public static string generatelowerstring (INT length ){

Return generatemixstring (length). tolowercase ();

}

/**

* Returns a fixed length random lowercase letter string (only including uppercase and lowercase letters)

*

* @ Param length: Random String Length

* @ Return random string

*/

Public static string generateupperstring (INT length ){

Return generatemixstring (length). touppercase ();

}

/**

* Generate a fixed-length pure 0 string

*

* @ Param length: String Length

* @ Return pure 0 string

*/

Public static string generatezerostring (INT length ){

Stringbuffer sb = new stringbuffer ();

For (INT I = 0; I <length; I ++ ){

SB. append ('0 ');

}

Return sb. tostring ();

}

/**

* Generate a fixed-length string based on numbers. If the length is not enough, add 0.

*

* @ Param num number

* @ Param fixdlenth String Length

* @ Return a fixed-length string

*/

Public static string tofixdlengthstring (long num, int fixdlenth ){

Stringbuffer sb = new stringbuffer ();

String strnum = string. valueof (Num );

If (fixdlenth-strnum. Length ()> = 0 ){

SB. append (generatezerostring (fixdlenth-strnum. Length ()));

} Else {

Throw new runtimeexception ("Convert number" + num + "to string with length of" + fixdlenth + "exception! ");

}

SB. append (strnum );

Return sb. tostring ();

}

/**

* Generate a fixed-length string based on numbers. If the length is not enough, add 0.

*

* @ Param num number

* @ Param fixdlenth String Length

* @ Return a fixed-length string

*/

Public static string tofixdlengthstring (INT num, int fixdlenth ){

Stringbuffer sb = new stringbuffer ();

String strnum = string. valueof (Num );

If (fixdlenth-strnum. Length ()> = 0 ){

SB. append (generatezerostring (fixdlenth-strnum. Length ()));

} Else {

Throw new runtimeexception ("Convert number" + num + "to string with length of" + fixdlenth + "exception! ");

}

SB. append (strnum );

Return sb. tostring ();

}

Public static void main (string [] ARGs ){

System. Out. println (generatestring (15 ));

System. Out. println (generatemixstring (15 ));

System. Out. println (generatelowerstring (15 ));

System. Out. println (generateupperstring (15 ));

System. Out. println (generatezerostring (15 ));

System. Out. println (tofixdlengthstring (123, 15 ));

System. Out. println (tofixdlengthstring (123l, 15 ));

}

}

Running result:

Vwmbpinbzfgcphg

23 hyrahdjkkpwmv

Tigowetbwkm1nde

Bpz1knejphb115n

000000000000000

000000000000123

000000000000123

Process finished with exit code 0

Vi. Summary

1. Random numbers are very common. There are three methods to generate random numbers in Java. The use of random numbers in random is the most complex.

2. Whether a random object contains seeds. If the seeds are the same and run multiple times, the random number generation result is always the same.

3. There are two ways to create a seed object with a seed random number, with the same effect. However, random numbers with seeds seem useless.

4. the random function covers the math. Random () function.

5. Complex random data such as random strings can be implemented using random numbers.

6. Do not study random numbers that are not repeated, which is of little significance.

In Java, we can use the java. util. Random class to generate a random number generator. It has two forms of constructor: Random () and random (long seed ). Random () uses the current time (system. currenttimemillis () as the generator seed, and random (long seed) uses the specified seed as the generator seed.

After a random number generator (random) object is generated, different types of random numbers are obtained by calling different methods: nextint (), nextlong (), nextfloat (), and nextdouble.

1> generate random number
Random random = new random ();
Random random = new random (100); // specify the number of seeds as 100
Random calls different methods to obtain random numbers.
If two random objects use the same seed (for example, 100) and call the same function in the same order, they return identical values. For example, the output of the two random objects in the following code is identical.
Import java. util .*;
Class testrandom {
Public static void main (string [] ARGs ){
Random random1 = new random (100 );
System. Out. println (random1.nextint ());
System. Out. println (random1.nextfloat ());
System. Out. println (random1.nextboolean ());
Random random2 = new random (100 );
System. Out. println (random2.nextint ());
System. Out. println (random2.nextfloat ());
System. Out. println (random2.nextboolean ());
}
}

2> random number within the specified range
The random number is controlled within a certain range and the modulus operator % is used.
Import java. util .*;
Class testrandom {
Public static void main (string [] ARGs ){
Random random = new random ();
For (INT I = 0; I <10; I ++ ){
System. Out. println (math. Abs (random. nextint () % 10 );
}
}
}
The obtained random number has positive and negative values. use math. ABS to make the obtained data range non-negative.

3> obtain random numbers within the specified range
Import java. util .*;
Class testrandom {
Public static void main (string [] ARGs ){
Int [] intret = new int ;
Int intrd = 0; // store random numbers
Int COUNT = 0; // record the number of random numbers generated
Int flag = 0; // whether the flag has been generated
While (count <6 ){
Random RDM = new random (system. currenttimemillis ());
Intrd = math. Abs (RDM. nextint () % 32 + 1;
For (INT I = 0; I <count; I ++ ){
If (intret [I] = intrd ){
Flag = 1;
Break;
} Else {
Flag = 0;
}
}
If (flag = 0 ){
Intret [count] = intrd;
Count ++;
}
}
For (int t = 0; t <6; t ++ ){
System. Out. println (t + "->" + intret [T]);
}
}
}
Can random numbers in Java be repeated? Can random numbers generated in Java be used to generate database primary keys? With this problem, we did a series of tests.
1. Test 1: Use the random () constructor without Parameters

Public class randomtest {

Public static void main (string [] ARGs ){
Java. util. Random r = new java. util. Random ();
For (INT I = 0; I <10; I ++ ){
System. Out. println (R. nextint ());
}
}
}
Program running result:
-1761145445
-1070533012
216216989
-910884656
-1408725314
-1091802870
1681403823
-1099867456
347034376
-1277853157

Run the program again:
-169416241
220377062
-1140589550
-1364404766
-1088116756
2134626361
-546049728
1132916742
-1522319721
1787867608

From the test above, we can see that the random number generated by using the random () constructor without parameters will not be repeated. So, under what circumstances will Java generate repeated random numbers? See the following test.

2. Test 2: set the number of seeds for random

Public class randomtest_repeat {
/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
Java. util. Random r = new java. util. Random (10 );
For (INT I = 0; I <10; I ++ ){
System. Out. println (R. nextint ());
}
}
}

No matter how many times the program runs, the result is always:
-1157793070
1913984760
1107254586
1773446580
254270492
-1408064384
1048475594
1581279777
-778209333
1532292428

Test results won't change even on different machines!

3. Cause Analysis:
(1) first open Java Doc and we will see the description of the random class:
An instance of this type is used to generate a pseudo-random number stream. This class uses a 48-bit seed, which can be modified using a linear same formula (see the art of computer programming in Donald knuth, volume 2, section 3.2.1 ).
If two random instances are created with the same seed, the same method call sequence is performed for each instance. they generate and return the same numerical sequence. To ensure the implementation of this feature, we specify a specific algorithm for the class random. To ensure full portability of Java code, Java implementation must allow the class random to use all the algorithms shown here. However, to allow sub-classes of the random class to use other algorithms, you only need to comply with the common protocols of all methods.
Java Doc has clearly explained the random class and our tests have also proved this.

(2) If the number of seeds is not provided, the number of seeds in the random instance will be the number of milliseconds in the current time. You can use system. currenttimemillis () to obtain the number of milliseconds in the current time. Open the source code of JDK and we can see this clearly.
/**
* Creates a new random number generator. Its seed is initialized
* A value based on the current time:
* <BLOCKQUOTE> <PRE>
* Public random () {This (system. currenttimemillis () ;}</PRE> </BLOCKQUOTE>
*
* @ See java. Lang. System # currenttimemillis ()
*/
Public random () {This (system. currenttimemillis ());}

4. Conclusion:
Through the above tests and analysis, we will have a deep understanding of the random class. At the same time, I think that by reading the API documentation of Java Doc, we can improve our Java programming capability and "know it". Once you encounter a puzzling problem, open the source code of Java so that we can "know why ".

Related Keywords:
Related Article

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.