Generating Random Numbers Using the Random Class
Sometimes we may need a number to be randomly generated by the computer in the program. In the example below, two random numbers are generated and transferred to the variables.
Sample:
Random randomNumber = new Random();
int number1 = randomNumber.Next(0, 100);
int number2 = randomNumber.Next(0, 100);
In the first line, an object named RandomNumber is created from the Random class. Here;
Random name of the class to derive the object
rastgelesa the name that the object to be created, the
new command is used in generating the new object command,
Random ( ) is the constructor method of that class used with the same name.
A number between 0 and 100 was generated by using the Next method of the object created in the second and third lines, namely the randomNumber object, and assigned to the relevant variables.
Example :
A form has been created as above and the following codes have been written. The goal is to make a game that teaches addition. The computer will randomly generate two numbers, the user will check the sum of these numbers in the box.
int number1 , number2;
private void button1_Click(object sender, EventArgs e)
{
int total = number1 + number2;
int guess = int.Parse(textBox1.Text);
if (guess == total) label5.Text = "Congratulations, Result Correct..";
else label5.Text = "Incorrect Result.";
}
private void button2_Click(object sender, EventArgs e)
{
Random randomNumber = new Random();
number1 = randomNumber.Next(0, 100);
number2 = randomNumber.Next(0, 100);
label3.Text = number1.ToString();
label4.Text = number2.ToString();
}
c# random number generation, random number, random, randomise, c# random, randomized, random number, random number generation
EXERCISES
There are no examples related to this subject.
Read 789 times.