Java use in the random number

  Abstract: Java in the use of random number 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="263" height="86" align="center" valign="top"> </ td> <td width="421" valign="top"> 

  In Java, we can use to generate java.util.Random of a random number generator.    It has two forms of constructor function, namely Random () and Random (long seed).    Random () to use the current time that System.currentTimeMillis () as a generator of seeds, Random (long seed), as specified seed generator seed. 
  Random Random Number Generator that is a target, the object can be called by different function: nextInt (), nextLong (), nextFloat (), nextDouble () to access different types of random numbers. 

  If two objects Random use the same seed (for example, are 100), and call the same order of the same function, then they return the same value.    As in the following code in the output of two identical objects Random: 

  </ Td> </ tr> </ table> 

  Import java.util .*; 
  (Class TestRandom 
  Public static void main (String [] args) ( 
  Random random1 = new Random (100); 
  System.out.println (random1.nextInt ()); 
  System.out.println (random1.nextInt ()); 
  System.out.println (random1.nextFloat ()); 
  System.out.println (random1.nextFloat ()); 
  System.out.println (random1.nextBoolean ()); 
  System.out.println (random1.nextBoolean ()); 
  Random random2 = new Random (100); 
  System.out.println (random2.nextInt ()); 
  System.out.println (random2.nextInt ()); 
  System.out.println (random2.nextFloat ()); 
  System.out.println (random2.nextFloat ()); 
  System.out.println (random2.nextBoolean ()); 
  System.out.println (random2.nextBoolean ()); 
  ) 
  ) 

  If you want to return to the random number will be controlled within a certain range (0 to 99, for example), you can use the modulus operator%.    Note:% modulus operator role in the random number generator of the random numbers generated by the body, is designed to allow the maximum number of random confined to the operation we have developed by a number of numerical limits.    As in the following code will be in control of the importation of 0 to 99 within the scope of Note: If not Math.abs (), output range is -99 to 99. 

  Import java.util .*; 
  (Class TestRandom 
  Public static void main (String [] args) ( 
  Random random = new Random (); 
  For (int i = 0; i <100; i + +) ( 
  System.out.println (Math.abs (random.nextInt ())% 100); 
  ) 
  ) 
  ) 

  </ Td> </ tr> <tr> 

  ↑ Back 

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Facebook
  • DotNetKicks
  • DZone
  • Netvouz
  • Propeller

Tags: ,

Releated Java Articles

Comments

Leave a Reply