Proving a probability paradox – Part 3
The last installation of the three part look at the Monty Hall problem

Last but not least, this third part of the our problem solving exercise delves into the code for the TextBox object. Part 1 and Part 2 can be found at their respective links. Part 1 contains the code we're analysing.
The code discussed below is executed in the event that the text is altered within the TextBox (noRounds). The purpose of the code is to check that the input is valid.
private void noRounds_TextChanged(object sender, EventArgs e)
{
try
{
if (Convert.ToInt32(noRounds.Text) > 9999 ||
Convert.ToInt32(noRounds.Text) < 1)
{
MessageBox.Show("Please enter a number between 0 and 10,000.");
noRounds.Text = Convert.ToString(9999);
}
}
catch
{
MessageBox.Show("Please enter a number between 0 and 10,000.");
noRounds.Text = Convert.ToString(1);
}
}
The code is enclosed within a try and catch block. Try/catch blocks are used together when there's a chance that the program will throw an exception (i.e. an error). For instance, if the user puts in a huge number, the int variable within the 'GO' button code may overflow. Integer values cannot exceed 2,147,483,647 in C#. There are exceptions to this, such as long and unsigned integers, however they are beyond the scope of this guide. When a value larger than the maximum is used, it wraps around and continues from -2,147,483,647. Clearly, this is a bad thing, we don't want the number to become negative.
In this case, the try/catch block isn't to prevent the user from inputting a large number. Rather, its ensure invalid input such as alpha characters aren't used. We can't execute the simulation 'lol' amount of times, as humorous as that would be. Instead, we manually check that the number is within reasonable bounds. In this case, I've limited it to 9999, as shown by the first if statement.
Of course, to convert the TextBox string to an integer value to check the 0 - 9999 bound, the characters must all be numerical to prevent an exception occurring. If alpha characters are used, and an exception is thrown, the catch block is executed. In both cases the user is told that they must input a number between 0 - 9999. In the try block, the TextBox is then reset to 9999. The catch block resets it to 1.
Try/catch blocks are typically used with a parameter explicitly stating what exception the catch block will catch. In order to maintain simplicity, I left it in its most basic form. Assigning a specific exception ensures you reacting to a particular error.
And that concludes the three part series of 'Proving a probability paradox'. Now get out there, and have fun. :)






