Java random number Summary

Source: Internet
Author: User
Tags time in milliseconds
Copyright:Original works. If you need to reprint them, please contact the author. Otherwise, legal liability will be held.
Java random number SummaryRandom 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 numbersIn 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 APIs1. Java API description the random class instance 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 instructions1. Differences between seed and Seed
The random class uses instances with seeds or without seeds.
In general, the difference between the two is:
The results generated by each running with seeds 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 ways to create a random object with seeds: 1) random = new random (555l );
2) random = new random (); random. setseed (555l );

Iv. TestAn example is provided to illustrate 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 ApplicationThe following uses a random number tool class recently written to demonstrate its usage: 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. Summary1. 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.

This article is from the "fuyan" blog. For more information, contact the author!

This article is from 51cto. com technical blog

Related Article

Contact Us

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.