<body>
  
   <%
    for(int i=0;i<5;i++)
   {
   out.println("随机数:");
   Random random=new Random();
         int temp1=random.nextInt(33);
   int temp2=random.nextInt(33);
   int temp3=random.nextInt(33);
   int temp4=random.nextInt(33);
   int temp5=random.nextInt(33);
   int temp6=random.nextInt(33);
   int temp7=random.nextInt(16);
    out.println(temp1);
    out.println(temp2);
    out.println(temp3);
    out.println(temp4);
    out.println(temp5);
    out.println(temp6);
    out.println(temp7);
    out.println("<br>");
    }
%>每次输出的5组随机数都一样,输出结果如下:
随机数: 19 20 29 25 14 29 4 
随机数: 19 20 29 25 14 29 4 
随机数: 19 20 29 25 14 29 4 
随机数: 19 20 29 25 14 29 4 
随机数: 19 20 29 25 14 29 4 
  为什么啊?恳请高手指点迷机。

解决方案 »

  1.   

    Random必须定义在循环外面,Java中如果在同一机器、同一毫秒数时Random都会得到相同的结果   Random random=new Random();
    for(int i=0;i<5;i++)
       {
       out.println("随机数:");         int temp1=random.nextInt(33);
       int temp2=random.nextInt(33);
       int temp3=random.nextInt(33);
       int temp4=random.nextInt(33);
       int temp5=random.nextInt(33);
       int temp6=random.nextInt(33);
       int temp7=random.nextInt(16);
        out.println(temp1);
        out.println(temp2);
        out.println(temp3);
        out.println(temp4);
        out.println(temp5);
        out.println(temp6);
        out.println(temp7);
        out.println("<br>");
        }
      

  2.   

    Random random=new Random();
    把你程序中的这句放到for循环之外。
    原因俺表述不清楚,多注意,Random的nextInt()及其他函数产生的都是伪随机数。
    多理解一下,有什么想法了回帖,很愿意和大家交流,呵呵!
      

  3.   

    对,关键是你用来产生随机数的种子每次都是一样的。
    可以用这个构造方法 Random(long seed),每次设置一个不同的种子还可以使用这个类 java.security.SecureRandom
      

  4.   

    这么快,顶错人了!再顶下 ChDw(米) !
      

  5.   

    看一下Random的源代码
     public Random() { this(System.currentTimeMillis()); }
    默认构造函数是用现在时间的long值做种子,而javadoc上对于Random有这样的描述。If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.
      

  6.   

    to ChDw(米)
    厉害,能不能再详细的解释一下Random的实现,或者传一些资料啊。
    我在sun的中文API文档看到对Rangdom的说明:如果用相同的种子创建两个 Random 实例,则对每个实例进行相同的方法调用序列,它们将生成并返回相同的数字序列。请问这里说的种子是什么啊?谢谢!
      

  7.   

    TO : ChDw(米) 
    知道这个问题么?
    And to All 牛人.
    http://community.csdn.net/Expert/topic/4915/4915883.xml?temp=.5306513