96
Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Embed Size (px)

Citation preview

Page 1: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Visual Basic 2010 How to Program

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 2: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 3: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 4: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 5: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

This chapter introduces basic concepts of data structures—collections of related data items.

Arrays are simple data structures consisting only of data items of the same type.

Arrays normally are “static” entities, in that they typically remain the same size once they’re created, although they can be resized (as we show in Section 7.16.

We discuss arrays that can represent lists and tables of values.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 6: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

We begin by creating and accessing arrays. We then perform more complex array manipulations,

including summing the elements of an array, using arrays to summarize survey results, searching arrays for specific values and sorting arrays so their elements are in ascending order.

We also introduce For Each…Next repetition statement and use it to process the elements of an array.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 7: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

An array is a group of variables (called elements) containing values that all have the same type.

To refer to a particular element in an array, we specify the name of the array and the position number of the element to which we refer.

Figure 7.1 shows a logical representation of an integer array called c.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 8: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

This array contains 12 elements, any one of which can be referred to by giving the name of the array followed by the position number of the element in parentheses ().

The first element in every array is the zeroth element. Thus, the names of array c’s elements are c(0), c(1), c(2) and so on.

The highest position number in array c is 11 (also called the array’s upper bound), which is 1 less than the number of elements in the array (12).

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 9: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Accessing Array Elements◦ The position number in parentheses more formally is called an

index or “subscript.” An index must be a nonnegative integer or integer expression.

◦ If a program uses an expression as an index, the expression is evaluated first to determine the index.

◦ For example, if variable value1 is equal to 5, and variable value2 is equal to 6, then the statement

c(value1 + value2) += 2adds 2 to array element c(11).

◦ The name of an array element can be used on the left side of an assignment statement to place a new value into an array element.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 10: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 11: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Let’s examine array c (Fig. 7.1) more closely. The array’s name is c. Its 12 elements are referred to as c(0) through c(11)

—pronounced as “c sub zero” through “c sub 11,” where “sub” derives from “subscript.” The value of c(0) is -45, the value of c(1) is 6, the value of c(7) is 62 and the value of c(11) is 78.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 12: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Values stored in arrays can be used in calculations. For example, to determine the total of the values

contained in the first three elements of array c and then store the result in variable sum, we would writesum = c(0) + c(1) + c(2)

To divide the value of c(6) by 2 using Integer division and assign the result to the variable result, we’d writeresult = c(6) \ 2

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 13: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Array Length◦ Every array “knows” its own length (that is, number of

elements), which is determined by the array’s Length property, as in:

c.Length

◦ All arrays have the methods and properties of class System.Array.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 14: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

The following statement can be used to declare the array in Fig. 7.1:Dim c(11) As Integer

The parentheses that follow the variable name indicate that c is an array.

Arrays can be declared to contain elements of any type; every element of the array is of that type.

For example, every element of an Integer array contains an Integer value.

The number in parentheses in the array declaration helps the compiler allocate memory for the array c.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 15: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

In the preceding declarations, the number 11 defines the array’s upper bound.

Array bounds determine what indices can be used to access an element in the array.

Here the array bounds are 0 and 11. The bound 0 is implicit in the preceding statement and is

always the lower bound of every array. An index outside these bounds cannot be used to access

elements in the array c. The actual size of the array is one larger (12) than the

specified upper bound.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 16: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

We also can explicitly specify the array bounds, as inDim c(0 To 11) As Integer

The explicit array bounds specified in the preceding statement indicate that the lower bound of the array is 0 and the upper bound is 11.

The size of the array is still 12. Because the lower bound must always be 0, we do not

include “0 To” when declaring an array’s bounds in this book.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 17: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Initializer Lists◦ You can follow an array declaration with an equal sign and an

initializer list in braces ({ and }) to specify the initial values of the array’s elements.

◦ For instance,Dim numbers() As Integer = {1, 2, 3, 6}

declares and allocates an array containing four Integer values.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 18: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

The compiler determines the array bounds from the number of elements in the initializer list—you cannot specify the upper bound of the array when an initializer list is present.

Visual Basic can also use local type inference to determine the type of an array with an initializer list.

So, the preceding declaration can be written as:Dim numbers = {1, 2, 3, 6}

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 19: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Default Initialization◦ When you do not provide an initializer list, the elements in the

array are initialized to the default value for the array’s type—0 for numeric primitive data-type variables, False for Boolean variables and Nothing for String and other class types.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 20: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Figure 7.2 creates two five-element integer arrays and sets their element values, using an initializer list and a For…Next statement that calculates the element values, respectively.

The arrays are displayed in tabular format in the outputTextBox.

Line 10 combines the declaration and initialization of array1 into one statement.

The compiler implicitly allocates the array based on the number of values in the initializer list.

Line 13 declares and allocates array2, whose size is determined by the expression array1.GetUpperBound(0).

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 21: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Array method GetUpperBound returns the index of the last element in the array.

The value returned by method GetUpperBound is one less than the value of the array’s Length property.

For arrays that represent lists of values, the argument passed to GetUpperBound is 0.

In this example, array1.GetUpperBound(0) returns 4, which is then used to specify the upper bound of array2, so array1 and array2 have the same upper bound (4) and the same length (5).

This makes it easy to display the arrays’ contents side-by-side.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 22: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 23: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 24: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

The For statement in lines 16–18 initializes the elements in array2 to the even integers 2, 4, 6, 8 and 10.

These numbers are generated by multiplying each successive value of the loop counter by 2 and adding 2 to the product.

The For statement in lines 24–27 displays the values from the two arrays side-by-side in a TextBox.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 25: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Often, the elements of an array represent a series of related values that are used in a calculation.

For example, if the elements of an array represent students’ exam grades, the instructor might wish to total the elements of the array, then calculate the class average for the exam.

Figure 7.3 sums the values contained in a 10-element integer array named values and displays the result in sumLabel.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 26: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 27: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Line 8 declares, allocates and initializes the 10-element array values.

Line 13, in the body of the For statement, performs the addition.

Alternatively, the values supplied as initializers for array could have been read into the program.

For example, the user could enter the values through a TextBox, or the values could be read from a file on disk.

Information about reading values from a file can be found in Chapter 8, Files.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 28: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Our next example uses arrays to summarize data collected in a survey.

Consider the following problem statement:◦ Twenty students were asked to rate on a scale of 1 to 5 the

quality of the food in the student cafeteria, with 1 being “awful” and 5 being “excellent.” Place the 20 responses in an integer array and determine the frequency of each rating.

◦ This is a typical array-processing application (Fig. 7.4).◦ We wish to summarize the number of responses of each type

(that is, 1–5). Array responses (lines 9–10) is a 20-element

integer array containing the students’ survey responses.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 29: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

The last value in the array is intentionally an incorrect response (14).

When a Visual Basic program executes, array element indices are checked for validity—all indices must be greater than or equal to 0 and less than the length of the array.

Any attempt to access an element outside that range of indices results in a runtime error that is known as an IndexOutOfRangeException.

At the end of this section, we’ll discuss the invalid response value, demonstrate array bounds checking and introduce Visual Basic’s exception-handling mechanism, which can be used to detect and handle an IndexOutOfRangeException.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 30: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 31: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 32: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

The frequency Array◦ We use the six-element array frequency (line 13) to count

the number of occurrences of each response.◦ Each element is used as a counter for one of the possible types

of survey responses—frequency(1) counts the number of students who rated the food as 1, frequency(2) counts the number of students who rated the food as 2, and so on.

◦ The results are displayed in outputTextBox.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 33: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Summarizing the Results◦ The For statement (lines 16–25) reads the responses from the

array responses one at a time and increments one of the five counters in the frequency array (frequency(1) to frequency(5); we ignore frequency(0) because the survey responses are limited to the range 1–5).

◦ The key statement in the loop appears in line 18.◦ This statement increments the appropriate frequency

counter as determined by the value of responses(answer).

◦ Let’s step through the first few iterations of the For statement:

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 34: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

◦ When the counter answer is 0, responses(answer) is the value of responses(0) (that is, 1—see line 10). In this case, frequency(responses(answer)) is interpreted as frequency(1), and the counter frequency(1) is incremented by one.

◦ To evaluate the expression, we begin with the value in the innermost set of parentheses (answer, currently 0). The value of answer is plugged into the expression, and the next set of parentheses (responses(answer)) is evaluated. That value is used as the index for the frequency array to determine which counter to increment (in this case, frequency(1)).

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 35: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

◦ The next time through the loop answer is 1, responses(answer) is the value of responses(1) (that is, 2—see line 10), so frequency(responses(answer)) is interpreted as frequency(2), causing frequency(2) to be incremented.

◦ When answer is 2, responses(answer) is the value of responses(2) (that is, 5—see line 10), so frequency(responses(answer)) is interpreted as frequency(5), causing frequency(5) to be incremented, and so on.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 36: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Regardless of the number of responses processed in the survey, only a six-element array (in which we ignore element zero) is required to summarize the results, because all the correct response values are between 1 and 5, and the index values for a six-element array are 0–5.

In the output in Fig. 7.4, the frequency column summarizes only 19 of the 20 values in the responses array—the last element of the array responses contains an incorrect response that was not counted.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 37: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Exception Handling: Processing the Incorrect Response◦ An exception indicates a problem that occurs while a program

executes.◦ The name “exception” suggests that the problem occurs

infrequently—if the “rule” is that a statement normally executes correctly, then the problem represents the “exception to the rule.”

◦ Exception handling enables you to create fault-tolerant programs that can resolve (or handle) exceptions.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 38: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

In many cases, this allows a program to continue executing as if no problems were encountered.

For example, the Student Poll application still displays results (Fig. 7.4(b)), even though one of the responses was out of range.

More severe problems might prevent a program from continuing normal execution, instead requiring the program to notify the user of the problem, then terminate.

When the runtime or a method detects a problem, such as an invalid array index or an invalid method argument, it throws an exception—that is, an exception occurs.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 39: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

The Try Statement ◦ To handle an exception, place any code that might throw an

exception in a Try statement (lines 17–24).◦ The Try block (lines 17–18) contains the code that might throw

an exception, and the Catch block (lines 19–23) contains the code that handles the exception if one occurs.

◦ You can have many Catch blocks to handle different types of exceptions that might be thrown in the corresponding Try block.

◦ When line 18 correctly increments an element of the frequency array, lines 19–23 are ignored.

The End Try keywords terminate a Try statement.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 40: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Executing the Catch Block ◦ When the program encounters the value 14 in the responses array, it attempts to add 1 to frequency(14), which does not exist—the frequency array has only six elements.

◦ Because array bounds checking is performed at execution time, line 18 throws an IndexOutOfRangeException to notify the program of this problem.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 41: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

At this point the Try block terminates and the Catch block begins executing—if you declared any variables in the Try block, they’re now out of scope and are not accessible in the Catch block.

The Catch block declares an exception parameter (ex) and a type (IndexOutOfRangeException)—the Catch block can handle exceptions of the specified type.

Inside the Catch block, you can use the parameter’s identifier to interact with a caught exception object.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 42: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Entering a Try Statement in the Code Editor ◦ When you create a Try statement in your own code, you begin

by typing Try and pressing Enter.◦ The IDE then generates the following code:

Try

Catch ex As Exception

End Trywhich can catch any type of exception thrown in the Try block.

◦ We changed Exception to IndexOutOfRangeException—the type of exception that might occur in line 18.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 43: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Message Property of the Exception Parameter ◦ When lines 19–23 catch the exception, the program displays a MessageBox indicating the problem that occurred.

◦ Line 21 uses the exception object’s Message property to get the error message that is stored in the exception object and display it in the MessageBox.

◦ Once the user dismisses the MessageBox, the exception is considered handled and the program continues with the next statement after the End Try keywords.

◦ In this example, Next (line 25) causes the program to continue with line 16.

◦ Chapter 16 includes a detailed treatment of exception handling.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 44: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

In Chapter 6, we used a series of counters in our die-rolling program to track the number of occurrences of each face on a six-sided die.

We indicated that we can do what we did in Fig. 6.14 in a more elegant way than using a Select…Case statement to write the dice-rolling program.

An array version of this application is shown in Fig. 7.5.

This new version uses the same GUI as the application in Fig. 6.14.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 45: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 46: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 47: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 48: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 49: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Lines 61–74 of Fig. 6.14 are replaced by line 55 of Fig. 7.5, which uses face’s value as the index for array frequency to determine which element should be incremented during each iteration of the loop.

The random number calculation at line 46 produces numbers from 1 to 6 (the values for a six-sided die); thus, the frequency array must have seven elements so we can use the index values 1–6.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 50: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

We ignore frequency element 0. Lines 37–41 replace lines 35–46 from Fig. 6.14. We can loop through array frequency; therefore, we

do not have to enumerate each line of text to display in the TextBox, as we did in Fig. 6.14.

Recall from Section 6.9 that the more you roll the dice, the closer each percentage should get to 16.66%, as shown in Fig. 7.5(b).

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 51: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Let’s create an application that tests a student’s knowledge of the flags of various countries.

Consider the following problem statement:◦ A geography instructor would like to quiz students on their

knowledge of the flags of various countries. The instructor has asked you to write an application that displays a flag and allows the student to select the corresponding country from a list. The application should inform the user of whether the answer is correct and display the next flag. The application should display a flag randomly chosen from those of Australia, Brazil, China, Italy, Russia, South Africa, Spain and the United States. When the application executes, a given flag should be displayed only once.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 52: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

The application uses arrays to store information. One array stores the country names. Another stores Boolean values that help us determine

whether a particular country’s flag has already been displayed, so that no flag is displayed more than once during a quiz.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 53: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Flag Quiz GUI◦ Figure 7.6 shows the application’s GUI.◦ The flag images should be added to the project as image

resources—you learned how to do this in Section 6.9.◦ The images are located in the Images folder with this

chapter’s examples.◦ This application introduces the ComboBox control, which

presents options in a drop-down list that opens when you click the down arrow at the right side of the control.

◦ A ComboBox combines features of a TextBox and a ListBox.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 54: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

You can click the down arrow to display a list of predefined items.

If you choose an item from this list, that item is displayed in the ComboBox.

If the list contains more items than the drop-down list can display at one time, a vertical scrollbar appears.

You may also type into the ComboBox control to locate an item.

In this application, the user selects an answer from the ComboBox, then clicks the Submit Button to check if the selected country name is correct for the currently displayed flag.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 55: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 56: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

ComboBox property DropDownStyle determines the ComboBox’s appearance.

Value DropDownList specifies that the ComboBox is not editable (you cannot type text in its TextBox).

In this ComboBox style, if you press the key that corresponds to the first letter of an item in the ComboBox, that item is selected and displayed in the ComboBox.

If multiple items start with the same letter, pressing the key repeatedly cycles through the corresponding items.

Set the ComboBox’s DropDownStyle property to DropDownList.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 57: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Then, set the ComboBox’s MaxDropDownItems property to 4, so that the drop-down list displays a maximum of four items at one time.

We do this to demonstrate that a vertical scrollbar is added to the drop-down list to allow users to scroll through the remaining items.

We show how to programmatically add items to the ComboBox shortly.

Figure 7.7 shows the application’s code.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 58: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 59: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 60: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 61: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 62: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 63: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Instance Variables◦ Lines 5–6 create and initialize the array of Strings called countries.

◦ Each element is a String containing the name of a country.◦ The compiler determines the size of the array (in this case,

eight elements) based on the number of items in the initializer list.

◦ Line 7 creates the Random object that is used in method GetUniqueRandomNumber (lines 49–58).

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 64: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Line 10 creates the Boolean array used, which helps us determine which of the countries have already been displayed in the quiz.

We specify the upper bound of the array used by getting the upper bound of the array countries.

By default, each of array used’s elements is set to False.

Variable count (line 12) keeps track of the number of flags displayed so far, and variable country (line 13) stores the name of the country that corresponds to the currently displayed flag.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 65: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Method FlagQuiz_Load◦ When the application loads, method FlagQuiz_Load

executes.◦ ComboBox property DataSource (line 20) specifies the source

of the items displayed in the ComboBox.◦ In this case, the source is array countries.◦ Line 22 calls method DisplayFlag (declared in lines 61–

71) to display the first flag.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 66: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Method submitButton_Click◦ When you click the Submit Button, method submitButton_Click (lines 26–46) determines whether the selected answer is correct and displays an appropriate message (lines 30–35).

◦ If all the flags have been displayed, line 38 indicates that the quiz is over and lines 39–40 disable the ComboBox and Button.

◦ Otherwise, the quiz continues.◦ Line 42 calls method DisplayFlag to display the next flag.◦ Line 43 uses ComboBox property SelectedIndex to select the

item at index 0 in the ComboBox—ComboBoxes are indexed from 0 like arrays.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 67: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Method GetUniqueRandomNumber◦ Method GetUniqueRandomNumber (lines 49–58) uses a Do…Loop Until statement to choose a random number in the bounds of the used array.

◦ The loop performs this task until the value at used(randomNumber) is False, indicating that the corresponding country’s flag has not yet been displayed.

◦ Line 56 marks the flag as used.◦ Line 57 returns the random number.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 68: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Method DisplayFlag◦ Method DisplayFlag (lines 61–71) calls method GetUniqueRandomNumber (line 63) to determine which flag to display.

◦ Line 65 uses that value as the index into the countries array and stores the current country’s name in the variable country.

◦ This variable is used in method submitButton_Click to determine whether the selected answer is correct.

◦ Lines 68–70 get the corresponding flag’s image resource and display it in the flagPictureBox.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 69: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Some of the country names in the countries array contain spaces.

However, the image resource names do not. To use a country name to load the appropriate image

resource, we remove any spaces in the country name by calling String method Replace on country.

The first argument to this method is the substring that should be replaced throughout the original String and the second argument is the replacement substring.

In this case, we’re replacing each space with the empty String ("").

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 70: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

To pass an array argument to a method, specify the name of the array without using parentheses.

For example, if array hourlyTemperatures has been declared asDim hourlyTemperatures(24) As Integer

the method callDisplayDayData(hourlyTemperatures)

passes array hourlyTemperatures to method DisplayDayData.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 71: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Every array object “knows” its own upper bound (that is, the value returned by the method GetUpperBound), so when you pass an array object to a method, you do not need to pass the upper bound of the array as a separate argument.

For a method to receive an array through a method call, the method’s parameter list must specify that an array will be received.

For example, the method header for DisplayDayData might be written asSub DisplayDayData( ByVal temperatureData() As Integer)

indicating that DisplayDayData expects to receive an Integer array in parameter temperatureData.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 72: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Arrays always are passed by reference, so when you pass an array to method DisplayDayData, it can change the original array’s element values.

Although entire arrays are always passed by reference, individual array elements can be passed by value or by reference like simple variables of that type.

For instance, array element values of primitive types, such as Integer, can be passed either by value or by reference, depending on the method definition.

To pass an array element to a method, use the indexed name of the array element as an argument in the method call.

Figure 7.8 demonstrates the difference between passing an entire array and passing an array element.

The results are displayed in outputTextBox.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 73: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 74: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 75: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 76: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 77: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 78: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

The For…Next statement in lines 16–18 displays the five elements of integer array array1 (line 9).

Line 20 passes array1 to method ModifyArray (lines 47–51), which then multiplies each element by 2 (line 49).

To illustrate that array1’s elements were modified in the called method (that is, as enabled by passing by reference), the For…Next statement in lines 25–27 displays the five elements of array1.

As the output indicates, the elements of array1 are indeed modified by ModifyArray.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 79: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Lines 29–32 display the value of array1(3) before the call to ModifyElementByVal.

Line 34 invokes method ModifyElementByVal (lines 55–61) and passes array1(3).

When array1(3) is passed by value, the Integer value in position 3 of array array1 (now an 8) is copied and is passed to method ModifyElementByVal, where it becomes the value of parameter element.

Method ModifyElementByVal then multiplies element by 2 (line 58).

The parameter element of ModifyElementByVal is a local variable that is destroyed when the method terminates.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 80: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Thus, when control is returned to Main, the unmodified value of array1(3) is displayed.

Lines 37–43 demonstrate the effects of method ModifyElementByRef (lines 65–71).

This method performs the same calculation as ModifyElementByVal, multiplying element by 2.

In this case, array1(3) is passed by reference, meaning that the value of array1(3) displayed (lines 42–43) is the same as the value calculated in the method (that is, the original value in the caller is modified by the called method).

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 81: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

The For Each…Next repetition statement iterates through the values in a data structure, such as an array, without using a loop counter.

For Each…Next behaves like a For…Next statement that iterates through the range of indices from 0 to the value returned by GetUpperBound(0).

Instead of a counter, For Each…Next uses a variable to represent the value of each element.

In this example, we’ll use the For Each…Next statement to determine the minimum value in a one-dimensional array of grades.

The GUI for the application is shown in Fig. 7.9 and the code is shown in Fig. 7.10.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 82: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 83: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 84: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 85: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 86: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

When the user clicks the Create Grades Button, method createGradesButton_Click (lines 8–21) creates 10 random grade values in the range 0–99 and places them in the gradesListBox.

When the user clicks the Find Smallest Button, method findSmallestButton_Click (lines 24–38) uses a For Each…Next statement to find the lowest grade.

The header of the For Each repetition statement (line 30) specifies an Integer variable (grade) and an array (gradesArray).

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 87: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

The type of variable grade is determined from the type of the elements in gradesArray, though you can also declare the variable’s type explicitly as inFor Each grade As Integer In gradesArray

The For Each statement iterates through all the elements in gradesArray, sequentially assigning each value to variable grade.

The values are compared to variable lowGrade (line 31), which stores the lowest grade in the array.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 88: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

The repetition of the For Each…Next statement begins with the element whose index is zero, iterating through all the elements.

In this case, grade takes on the successive values that are stored in gradesArray and displayed in the gradesListBox.

When all the grades have been processed, lowGrade is displayed (line 36).

Although many array calculations are handled best with a counter, For Each is useful when you wish to process all of an array’s elements and do not need to access the index values in the loop’s body.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 89: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Sorting data (that is, arranging the data in ascending or descending order) is one of the most popular computing applications.

For example, a bank sorts all checks by account number, so that it can prepare individual bank statements at the end of each month.

Telephone companies sort their lists of accounts by last name and, within last-name listings, by first name, to make it easy to find phone numbers.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 90: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Arrays have the methods and properties of class Array in namespace System.

Class Array provides methods for creating, modifying, sorting and searching arrays.

By default, Array method Sort sorts an array’s elements into ascending order.

The next application (GUI in Fig. 7.11 and code in Fig. 7.12) demonstrates method Sort by sorting an array of 10 randomly generated elements (which may contain duplicates).

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 91: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 92: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 93: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 94: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 95: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Method createDataButton_Click (lines 8–21) assigns 10 random values to the elements of integerArray and displays the contents of the array in the originalValuesTextBox.

Method sortButton_Click (lines 24–35) sorts integerArray by calling Array.Sort, which takes an array as its argument and sorts the elements in the array in ascending order.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Page 96: Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved

Sorting in Descending Order◦ To sort an array in descending order, first call method Sort to

sort the array, then call Array.Reverse with the array as an argument to reverse the order of the elements in the array.

◦ Exercise 7.14 asks you to modify this program to display an array’s values in both ascending and descending order.

© 1992-2011 by Pearson Education, Inc. All Rights Reserved.