发表于: java/j2ee | 作者: | 日期: 2008/11/03 08:11

总结了一下java.util.Random类的使用。


import java.util.Random;

class TestRandom {

public static void main(String[] args) {

Random random1 = new Random(100);
System.out.println(random1.nextInt());
System.out.println(random1.nextInt());
System.out.println(random1.nextFloat());
System.out.println(random1.nextFloat());
System.out.println(random1.nextBoolean());
System.out.println(random1.nextBoolean());

Random random2 = new Random(100);

System.out.println(random2.nextInt());
System.out.println(random2.nextInt());
System.out.println(random2.nextFloat());
System.out.println(random2.nextFloat());
System.out.println(random2.nextBoolean());
System.out.println(random2.nextBoolean());

}
}

输出结果如下:


-1193959466
-1139614796
0.19497603
0.7158033
true
false
-1193959466
-1139614796
0.19497603
0.7158033
true
false

注释:
1:如果2个Random对象使用相同的种子(比如都是100),并且以相同的顺序调用相同的函数,那么它们的返回值完全相同。

2:如果希望将返回的随机数控制在某个范围内(比如0~99),则可以使用模数运算符%


import java.util.Random;

class TestRandom {
public static void main(String[] args) {
Random random = new Random();
for (int i = 0; i < 100; i++) { System.out.println(Math.abs(random.nextInt()) % 100); } } }

注释: 
1:将模数运算符%作用于随机数产生器所产生的随机数身上,目的是为了让随机数的最大值局限于我们所制定的操作数数值减1范围内。

2:如上面代码就将输入控制在0~99的范围内,注意:如果不加Math.abs(),输出范围将是-99~99。

: https://blog.darkmi.com/2008/11/03/260.html

本文相关评论 - 1条评论都没有呢
Post a comment now » 本文目前不可评论

No comments yet.

Sorry, the comment form is closed at this time.