Random Numbers in Java

  • 2020-04-01 03:00:21
  • OfStack

In Java we can use the java.util.random class to generate a Random number. It has two constructors, Random() and Random(long seed). Random() USES the current time, system.currenttimemillis (), as the generator's seed, and Random(long seed) USES the specified seed as the generator's seed.

When the Random number generator is a Random object, different types of Random Numbers can be obtained by calling different methods of the object: nextInt(), nextLong(), nextFloat(), nextDouble(), etc. If two Random objects use the same seed (say, both 100) and call the same function in the same order, their return values are exactly the same.
More useless words, I first hold up a chestnut, the following code:

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201402/2014221145602037.jpg" >

But what if I want a range of Numbers? For example, if I want to randomly generate a random number between 0 and 99, we can use the modulus operator %.
The purpose of applying the modulus operator % to the random number generated by the random number generator is to make the maximum value of the random number fall within the range of the specified operand value minus 1. Look at the following code to control the input within a range of 0 to 99. (note: if you do not add math.abs (), the output range will be -99~99. )
Let's look at the case without math.abs (), as follows

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201402/2014221145700308.jpg" >

Look at the added situation, as follows:

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201402/2014221145803604.jpg" >


Related articles: