Java随机数生成的几种方式

方式一:静态方法Math.random()产生double类型的随机值,范围是[0.0d, 1.0d)

public static int randValueA_0_100(){
		//强制转换为int
		return (int)(Math.random()*101);//[0, 100]之间的整数
	}
	
	public static long randValueB_0_100(){
		//Math.round()相当于"加上0.5并向下取整(x轴负方向)"
		return Math.round(Math.random()*100);//[0, 100]之间的整数
	}
	
	public static int randValueC_0_100(){
		//Math.floor()返回的是浮点类型
		return (int) Math.floor(Math.random()*101);//[0, 100]之间的整数
	}

方式二:java.util.Random类来完成

public static int value_0_100(){
		return new Random().nextInt(101);//[0, 100]之间的整数
	}

方式三:Java1.7版本提供了java.util.concurrent.ThreadLocalRandom类,可以满足多线程场景下的隔离。

另外,方式一中Math.round()、Math.floor()和(int)强制转换的区别,通过实测例子说明如下:

Math.round(9.9f));//10
Math.round(9.1f));//9
Math.round(9.5f));//10
Math.round(-9.9f));//-10
Math.round(-9.1f));//-9
Math.round(-9.5f));//-9
Math.floor(9.1d));//9.0d
Math.floor(9.5d));//9.0d
Math.floor(9.9d));//9.0d
Math.floor(-9.1d));//-10.0d
Math.floor(-9.5d));//-10.0d
Math.floor(-9.9d));//-10.0d
(int)9.1d;//9
(int)9.5d;//9
(int)9.9d;//9
(int)-9.1d;//-9
(int)-9.5d;//-9
(int)-9.9d;//-9

其他方式,例如:

public static int randValueD_0_100(){
		return (int)System.currentTimeMillis()%101;//[0, 100]之间的整数
	}

不过这种方式严格的说,并不是随机的,只不过是随着时间在变化而已。

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值