Randomize Output
Random Class
•
Soon you will learn about classes. Classes can be built in or created by the programmer.•
For pseudo random output- we use the Random class.Coding Example
Random numGen = new Random(); //creating a new Random object
int num1= numGen.Next(0,15); //using the Next method to generate a number
MessageBox.Show(num1.ToString()); //output- remember we must convert to a string
• Note: The 2nd argument is not included in the range- so the highest random
Static Keyword
• To create better (more random) random numbers we can make the data member static.
private void button1_Click(object sender, EventArgs e) {
randNum();
}
RandNum Method
static Random _r = new Random(); //creating an instance variable
static void randNum() {
int num1 = _r.Next(0,15);
Static in C#
•
As mentioned in 1.01- the “static” keyword works differently in C#.•
Classes, methods, and constructors (you will learn more about each of these topics in later lessons) can be static.Program.cs
•
Every C# program has a static method. It is called the main method.static void Main(string[] args)
Random Characters
• Random isn’t only for numbers! We can generate random characters too.
private void btnStart_Click(object sender, EventArgs e) {
char randLetter = RandomLetter.GetLetter();
MessageBox.Show(randLetter.ToString()); //must convert char to string
Class code
public static class RandomLetter //static custom class {
static Random _randLetter = new Random(); //static variable
public static char GetLetter() //method that returns a value of type char {
int num1 = _randLetter.Next(0, 26); char letter = (char)('a' + num1); return letter;
Program: Random Letters
Step 1: Radio Buttons
•
Add 2 radio buttons on the form for the selection: upper or lower case letter.Step 2: Passing the Choice to the
Method
• Since a custom class cannot access objects on the form we will pass a value to let it know the user’s choice.
int letterChoice = 0;
if(radUpper.Checked) {
letterChoice = 1; }
Step 3: Method
if(letterChoice == 0) {
char letter = (char)('a' + num1); return letter;
} else {
char letter = (char)('A' + num1); return letter;
Video
Random Characters
•
What if we need more than 1 random character?•
There is an easy way to get up to 11 random characters.Using Keyword
•
At the top of your program you see this: (some lines omitted)using System.Data;
using System.Windows.Forms;
•
These imports give C# access to classes. We need to add the IO class which the path method is part of.Program Code
private void btnStart_Click(object sender, EventArgs e) {
string randomString = GetRandomString(); //variable to hold output from method lblOutput.Text= randomString;
}
public static string GetRandomString() //string method which will return a random string
{
string path = Path.GetRandomFileName();
path = path.Replace(".", ""); // Remove period. //GetRandomFileName method adds a period