In java we can use the java.util.Random class to generate a random number to occur. It has two constructors, namely Random() and Random(long seed). Random() uses the current time, System.currentTimeMillis(), as the seed of the generator, while Random(long seed) uses the specified seed as the seed of the generator.
When the random number generator is a Random object, different methods can be called by the object: nextInt(), nextLong(), nextFloat(), nextDouble(), etc. to obtain different types of random numbers. If 2 Random objects use the same seed (e.g., both 100) and call the same function in the same order, their return values are exactly the same.
It’s useless to talk too much, let me give you a chestnut first, as follows:
But what should I do if I want a number in a certain range? For example, I want to randomly generate random numbers between 0 and 99, and at this time we can use the modulo operator %.
The purpose of using the modulus operator % on the random number generated by the random number generator is to make the maximum value of the random number within the range of minus the operand value we set. Look at the following code and control the input to the range of 0~99. (Friendly reminder: If Math.abs() is not added, the output range will be -99~99.)
First look at the situation where Math.abs() is not added, as follows
Looking at the added situation, as follows: