2012年11月29日 星期四

generating random number and string

Author     Date Of Submission     User Level
Mahesh Chand    11/19/2004     Beginner



The Random class defined in the .NET Framework class library provides functionality to generate random numbers. 

 The Random class constructors have two overloaded forms. It takes either no value or it takes a seed value.

 The Random class has three public methods – Next, NextBytes, and NextDouble. The Next method returns a random number, NextBytes returns an array of bytes filled with random numbers, and NextDouble returns a random number between 0.0 and 1.0. The Next method has three overloaded forms and allows you to set the minimum and maximum range of the random number.

 The following code returns a random number:

 int num = random.Next();

 The following code returns a random number less than 1000.

 int num = random.Next(1000);

 The following code returns a random number between min and max:

 private int RandomNumber(int min, int max)
 {
Random random = new Random();
 return random.Next(min, max); 
 }

 At some point, you may also want to generate random strings. I have created a method, which takes first parameter as the size of string and second parameter if you want the string to be lowercase. 

 /// 
 /// Generates a random string with the given length
 /// 
 /// Size of the string
 /// If true, generate lowercase string
 /// Random string
 private string RandomString(int size, bool lowerCase)
 {
 StringBuilder builder = new StringBuilder();
Random random = new Random();
 char ch ;
 for(int i=0; i

沒有留言: