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

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值