Generate random numbers in java
One, the specific method:
1, java.util.Random class
You can use the java.util.Random class to construct a random number generator. There are two constructors:
(1) Random(): Create a new random number generator
(2) Random(long seed): Create a single long seed A new random number generator.
Example:
(1)
Here we use the parameterless constructor of the Random class to generate a random generator r, and use nextInt(100) to generate any number in [0,100).
You can also use nextInt(), nextBoolean(), nextDouble(), nextFloat(), nextLong() to generate other types of random numbers. Among them, nextDouble() and nextFloat() are both randomly generated a floating point number in [0,1).
**Note: ** Only when generating random integers can you specify the upper limit of the number of generations, but not when generating Double, Float, Long, and Boolean values. For example, you can only use nextDouble() instead of nextDouble(Double d).
(2)
Here, the seed of the random number generator r is set to 5, and the random number generated every time the code is executed is the same number.
**Note:** For different random number generators, if their seed values are the same, they will generate the same value of the same type. For example:
The random integer values generated by w and r are both 87.
2. Math.random() method
The Math.random() method returns a double value in the range [0.0,1.0).
Generate an integer within [0,100): int x=(int)(Math.random()*100);
Generate a random number between [1,50]: int x=1+(int)(Math.random ()*50)