Java Random类的使用

1.简单使用:

Random random=new Random();
int a=random.nextInt();
System.out.println(a);
-325078223
Process finished with exit code 0

产生int类型范围内 -2147483648~2147483647 的随机整数。

Random random=new Random();
int a=random.nextInt(10);
System.out.println(a);

产生0~9的随机整数。

2.产生任意范围的随机整数

Random random=new Random();
int a=random.nextInt(6)+5;
System.out.println(a);

产生任意范围的随机整数,此处为5~10.

3.产生任意范围的随机小数

Random random=new Random();
double a=random.nextDouble();
System.out.println(a);
0.11665258082938701
Process finished with exit code 0

产生(0,1)范围的随机小数.

Random random=new Random();
double a=random.nextDouble()*1.5+1;
System.out.println(a);
2.445836482596139

Process finished with exit code 0

产生任意范围的随机小数,此处为1~2.5,精确度为double默认的精确度.

 Random random=new Random();
 double a=random.nextDouble()*1.5+1;
 BigDecimal bg = new BigDecimal(a);
 double b = bg.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
 System.out.println(b);
1.9

Process finished with exit code 0

产生任意范围的随机小数,此处为1~2.5.精确度为小数点后一位。
关于double精确度的内容请参考 java double的精确度控制 还没写。。。不要点

4.seed 种子的使用

Random random1 = new Random(100);
System.out.println(random1.nextInt());
System.out.println(random1.nextFloat());
System.out.println(random1.nextBoolean());
Random random2 = new Random(100);
System.out.println(random2.nextInt());
System.out.println(random2.nextFloat());
System.out.println(random2.nextBoolean());
-1193959466
0.7346627
false

-1193959466
0.7346627
false

Process finished with exit code 0

相同种子输出的结果相同.

Random random1 = new Random(System.currentTimeMillis());
System.out.println(random1.nextInt());
System.out.println(random1.nextFloat());
System.out.println(random1.nextBoolean());
System.out.println();
Random random2 = new Random(System.currentTimeMillis());
System.out.println(random2.nextInt());
System.out.println(random2.nextFloat());
System.out.println(random2.nextBoolean());
-1674565819
0.2528978
false

-1664947096
0.5270924
true

Process finished with exit code 0

不同种子输出的结果不同.

猜你喜欢

转载自blog.csdn.net/scotteperk/article/details/52374645