请问Random中的nextInt()和nextInt(int n)的区别是什么?nextInt(100) 可以产生100以内的随机数而用nextInt()也可以呀:
    Random random = new Random();
    int a = (random.nextInt(100) >>> 1) % 100;那他们有什么区别,用于什么不同的情况?

解决方案 »

  1.   

    下面的这段摘自java2 sdk的文档
    int nextInt() 
              Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. 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. 我觉得从效果上没有大的区别,内在实现不同。
      

  2.   

    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;
        }public int nextInt() {  return next(32); }
    这是源代码,看看就知道有什么不同了。
      

  3.   

    nextInt()是无范围的随机数
    但是nextInt(n)是从0到n的随机数
      

  4.   

    要import进哪个类,为什么rumlee(rum-lee) 的代码编译不了呢?
    import java.util.*;
    import java.io.*;
      

  5.   

    nextInt()  [0, 31]
    nextInt(n) [0, n-1]
      

  6.   

    谁能解释一下nextInt(n)为什么不设计成静态方法啊?