• No results found

Random Numbers

In document c#.net (Page 160-163)

}

We create the array with seven scores, and then convert the user’s entry in

guessBoxto an integer. Thewhilestatement searches for the number in the

scorearray. If the number is in the array at indexi, the conditionnumber !=

score[i]will fail and the loop will terminate. For example, if the user guesses 34, the condition34 != score[2]is false and the loop will stop wheniis 2.

If the user’s guess is not one of the score elements, then iwill continue to be incremented until it becomes 7 and the condition i < score.Lengthwill fail, causing the loop to terminate. After the whileloop terminates, we use anif-elsestatement to determine what caused the termination, finding the user’s number or incrementing the index past the end of the array. We indi-cate the result in the label.

To make it easier for the user to enter the next number, we reset the Textin

guessBoxto the empty string. We call the Focusmethod ofguessBoxto direct the keystrokes to guessBox. This is helpful because when the user presses the button, it gets the focus; otherwise the user would have to click the mouse insideguessBoxto direct key presses to it for the next entry.

6.1.5 Random Numbers

The guessing game of Example6-2 will not be interesting to replay because the user will soon figure out the numbers in the score array. To make it

more interesting, we can generate random numbers that will change each time the program is run.

TheRandomclass has a Nextmethod that returns a number that appears to be randomly chosen from the integers 0 through 99. The following C# code will create an array of scores and fill it with randomly chosen numbers from 1 through 100.

int[] score = new score[7];

Random r = new Random();

for (int i = 0; i < score.Length; i++) score[i] = r.Next(100) + 1;

In this code, we did not initialize the array, but instead used the new opera-tor to create seven variables,score[0], . . . ,score[6]. We use the newoperator again to create a Randomobject rthat we can use to generate the random numbers. In the forloop, we assign each variable a value randomly chosen from 1 through 100. The Nextmethod returns values from 0 through 99, so we add 1 to each.

Example6-2a revises Example6-2 to fill the scorearray with random num-bers. The easiest approach would be to modify the event-handling method for the button to fill the scorearray with random numbers. However, doing this would mean that each time the user made a guess the array would be recreated. We want to fill the array once and let the user keep making guesses until successfully finding a value. Thus we need to fill the score

array outside of the event-handling method.

To fill the array in one place and use it in another, we need to create it so that it will be visible throughout the application. Similarly, the controls we add in the Visual Studio .NET design need to be visible throughout the application. Visual Studio initializes them inside the InitializeComponent

method, and we use and change their properties inside our event-handling methods. We will declare the scorearray in the same location that Visual Studio .NET declares the controls. Figure 6.4 shows these declarations from Example6-2a. The privatemodifier indicates that only this application can use these variables directly.

Visual Studio .NET initializes the controls in the InitializeComponent

method. We cannot change this method because Visual Studio automati-cally regenerates it when we make changes in the design and does not include any added code. Visual Studio places a comment in the code telling

6.1 Arrays 147

Figure 6.4 Declarations of Example6-2a.

public class Form1 : System.Windows.Forms.Form {

private int[] score = new int[7];

private System.Windows.Forms.TextBox guessBox;

Figure 6.5 The Form1constructor.

public Form1() {

//

// Required for Windows Form Designer support //

InitializeComponent();

//

// TODO: Add any constructor code after // InitializeComponent call //

Random r = new Random();

for (int i = 0; i < score.Length; i++) score[i] = r.Next(100) + 1;

}

us where to add our initialization. Figure 6.5 shows the Form1constructor. A constructor has the same name as the application class. Notice that in Fig-ure 6.4 the class name is Form1. The constructor in Figure 6.5 has the same name,Form1, and no return value.

The .NET system calls the constructor when the application starts. The

Form1constructor calls the InitializeComponentmethod to initialize the con-trols. The TODOcomment tells us to add any constructor code we need to initialize our variables, so we add the code to fill the scorearray with ran-dom numbers.

Figure 6.6 Primitive types hold values.

The event-handling method for the Submit button, submitGuess_Click, is the same as the event-handling method used in Example6-2 except that we omit the first line to initialize the score array because we have already ini-tialized it with random numbers. Running Example6-2a will produce a form like Figure 6.3, but each time the user runs this application the score

array will be different, making the game more interesting. We will elaborate on the concepts introduced in this example later in the chapter.

In document c#.net (Page 160-163)

Related documents