C# Random Next(Int32)
Description
Random Next(Int32)
returns a nonnegative random integer
that is less than the specified maximum.
Syntax
Random.Next(Int32)
has the following syntax.
public virtual int Next(
int maxValue
)
Parameters
Random.Next(Int32)
has the following parameters.
maxValue
- The exclusive upper bound of the random number to be generated. maxValue must be greater than or equal to zero.
Returns
Random.Next(Int32)
method returns A 32-bit signed integer greater than or equal to zero, and less than maxValue;
that is, the range of return values ordinarily includes zero but not maxValue.
However, if maxValue equals zero, maxValue is returned.
Example
The following example generates random integers with the Next method.
// w w w . ja v a 2s . c om
using System;
public class RandomNextDemo
{
static void Main( )
{
Random randObj = new Random( 1 );
// Generate six random integers from 0 to the upper bound.
for( int j = 0; j < 6; j++ )
Console.Write( "{0,11} ", randObj.Next( 2 ) );
}
}
The code above generates the following result.
Example 2
The following example generates a random integer that it uses as an index to retrieve a string value from an array.
using System;/*from www. j a v a2 s . co m*/
public class Example
{
public static void Main()
{
Random rnd = new Random();
string[] malePetNames = { "A", "B", "C", "D",
"E", "F", "G", "H",
"I", "J" };
// Generate random indexes for pet names.
int mIndex = rnd.Next(malePetNames.Length);
Console.WriteLine(" For a male: {0}", malePetNames[mIndex]);
}
}
The code above generates the following result.