public int nextInt(int n){
  if (n > 0) {
    if ((n & -n) == n) {
      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;
  }
  throw new IllegalArgumentException();
}

public int nextInt ( int n ) { if ( n > 0 ) { if ( ( n & - n ) == n ) { 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 ; } throw new IllegalArgumentException ( ) ; }
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 ; } the hedge " approximately " is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits . if it were a perfect source of randomly chosen bits , then the algorithm shown would choose int values from the stated range with perfect uniformity . the algorithm rejects values that would result in an uneven distribution ( due to the fact that 2 ^ 31 is not divisible by n ) . the probability of a value being rejected depends on n . the worst case is n = 2 ^ 30 + 1 , for which the probability of a reject is 1 / 2 , and the expected number of iterations before the loop terminates is 2 . the algorithm treats the case where n is a power of two specially : it returns the correct number of high - order bits from the underlying pseudo - random number generator . in the absence of special treatment , the correct number of low - order bits would be returned . linear congruential pseudo - random number generators such as the one implemented by this class are known to have short periods in the sequence of values of their low - order bits . thus , this special case greatly increases the length of the sequence of values returned by successive calls to this method if n is a small power of two .
