This article introduces the usage of the Random class, a commonly used Java class. The following is a practical case. There is no additional text explanation. I have written everything that needs to be explained in the code comments.
import java.util.Random;public class random1 { public static void main(String[] args){ //两种构造函数 Random r1=new Random(); //Random r2=new Random(120); 使用单个 long 种子创建一个新的随机数生成器。 //System.out.println(r1.next(2));返回值为保护类型 //System.out.println(r2.next(2)); System.out.println(r1.nextBoolean());//返回下一个伪随机数,它是取自此随机数生成器序列的均匀分布的 boolean 值。 System.out.println(r1.nextBoolean()); System.out.println("+++++++++++"); byte[] by1=new byte[5]; byte[] by2=new byte[5]; r1.nextBytes(by1);//生成随机字节并将其置于用户提供的 byte 数组中。 r1.nextBytes(by2); for(int i=0;iRunning results:
Compiling random1.java....... -----------OUTPUT----------- falsefalse +++++++++++-55 -112 41 -78 93 54 127 -93 -22 120 +++++++++++0.69656134440266490.06445584272260563 +++++++++++0.285779950.8657566 +++++++++++-0.15436582029316171.4500847476555192 +++++++++++1824132073-436413982 +++++++++++2921 +++++++++++3295074968265391496 1387264859162260419[Finished in 1.2s]import java.util.Random;public class random1 { public static void main(String[] args){ //两种构造函数 Random r1=new Random(); //Random r2=new Random(120); 使用单个 long 种子创建一个新的随机数生成器。 //System.out.println(r1.next(2));返回值为保护类型 //System.out.println(r2.next(2)); System.out.println(r1.nextBoolean());//返回下一个伪随机数,它是取自此随机数生成器序列的均匀分布的 boolean 值。 System.out.println(r1.nextBoolean()); System.out.println("+++++++++++"); byte[] by1=new byte[5]; byte[] by2=new byte[5]; r1.nextBytes(by1);//生成随机字节并将其置于用户提供的 byte 数组中。 r1.nextBytes(by2); for(int i=0;iRunning results:
Compiling random1.java....... -----------OUTPUT----------- falsefalse +++++++++++-55 -112 41 -78 93 54 127 -93 -22 120 +++++++++++0.69656134440266490.06445584272260563 +++++++++++0.285779950.8657566 +++++++++++-0.15436582029316171.4500847476555192 +++++++++++1824132073-436413982 +++++++++++2921 +++++++++++3295074968265391496 1387264859162260419[Finished in 1.2s]Related articles:
JAVA Random class, array learning
Common classes that must be understood in java
Related videos:
Comprehensive analysis of Java annotations
The above is the detailed content of Java common classes-Usage case analysis of Random class. For more information, please follow other related articles on the PHP Chinese website!