方式一:静态方法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]之间的整数
}
不过这种方式严格的说,并不是随机的,只不过是随着时间在变化而已。