Java's Random class

A, Random class

    Examples of random class for generating pseudo-random numbers.

  Demo:

1 Random r = new Random();
2 int i = r.nextInt();

Two, Random using procedure

  1, View class

    java.util.Random: After importing the class needs to import in order to use;

  2, view the constructor

   public Random (): Creates a new random number generator;

  3, view the members method

    public int nextInt (int n): Returns a pseudo-random number, in the range of 0 directly (including) and the specified value n (not including) int value .

  Demo1: using Random class, generates complete . 3 th 10 operating within a random integer

1  // 1. guide packet 
2  Import java.util.Random;
 . 3  public  class Demo01_Random {
 . 4      public  static  void main (String [] args) {
 . 5          // 2. Create random number generator object 
. 6          the Random = R & lt new new the Random ();
 . 7          for ( int I = 0; I <. 3; I ++ ) {
 . 8              // 3. a randomly generated data 
. 9              int Number = r.nextInt (10 );
 10              // 4. data output 
. 11              the System.out. the println ( "Number:" + Number);
 12 is         }
13     }
14 }

   Demo2: obtaining 1-n random number comprising n

1  // guiding packet 
2  Import java.util.Random;
 . 3  public  class Test01Random {
 . 4      public  static  void main (String [] args) {
 . 5          int n-50 = ;
 . 6          // create the object 
. 7          the Random = R & lt new new the Random ();
 8          // Get a random number 
. 9          int number = r.nextInt (n-) +. 1 ;
 10          // output of the random number 
. 11          System.out.println ( "number:" + number);
 12 is      }
 13 is }

 

Guess you like

Origin www.cnblogs.com/niujifei/p/11409156.html