Detailed explanation of JAVA Random().nextBoolean()

Random().nextBoolean()Is a method to generate random boolean values ​​in Java. This is explained in detail below:

  1. Random(): Randomis a class in the Java standard library used to generate pseudo-random numbers. Random()It is Randoma no-argument constructor of the class, creating a new Randomobject.

  2. nextBoolean(): nextBoolean()is Randomone of the methods of the class, used to generate a random Boolean value. It returns a random booleanvalue, which is trueor false. Each call nextBoolean()to generates a new random boolean value.



import java.util.Random;
boolean success = new Random().nextBoolean(); 
System.out.println(success); // 输出随机的布尔值

The above code generates a random boolean value and assigns it to successthe variable. Then, System.out.println()print out the Boolean value via the method.

Note that Random()the constructor uses the current time as the default seed value, which means calling it multiple times within the same millisecond Random().nextBoolean()may result in the same boolean value. If you need higher quality random numbers or need to control the generation of random numbers, you can consider using java.util.Randomother methods of the class or use java.security.SecureRandomthe class.

おすすめ

転載: blog.csdn.net/monicateacat/article/details/132729595