Random x = new Random();
Creates a new random number generator. Its seed is initialized to a value based on the current time:
 public Random() { this(System.currentTimeMillis()); }
Two Random objects created within the same millisecond will have the same sequence of random numbers.
所以你的程序每一次运行得到的x是一样的
public int nextInt(int n)
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All n possible int values are produced with (approximately) equal probability. The method nextInt(int n) is implemented by class Random as follows: public int nextInt(int n) {
     if (n
<=0)                throw new IllegalArgumentException("n must be positive");
     if ((n & -n) == n)  // i.e., n is a power of 2
         return (int)((n * (long)next(31)) >> 31);
     int bits, val;
     do {
         bits = next(31);
         val = bits % n;
     } while(bits - val + (n-1) 
< 0);     return val;
 }
 
protected int next(int bits)
Generates the next pseudorandom number. Subclass should override this, as this is used by all other methods.The general contract of next is that it returns an int value and if the argument bits is between 1 and 32 (inclusive), then that many low-order bits of the returned value will be (approximately) independently chosen bit values, each of which is (approximately) equally likely to be 0 or 1. The method next is implemented by class Random as follows: synchronized protected int next(int bits) {
       seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L 
<< 48) - 1);       return (int)(seed >>> (48 - bits));
 }
This is a linear congruential pseudorandom number generator, as defined by D. H. Lehmer and described by Donald E. Knuth in The Art of Computer Programming, Volume 2: Seminumerical Algorithms, section 3.2.1.x一样的值所以每次计算出来的nextInt(9)也是同样的

解决方案 »

  1.   

    Random产生的随机数,只是伪随机数,需要设置随机种子.
    通常如此:
    Random rnd = new Random();
    rnd.setSedd(System.currentTimeMillis();
    1.其余方法基本就是产生int,double,float等类型的随机数
    2.每次nextInt等都是得到一个新的随机数
    3.
    0<=num<=max-1
    public static int random(int max)
    {
    return Math.abs((int)(random.nextInt()%max));
    }min<=num<=max
    public static int random(int min,int max)
    {
    return min+random(max-min+1);
    }
    4.应该将random实例定义在循环之外,并且设置随机种子