It mainly introduces three methods of obtaining random numbers in Java, mainly using the random() function to implement it
Method 1
(Data type) (minimum value + Math.random()*(maximum value -minimum value +1)) Example:
(int)(1+Math.random()*(10-1+1))
Int type from 1 to 10
Method 2
Obtain a random number
for (int i=0;i<30;i++){System.out.println((int)(1+Math.random()*10));}(int)(1+Math.random()*10) The random method of the java.Math package gets an int random number of 1-10
The formula is: minimum value----random number of maximum value (integral)
(Type) Min + Math.random() * Maximum Value
Method 3
Random ra =new Random();for (int i=0;i<30;i++){System.out.println(ra.nextInt(10)+1);} Use the nextInt method of Random class in java.util package to get an int random number of 1-10
Generate any random decimals between 0 and 1:
To generate a random decimal in the interval [0,d) and d is any positive decimal, you only need to multiply the return value of the nextDouble method by d.
[n1, n2]
That is ra.nextDouble() * (n2-n1)+n1
Several ways to generate random numbers in java
1. In j2se, we can use the Math.random() method to generate a random number. The random number generated is a double between 0-1. We can multiply it by a certain number, for example, multiply by 100. It is a random within 100. This does not exist in j2me.
2. In the java.util package, a Random class is provided. We can create a new Random object to generate random numbers. It can generate random integers, random floats, random doubles, and random long. This is also a method of taking random numbers that we often use in j2me programs.
3. There is a currentTimeMillis() method in our System class. This method returns a millisecond number from 0:00:00 on January 1, 1970 to the current one. The return type is long. We can use it as a random number. We can use it to modulo some numbers, and limit it to a range.
In fact, in Random's default construction method, the third method above is used to generate random numbers.
The Random class in method two has the following description:
There are two ways to build the java.util.Random class: with seeds and without seeds
No seeds:
This method will return random numbers, and the results will be different for each run.
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());}} With seeds:
In this way, no matter how many times the program runs, the return result will be 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
(1) First, please open Java Doc, we will see the description of the Random class:
Examples of this class are used to generate pseudo-random number streams, which use a 48-bit seed that can be modified using a linear congruent formula.
If two Random instances are created with the same seed, the same sequence of method calls is made to each instance and they will generate and return the same sequence of numbers. To ensure that this feature is implemented, we specify a specific algorithm for the class Random. For full portability of Java code, Java implementations must have the class Random use all the algorithms shown here. But subclasses of Random class are allowed to use other algorithms as long as they comply with the conventional agreements of all methods.
Java Doc has explained the Random class very well, and our tests have verified this.
(2) If no seed number is provided, the number of seeds of the Random instance will be the milliseconds of the current time. You can obtain the milliseconds of the current time through System.currentTimeMillis(). Open the source code of JDK and we can see this very clearly.
public Random() { this(System.currentTimeMillis()); } in addition:
Description of the nextInt(), nextInt(int n) methods of the random object:
int nextInt() //Returns the next pseudo-random number, which is the evenly distributed int value in the sequence of this random number generator.
int nextInt(int n) //Returns a pseudo-random number, which is an int value evenly distributed between 0 (including) and the specified value (excluding) taken from the sequence of this random number generator.
Java random number summary
Random numbers are widely used in practice, such as generating a fixed-length string or number. Either then generate a number of uncertain length, or perform a simulated random selection, etc. Java provides the most basic tools that can help developers achieve all of this.
1. How to generate Java random numbers
In Java, there are three general concepts of random numbers.
1. Use System.currentTimeMillis() to get a long-type number of milliseconds in the current time.
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.
2. Random API description
1. Java API description
An instance of the Random class is used to generate a pseudo-random number stream. This class uses 48-bit seeds and uses a linear congruent formula to modify them (see Donald Knuth's The Art of Computer Programming, Volume 2, Section 3.2.1).
If two Random instances are created with the same seed, the same sequence of method calls is made to each instance and they will generate and return the same sequence of numbers. In order to ensure the implementation of attributes, a specific algorithm is specified for the class Random.
Many applications will find the random method in the Math class easier to use.
2. Method Summary
Random() //Create a new random number generator.
Random(long seed) //Create a new random number generator using a single long seed: public Random(long seed) { setSeed(seed); } next method uses it to save the state of the random number generator.
protected int next(int bits): generates the next pseudo-random number.
boolean nextBoolean(): Returns the next pseudo-random number, which is the evenly distributed boolean value taken from the sequence of this random number generator.
void nextBytes(byte[] bytes): generates random bytes and places them in a user-provided byte array.
double nextDouble(): Returns the next pseudo-random number, which is a double value evenly distributed between 0.0 and 1.0, taken from the sequence of this random number generator.
float nextFloat(): Returns the next pseudo-random number, which is a float value evenly distributed between 0.0 and 1.0 taken from the sequence of this random number generator.
double nextGaussian(): Returns the next pseudo-random number, which is a Gaussian ("normally") distribution taken from the sequence of this random number generator, with an average value of 0.0 and a standard deviation of 1.0.
int nextInt(): Returns the next pseudo-random number, which is the evenly distributed int value in the sequence of this random number generator.
int nextInt(int n): Returns a pseudo-random number that is a uniformly distributed int value taken from the sequence of this random number generator and is uniformly distributed between 0 (including) and the specified value (excluding).
long nextLong(): Returns the next pseudo-random number, which is a uniformly distributed long value taken from the sequence of this random number generator.
void setSeed(long seed): Sets the seed of this random number generator using a single long seed.
3. Random class usage instructions
1. The difference between taking seeds and not taking seeds. The fundamental use of Random class is to divide the examples of Random with seeds and without seeds.
In layman's terms, the difference between the two is: if the seeds are produced, the results generated by each run are the same.
If you don’t have seeds, what you generate is random every time you run, and there is no pattern at all.
2. Create a Random object without seeds
Random random = new Random();
3. There are two ways to create a Random object without seeds:
1) Random random = new Random(555L);
2) Random random = new Random();random.setSeed(555L);
4. Test
Use an example to illustrate the usage above
import java.util.Random; public class TestRandomNum { public static void main(String[] args) { randomTest(); testNoSeed(); testSeed1(); testSeed2(); } public static void randomTest() { System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- long r1 = System.currentTimeMillis(); //Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. double r2 = Math.random(); //Get 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("----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Random(); for (int i = 0; i < 3; i++) { System.out.println(random.nextInt()); } } public static void testSeed1() { System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- System.out.println("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Running results:
--------------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
Through the results of testSeed1() and testSeed2() methods, we can see that the two print results are the same because they see the same. If they run again, the result will still be the same. This is the characteristic of random numbers with seeds. If you don't have seeds, the results of each run are random.
V. Comprehensive application
The following is a recently written random number tool class to show the usage:
import java.util.Random; public class RandomUtils { public static final String allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final String letterChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final String numberChar = "0123456789"; 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(); } 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(); } public static String generateLowerString(int length) { return generateMixString(length).toLowerCase(); } public static String generateUpperString(int length) { return generateMixString(length).toUpperCase(); } public static String generateZeroString(int length) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { sb.append('0'); } return sb.toString(); } 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 + "Exception occurs when an exception is made to a string with length " + fixdlenth + "); } sb.append(strNum); return sb.toString(); } 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 + "Exception occurs when an exception is made in a string with length " + fixdlenth + "); } 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)); System.out.println(toFixdLengthString(123L, 15)); } }Running results:
vWMBPiNbzfGCpHG
23hyraHdJkKPwMv
tigowetbwkm1nde
BPZ1KNEJPHB115N
000000000000000000
00000000000000123
00000000000000123
Process finished with exit code 0
6. Summary
1. Random numbers are very commonly used. There are three ways to generate them in Java. Random random numbers are the most complex.
2. Random class objects have a difference between whether they carry seeds. As long as the seeds are the same, they run multiple times, and the result of generating random numbers is always the same.
3. There are two ways to create seed objects with random numbers, with the same effect. But random numbers with seeds don't seem to be of much use.
4. Random's functions cover the functions of Math.random().
5. You can use random numbers to implement complex random data such as random strings.
6. Don’t study random numbers that don’t repeat, it’s not very meaningful.
In Java we can use the java.util.Random class to generate a random number generator. It has two forms of constructors, namely Random() and Random(long seed). Random() uses the current time, System.currentTimeMillis(), 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(), etc.
1>Generate random numbers
Random random = new Random(); Random random = new Random(100);//Specify the number of seeds 100
random calls different methods to get random numbers.
If 2 Random objects use the same seed (for example, both are 100) and the same function is called in the same order, then their return values are exactly the same. As in the following code, the output of the two Random objects is exactly the same
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 numbers in the specified range
Random numbers are controlled within a certain range, using the modulus operator %
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())); } } }The random numbers obtained are positive and negative. Use Math.abs to make the data range retrieved as non-negative numbers.
3> Get non-repetitive random numbers within the specified range
import java.util.*; class TestRandom { public static void main(String[] args) { int[] intRet = new int[6]; intRd = 0; //Storage random numbers int count = 0; //Record the generated random numbers int flag = 0; //Whether the flag has been generated while(count<6){ Random rdm = new Random(System.currentTimeMillis()); intRd = Math.abs(rdm.nextInt())2+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 question in mind, 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 results:
-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 above test we can see that the random numbers generated by using the Random() constructor without parameters will not be repeated. So, under what circumstances does Java produce duplicate random numbers? Let’s see the test below.
2. Test 2: Set the number of seeds for Random
public class RandomTest_Repeat { 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
Even if you test it on different machines, the test results will not change!
3. Cause analysis:
(1) First, please open Java Doc, we will see the description of the Random class:
Examples of this class are used to generate pseudo-random number streams, which use a 48-bit seed that can be modified using a linear congruent formula (see Donald Knuth's The Art of Computer Programming, Volume 2, Section 3.2.1).
If two Random instances are created with the same seed, the same sequence of method calls is made to each instance and they will generate and return the same sequence of numbers. To ensure that this feature is implemented, we specify a specific algorithm for the class Random. For full portability of Java code, Java implementations must have the class Random use all the algorithms shown here. But subclasses of Random class are allowed to use other algorithms as long as they comply with the conventional agreements of all methods.
Java Doc has explained the Random class very well, and our tests have verified this.
(2) If no seed number is provided, the number of seeds of the Random instance will be the milliseconds of the current time. You can obtain the milliseconds of the current time through System.currentTimeMillis(). Open the source code of JDK and we can see this very clearly.
public Random() { this(System.currentTimeMillis()); } 4. Conclusion:
Through the above tests and analysis, we will have a deeper understanding of the Random class. At the same time, I think that by reading the Java Doc API documentation, our Java programming capabilities can be greatly improved and "knowing the truth" can be achieved; once we encounter puzzled problems, we might as well open the Java source code so that we can "knowing the truth".
There are generally two types of random numbers in Java, one is the random() method in Math, and the other is the Random class.
1. Math.random()
A decimal number of 0<x<1 is generated.
Example: How to write and generate randomly one of the numbers from 0 to 100?
Math.random() returns only a decimal from 0 to 1. If you want 50 to 100, you will zoom in 50 times first, that is, between 0 and 50. Here is still a decimal. If you want an integer, you will cast int, and then add 50 to 50 to 100.
Final code: (int)(Math.random()*50) + 50
2. Random class
Random random = new Random();//Default constructor Random random = new Random(1000);//Specify seed number
When performing randomization, the number of origin of the random algorithm is called seeds, which performs a certain transformation based on the seeds, thereby generating the required random numbers.
Random objects with the same number of seeds, the random numbers generated by the same number of times are exactly the same. In other words, for two Random objects with the same seed number, the random numbers generated for the first time are exactly the same, and the random numbers generated for the second time are exactly the same.
2. Common methods in Random class
The methods in the Random class are relatively simple, and the functions of each method are also easy to understand. It should be noted that the random numbers generated by each method in the Random class are uniformly distributed, which means that the probability of numerical generation within the interval is equal. Here is a basic introduction to these methods:
a , public boolean nextBoolean()
The function of this method is to generate a random boolean value, and the probability of generating true and false values is equal, that is, both are 50%.
b, public double nextDouble()
The purpose of this method is to generate a random double value, the value is between [0, 1.0). Here, the brackets represent the endpoints containing the interval, and the brackets represent the endpoints that do not include the interval, that is, a random decimal between 0 and 1, containing 0 but not 1.0.
c, public int nextInt()
The purpose of this method is to generate a random int value, which is between the 31st power of -2 and 31st power of -1st power of 2.
If you need to generate an int value for a specified interval, you need to perform a certain mathematical transformation. For details, please refer to the code in the usage example below.
d , public int nextInt(int n)
The function of this method is to generate a random int value, which is within the interval of [0, n), that is, a random int value between 0 and n, containing 0 but not n.
If you want to generate an int value for a specified interval, you also need to perform a certain mathematical transformation. For details, please refer to the code in the usage example below.
e, public void setSeed(long seed)
The purpose of this method is to reset the number of seeds in the Random object. After setting the number of seeds, the Random object is the same as the Random object created with the new keyword.
3. Random class usage example
Using the Random class, it is generally to generate random numbers for a specified interval. The following will introduce how to generate random numbers for a corresponding interval one by one. The following codes that generate random numbers are generated using the following Random object r:
Random r = new Random();
a. Generate decimals of the interval [0,1.0)
double d1 = r.nextDouble();
It is obtained directly using the nextDouble method.
b. Generate decimals of the interval [0,5.0)
double d2 = r.nextDouble() * 5;
Because the number interval generated by the nextDouble method is [0, 1.0), expanding the interval by 5 times is the required interval.
Similarly, to generate a random decimal in the interval [0,d) and d is any positive decimal, you only need to multiply the return value of the nextDouble method by d.
c. Generate the decimal number [n1, n2] of the interval [1, 2.5) [1]
double d3 = r.nextDouble() * 1.5 + 1;【that is, r.nextDouble() * (n2-n1)+n1】
To generate a random decimal of the interval [1, 2.5) you only need to first generate a random number of the interval [0, 1.5) and then add 1 to the generated random number interval.
Similarly, to generate any random number in the range of decimal interval [d1, d2) that does not start from 0 (where d1 is not equal to 0), you only need to first generate a random number in the interval [0, d2-d1) and then add the generated random number interval to d1.
d. Generate any integer
int n1 = r.nextInt();
Just use the nextInt method directly.
e. Generate integers in interval [0,10)
int n2 = r.nextInt(10);n2 = Math.abs(r.nextInt() % 10);
The above two lines of code can generate integers in the interval [0,10).
The first implementation is directly implemented using the nextInt(int n) method in the Random class.
In the second implementation, first call nextInt() method to generate an arbitrary int number. The interval generated by the number sum of the number 10 is (-10,10), because according to the mathematical specification, the absolute value of the remainder is less than the divisor, and then the absolute value of the interval is calculated, and the resulting interval is [0,10).
Similarly, to generate random integers in any interval [0, n) you can use the following code:
int n2 = r.nextInt(n);n2 = Math.abs(r.nextInt() % n);
f. Generate integers in interval [0,10]
int n3 = r.nextInt(11);n3 = Math.abs(r.nextInt() % 11);
Compared with the integer interval, the [0,10] interval and the [0,11) interval are equivalent, so an integer of the [0,11) interval is generated.
g. Generate integers in the interval [-3,15)
int n4 = r.nextInt(18) - 3; //【that is, r.nextInt() * (n2-n1)+n1】 n1 is a negative number n4 = Math.abs(r.nextInt() % 18) - 3;
To generate random integers that do not start from 0, you can refer to the above description of the implementation principle of the decimal interval that does not start from 0.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.