java中随机数小结

三种随机数的方法

1 java.util.Random.nextInt
   Random().nextInt(int bound)

这将产生0到bound之间,包括0,但不包括bound的随机数
 产生随机数的公式
  Random r = new Random();
return r.nextInt((max - min) + 1) + min;

例子:
new Random().nextInt(5);  // [0...4] [min = 0, max = 4]
new Random().nextInt(6);  // [0...5]
new Random().nextInt(7);  // [0...6]
new Random().nextInt(8);  // [0...7]

如果要包含最后的值,则:
   new Random().nextInt(5 + 1)  // [0...5] [min = 0, max = 5]
new Random().nextInt(6 + 1)  // [0...6]
再比如,要产生某个范围的两个值,如何搞:
比如,产生10-15之间的随机数,则

new Random().nextInt(5 + 1)  + 10 // [0...5]  + 10 = [10...15]
实际上就是max-min+1+min

2  Math.random()
   其实差不多,其实就是double类型

猜你喜欢

转载自jackyrong.iteye.com/blog/2242938