A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

©   /  2013-9-25 21:47  /  3711 人查看  /  15 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

是啊,你的是把种子写死了的缘故,看下java 类库源代码
  1. /**
  2.      * Creates a new random number generator using a single {@code long} seed.
  3.      * The seed is the initial value of the internal state of the pseudorandom
  4.      * number generator which is maintained by method {@link #next}.
  5.      *
  6.      * <p>The invocation {@code new Random(seed)} is equivalent to:
  7.      *  <pre> {@code
  8.      * Random rnd = new Random();
  9.      * rnd.setSeed(seed);}</pre>
  10.      *
  11.      * @param seed the initial seed
  12.      * @see   #setSeed(long)
  13.      */
  14.     public Random(long seed) {
  15.         this.seed = new AtomicLong(0L);
  16.         setSeed(seed);
  17.     }
复制代码
在这里你把参数seed写死了的,所以结果你懂的,一般用无参构造的就行,在java类库源代码中式这样定义的
  1. /**
  2.      * Creates a new random number generator. This constructor sets
  3.      * the seed of the random number generator to a value very likely
  4.      * to be distinct from any other invocation of this constructor.
  5.      */
  6.     public Random() { this(++seedUniquifier + System.nanoTime()); }
  7.     private static volatile long seedUniquifier = 8682522807148012L;
复制代码
这样取出的每次的seed就会不一样,才能生成随机数,我把代码改了一下,
  1. import java.util.Random;


  2. public class Test1{
  3.     public static void main(String[] args) {
  4.         Random r1 = new Random();
  5.             Random r2 = new Random();
  6.             System.out.println("r1:"+r1.nextInt(10));
  7.             System.out.println("r2:"+r2.nextInt(25));
  8.             Random r = new Random();
  9.             System.out.println("r:"+r.nextInt(100));
  10.     }
  11. }
复制代码
这样就可以生成随机数
希望能帮到你

评分

参与人数 1技术分 +1 收起 理由
乔兵 + 1

查看全部评分

回复 使用道具 举报
黑马戴帅军 发表于 2013-9-25 22:00
多次调用出相同序列,是因为 Random randdom = new Random(); 这个地方,随机数种子是当前的时间,由于你循 ...

哥们,错了吧,不是调用时间短,是因为他把随机数种子写死了。
回复 使用道具 举报
梁贺 发表于 2013-9-25 22:12
API中的解释:
Random类的实例用于生成伪随机数流。此类使用 48 位的种子,使用线性同余公式 (linear congr ...

说得好,不过说错了。
回复 使用道具 举报
梁贺 发表于 2013-9-25 22:38
好吧,没看源码,一直以为是当前时间作为种子的。又有收获了~!

我现在是打个呵呵都得输验证码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马