1 / 66

Chapter 8 – Arrays and Structures

Chapter 8 – Arrays and Structures. Controls like the MS flex grid expand on the concept of a programming construct called an array . An array allows you to store multiple values of a data type in a single variable.

yon
Télécharger la présentation

Chapter 8 – Arrays and Structures

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 8 – Arrays and Structures Controls like the MS flex grid expand on the concept of a programming construct called an array. An array allows you to store multiple values of a data type in a single variable. An MS flex grid allows you to do this and provides an interface for the user to see the results graphically. While arrays give you an extremely efficient method of storing data, their rigid structure makes it challenging to delete values or store values of different data types. Visual Basic .NET provides the collection object to allow you to store objects in a single construct of different data types with the ability to easily add, access, and delete values. The Visual Basic .NET Coach

  2. Chapter 8 – Arrays and Structures 8.1 Arrays An array is declared using the following syntax: Dim ArrayName(UpperBound) As Datatype An array’s name obeys the same rules as when declaring a variable: it begins with a letter and may be followed by any number of letters, underscores, or digits. An array name can be as small as one letter or as large as 255 letters, underscores, and digits. Individual values within an array are selected by using an index. The lowest index of an array is 0, while the upper bound of the array is the highest index in the array. An index must be a Short, an Integer, or a Long data type. The data type is any valid variable like a Short, an Integer, or a String. The Visual Basic .NET Coach

  3. Chapter 8 – Arrays and Structures The following code defined an array of six Short values called shtGrades. With valid indexes from 0 to 5, you have six elements. Dim shtGrades(5) As Short Pictorially, the array would be represented as follows: The Visual Basic .NET Coach

  4. Chapter 8 – Arrays and Structures To access an individual value in an array, you place the subscript of the value you wish to access inside the parentheses: ArrayName(Index) If you wanted to output the value stored in the array, shtGrades, at index 3, you could do so in a message box using the following code: MsgBox(shtGrades(3).ToString()) To store grades into the array shtGrades, you would use the following syntax: shtGrades(0) = 90 shtGrades(1) = 80 shtGrades(2) = 77 shtGrades(3) = 100 shtGrades(4) = 95 shtGrades(5) = 67 Graphically, the array would appear as follows: The Visual Basic .NET Coach

  5. Chapter 8 – Arrays and Structures Arrays of Other Data Types Arrays can be used to store values of other types of data besides numerical data. Arrays can be created from any data types. The following code shows how you can create an array of five Strings and initialize them to "Allen Iverson", "Aaron McKie", "Eric Snow", "Matt Harpring", and "Derrick Coleman". Dim strSixersNames(4) As String strSixersNames(0) = "Allen Iverson" strSixersNames(1) = "Aaron McKie" strSixersNames(2) = "Eric Snow" strSixersNames(3) = "Matt Harpring" strSixersNames(4) = "Derrick Coleman" The Visual Basic .NET Coach

  6. Chapter 8 – Arrays and Structures Arrays of Other Data Types Continued If you wanted to store the salary of each player in terms of millions of dollars, you could store them in an array of Single variables. If the salaries of each player were $7 million for Allen Iverson, $5.5 million for Aaron McKie, $4 million for Eric Snow, $2.7 million for Matt Harpring, and $8 million for Derrick Coleman, you could store them in the following code: Dim sngSixersSalaries(5) As Single sngSixersSalaries(0) = 7 sngSixersSalaries(1) = 5.5 sngSixersSalaries(2) = 4 sngSixersSalaries(3) = 2.7 sngSixersSalaries(4) = 8 The Visual Basic .NET Coach

  7. Chapter 8 – Arrays and Structures Drill 8.1 If an array has five elements, what is the highest index of a valid element in the array? Answer: 4 The Visual Basic .NET Coach

  8. Chapter 8 – Arrays and Structures Drill 8.2 How many elements are defined in the following array declaration? Dim strDrillArray(5) As String Answer: 6 The Visual Basic .NET Coach

  9. Chapter 8 – Arrays and Structures Drill 8.3 Write the code required to declare an array of five Strings called strDrillArray. Then initialize the array to the following values: "First Value", "Second Value", "Third Value", "Fourth Value", and "Fifth Value". Answer: Dim strDrillArray(4) As String strDrillArray(0) = "First Value" strDrillArray(1) = "Second Value" strDrillArray(2) = "Third Value" strDrillArray(3) = "Fourth Value" strDrillArray(4) = "Fifth Value" The Visual Basic .NET Coach

  10. Chapter 8 – Arrays and Structures Drill 8.4 Write the code required to declare an array of 1,000 Integers called intDrillArray with an index whose lower bound is 0 and upper bound is 999. Then initialize the array so that each element contains the value of its index. Hint: Use a loop. Answer: Dim intDrillArray(999) As Integer Dim intIndex As Integer For intIndex = 0 To 999 intDrillArray(intIndex) = intIndex Next intIndex The Visual Basic .NET Coach

  11. Chapter 8 – Arrays and Structures Stepping Through an Array To perform some action upon every element in the array you can use a For loop that steps from an index of 0 to the array’s upper bound. To output all of the values in the array strSixersNames use the following code: Dim shtSixerName As Short For shtSixerName = 0 To 4 MsgBox(strSixersNames(shtSixerName)) Next The code assumes that you know the upper bound of the array. It is convenient to use the UBound function to determine the upper bound of an array. By passing an array to UBound, the upper bound of the array is returned. The following shows the previous code rewritten using UBound to determine the highest value of the loop. Dim shtSixerName As Short For shtSixerName = 0 To Ubound(strSixersNames) MsgBox(strSixersNames(shtSixerName)) Next The Visual Basic .NET Coach

  12. Chapter 8 – Arrays and Structures Stepping Through an Array Continued You can loop through the array by stepping through each element of the array. Do not concern yourself with lower or upper bounds. Declare a variable with the same data type as the array that you wish to step through. You can step through the array by using the following syntax: Dim VariableName As VariableType For Each VariableName In ArrayName Do something with VariableName Next By using the For Each looping statement, you can simplify your loop further. See the following code: Dim shtSixerName As Short For Each shtSixerName In strSixersNames MsgBox(shtSixerName) Next The Visual Basic .NET Coach

  13. Chapter 8 – Arrays and Structures Example: TV Ratings Problem Description Create an application that rates a TV show from 1 to 5, with 5 being the best and 1 being the worst. The user should enter the rating with a combo box so that only a value of 1 to 5 can be entered. As each rating is entered, the application should track how many of each rating is selected and display them on the form after 10 ratings are entered. The Visual Basic .NET Coach

  14. Chapter 8 – Arrays and Structures Problem Discussion You could write the application so that the total number of each rating is stored in a separate variable. You could create variables like shtRating1, shtRating2, shtRating3, shtRating4, and shtRating5 and then increment each one every time a vote is cast corresponding to the appropriate variable. Observe the follow code that implements a rating system employing this strategy: 'Code to be placed in the Declarations Section Dim shtRating1 As Short Dim shtRating2 As Short Dim shtRating3 As Short Dim shtRating4 As Short Dim shtRating5 As Short Dim shtTotalVotes As Short The Visual Basic .NET Coach

  15. Chapter 8 – Arrays and Structures Problem Discussion Continued Process each vote as the Voting button is clicked. You must track the total number of votes and output the result when all the votes have been cast. You can process each individual vote by using a Select Case statement and setting up a case for each possible vote. Private Sub btnVote_Click(... 'Check each possible vote. Select Case cboRating.Text Case "1" shtRating1 += 1 Case "2" shtRating2 += 1 Case "3" shtRating3 += 1 Case "4" shtRating4 += 1 Case "5" shtRating5 += 1 End Select 'Increment the number of votes processed shtTotalVotes += 1 'If all ten votes have been processed then output the results If (shtTotalVotes = 10) Then Call OutputResults() End If End Sub The Visual Basic .NET Coach

  16. Chapter 8 – Arrays and Structures Problem Discussion Continued To simplify the processing of the results, you can move code that displays the results into another subroutine. Private Sub OutputResults() lblResults.Text = "1] " & shtRating1.ToString & vbNewLine & _ "2] " & shtRating2.ToString & vbNewLine & _ "3] " & shtRating3.ToString & vbNewLine & _ "4] " & shtRating4.ToString & vbNewLine & _ "5] " & shtRating5.ToString End Sub The Visual Basic .NET Coach

  17. Chapter 8 – Arrays and Structures Problem Discussion Continued If you increased the choice of ratings from 1–5 to 1–100, your application’s code would grow considerably. You need a better approach. Arrays allow a programmer to create a single variable that can store multiple values. These values can be referenced by an index. If you create a simple form with a single combo box that contains only the values 1, 2, 3, 4, and 5 and a button to process the votes, you can store each rating’s votes in an array of Shorts. You will also simplify the execution of the code. The Visual Basic .NET Coach

  18. Chapter 8 – Arrays and Structures Problem Discussion Continued Having a lower bound of 0 is not always convenient. If you wished to create an array of 5 Shorts to store your ratings from 1 to 5, it would seem logical for your array to be indexed from 1 to 5. Visual Basic .NET forces you to start indexing from 0. The following code declares an array of 5 Shorts with an index from 0 to 4. Dim shtRatings(4) As Short This would allocate an array that looks as follows: Elements of an array follow the same initialization rules as the individual data types that the array is composed of. Therefore, if the array is composed of elements of a numerical data type, all the values will be initialized to 0. The Visual Basic .NET Coach

  19. Chapter 8 – Arrays and Structures Problem Discussion Continued You could store the rating’s votes in the array element indexed by 1 less than the rating’s number. This would mean a rating of 1 would be stored at the index 0, a rating of 2 would be stored at the index of 1, a rating of 3 would be stored at the index of 2, etc. Pictorially, it would look as follows: The other option would be to simply declare an array with one more value and ignore the values stored in the element at index 0: The code is simpler, which will make the application smaller even with the wasted space in the array. Furthermore, the application will execute faster, so it is definitely the superior choice. The Visual Basic .NET Coach

  20. Chapter 8 – Arrays and Structures Problem Solution Add the code required in the Declarations section: an array and a single variable to store the total number of votes. 'Code to be placed in the Declarations Section Dim shtRatings(5) As Short Dim shtTotalVotes As Short The Visual Basic .NET Coach

  21. Chapter 8 – Arrays and Structures Problem Solution Continued You can combine the code for storing the vote and outputting the results. Use a For loop to step through the array and display each individual value: Private Sub btnRatings_Click(... 'Declare variables Dim strOutputString As String Dim shtVote As Short 'Add 1 to the current rating shtRatings(Val(cboRating.Text)) += 1 'Add 1 to the total number of votes shtTotalVotes += 1 'Check if all the votes have been entered If (shtTotalVotes = 10) Then 'Build the output string by looping through the array For shtVote = 1 To 5 strOutputString &= " " & shtVote.ToString() & "] " & _ shtRatings(shtVote).ToString() & vbNewLine Next shtVote 'Copy the output string to the label lblResults.Text = strOutputString End If End Sub The Visual Basic .NET Coach

  22. Chapter 8 – Arrays and Structures Initializing Arrays at Time of Declaration It is often convenient to initialize an array in the same line of code as you declare the array. You can initialize an array by setting it equal to the values you wish to initialize the array to enclosed within curly braces and separated by commas. Observe the code initializing the strSixersNames array to the same values, but with one line of code: Dim strSixersNames() As String = {"Allen Iverson", "Aaron McKie", _ "Eric Snow", "Matt Harpring", _ "Derrick Coleman"} You can initialize the sngSixersSalaries with the following code: Dim sngSixersSalaries() As Single = {7, 5.5,4 ,2.7, 8} The Visual Basic .NET Coach

  23. Chapter 8 – Arrays and Structures Drill 8.5 Declare and initialize an array of five prices—19.95, 12.95, 10.95, 99.99, 10.00—called sngPrices of data type Single. Answer: Dim sngPrices(4) As Single = {19.95, 12.95, 10.95 ,99.99, 10.00} The Visual Basic .NET Coach

  24. Chapter 8 – Arrays and Structures Drill 8.6 Declare and initialize an array called strMovies of the data type String. The array should be initialized at the time it is declared to these five movie titles: "The Princess Bride", "Space Balls", "Clerks", "Shrek", and "Fletch". Answer: Dim strMovies(4) As Single = {"The Princess Bride", "Space Balls",_ "Clerks", "Shrek", "Fletch"} The Visual Basic .NET Coach

  25. Chapter 8 – Arrays and Structures 8.2 Two-Dimensional Arrays The arrays that have been introduced so far all have one dimension and are referred to as single-dimensional arrays. You can also simplify your handling of multiple arrays by using a two-dimensional array. Revisit your rating system application. Store the results for 10 television shows, as show here: The Visual Basic .NET Coach

  26. Chapter 8 – Arrays and Structures Visual Basic .NET provides two-dimensional arrays, which will efficiently solve the problem of storing 10 sets of 10 ratings. A two-dimensional array is declared using the following template: Dim ArrayName(UpperBound1,UpperBound2) As Datatype You must create the interface to a rating for each of 10 TV shows. You can create the interface shown in previous figure by using two combo boxes, a series of labels, and a single button. The Visual Basic .NET Coach

  27. Chapter 8 – Arrays and Structures Declaring an Array You must declare a two-dimensional array of ratings in the Declarations section of the application. The two-dimensional array of Integers can be thought of as a grid with the ratings for each TV show contained within a single row of the grid: The code is like this: 'Code to be placed in the Declarations Section Dim shtRatings(5, 5) As Integer The Visual Basic .NET Coach

  28. Chapter 8 – Arrays and Structures Processing a Vote Once you have determined that the selections in the combo boxes are valid, you can use the SelectedIndex of each combo box as an index into the two-dimensional array. The cboTVShow combo box will select the row, while the cboRating combo box will select the column. The actual vote will be recorded by adding 1 to the value stored at the location specified by the two combo boxes. The code follows: Private Sub btnVote_Click(... 'Check for valid input If (cboTVShow.Text = "" Or cboRating.Text = "") Then MsgBox("A vote will only count if you enter a valid show _ and rating") Else 'Process Vote 'Record Vote shtRatings(cboTVShow.SelectedIndex, cboRating.SelectedIndex) += 1 cboTVShow.Text = "" 'Clear choice cboRating.Text = "" 'Clear choice End If End Sub The Visual Basic .NET Coach

  29. Chapter 8 – Arrays and Structures Outputting the Results To output the results of 10 ratings for each of 10 shows, you must loop through the two-dimensional array one row at a time. You can set up a nested For with the outer loop stepping through the TV shows and the inner loop stepping through the votes. The code follows: Private Sub btnResults_Click(... 'Declare variables Dim shtTVShow As Integer Dim shtVote As Integer Dim strOutputString As String 'Loop through the TV Shows For shtTVShow = 0 To 4 'Store the name of the show in the results strOutputString &= cboTVShow.Items(shtTVShow) & " “ 'Loop through the possible ratings For shtVote = 0 To 4 'Store results of a vote in a String strOutputString &= (shtVote + 1).ToString & "] " & _ (shtRatings(shtTVShow, shtVote).ToString) & " " Next shtVote 'Start a new line after each show strOutputString &= vbNewLine Next shtTVShow 'Copy results from String to label. lblResults.Text = strOutputString End Sub The Visual Basic .NET Coach

  30. Chapter 8 – Arrays and Structures Drill 8.7 What’s wrong with the following code, which declares a two-dimensional array to store the number and name of each of the players for the Sixers? Dim intPlayers(5, 2) As Integer intPlayers(0,0) = 3 intPlayers(0,1) = "Allen Iverson" intPlayers(1,0) = 20 intPlayers(1,1) = "Eric Snow" intPlayers(2,0) = 42 intPlayers(2,1) = "Matt Harpring" intPlayers(3,0) = 8 intPlayers(3,1) = "Aaron McKie" intPlayers(4,0) = 40 intPlayers(4,1) = "Derrick Coleman" Answer: you cannot mix data types in an array. The Visual Basic .NET Coach

  31. Chapter 8 – Arrays and Structures Drill 8.8 What’s wrong with the following code, which declares a two-dimensional array of integers and initializes each value to 2? Dim intDrillValues(5, 5) As Integer Dim intRow As Integer Dim intCol As Integer For intRow = 5 To 1 Step -1 For intCol = 5 To 1 Step -1 intDrillValues(intRow, intCol) = 2 Next intCol Next intRow Answer: the code does not initialize the values in the row and column with an index of 0. The Visual Basic .NET Coach

  32. Chapter 8 – Arrays and Structures Drill 8.9 Will the following two sets of code accomplish the same result? If not, explain why not. Dim intDrillValues(2, 2) As Integer Dim intRow As Integer Dim intCol As Integer For intRow = 0 To 2 For intCol = 0 To 2 intDrillValues(intRow, intCol) = 2 Next intCol Next intRow Dim intDrillValues(2, 2) As Integer Dim intRow As Integer Dim intCol As Integer For intCol = 0 To 2 For intRow = 0 To 2 intDrillValues(intCol, intRow) = 2 Next intRow Next intCol Answer: they accomplish the same result. The Visual Basic .NET Coach

  33. Chapter 8 – Arrays and Structures Drill 8.10 Will the following two sets of code accomplish the same result? If not, explain why not. Dim intDrillValues(4, 2) As Integer Dim intRow As Integer Dim intCol As Integer For intRow = 0 To 4 For intCol = 0 To 2 intDrillValues(intRow, intCol) = 2 Next intCol Next intRow Dim intDrillValues(4, 2) As Integer Dim intRow As Integer Dim intCol As Integer For intCol = 0 To 4 For intRow = 0 To 2 intDrillValues(intRow, intCol) = 2 Next intRow Next intCol Answer: they do not accomplish the same result. The Visual Basic .NET Coach

  34. Chapter 8 – Arrays and Structures 8.3 Collections There are a few major limitations to an array. An array can only store values of the same data type; an array makes it difficult to look up values; and an array makes it difficult to delete values. A collection gives you the functionality to accomplish all of these tasks effortlessly. A collection is a class that comes with Visual Basic .NET. The Items property of a combo or list box is a collection object. Collections can also be declared in code. To declare a collection, you would follow the same syntax as any other reference variable or object. Observe the following syntax: Dim CollectionName As New Collection() To declare a collection called Students, you would use the following code: Dim Students As New Collection() Once a collection is declared, it can be manipulated using the Add, Item, and Remove methods. The Visual Basic .NET Coach

  35. Chapter 8 – Arrays and Structures Adding Items to Collection To add an item to a collection, you simply call the Add method with two parameters. Observe the following syntax for adding an item to a method: CollectionName.Add(ItemToAdd, KeyValue) The ItemToAdd can be an object, an Integer, a String, or any value you wish to store in the collection. The KeyValue is either a numeric value or String that uniquely identifies the value you are adding to the collection. The Visual Basic .NET Coach

  36. Chapter 8 – Arrays and Structures Adding Items to Collection Continued Imagine if you wanted to create a collection of students that were in a Visual Basic .NET class. You would need to declare a class called Students. It should have properties for first name, last name, student number, major, and GPA. Then you could declare a collection called VBClass to store the students: Public Class Student 'Private attributes Private mstrFirstName As String Private mstrLastName As String Private mstrMajor As String Private mlngStudentNumber As Long Private msngGPA As Single 'FirstName Property Statements Public Property FirstName() As String Get Return mstrFirstName End Get Set(ByVal Value As String) mstrFirstName = Value End Set End Property The Visual Basic .NET Coach

  37. Chapter 8 – Arrays and Structures Adding Items to Collection Continued Student class continued: 'LastName Property Statements Public Property LastName() As String Get Return mstrLastName End Get Set(ByVal Value As String) mstrLastName = Value End Set End Property 'Major Property Statements Public Property Major() As String Get Return mstrMajor End Get Set(ByVal Value As String) mstrMajor = Value End Set End Property The Visual Basic .NET Coach

  38. Chapter 8 – Arrays and Structures Adding Items to Collection Continued Student class continued: 'StudentNumber Property Statements Public Property StudentNumber() As Long Get Return mlngStudentNumber End Get Set(ByVal Value As Long) mlngStudentNumber = Value End Set End Property 'GPA Property Statements Public Property GPA() As Single Get Return msngGPA End Get Set(ByVal Value As Single) msngGPA = Value End Set End Property The Visual Basic .NET Coach

  39. Chapter 8 – Arrays and Structures Adding Items to Collection Continued Student class continued: 'Constructor Sub New(ByVal strFirstName As String, ByVal strLastName As String, _ ByVal strMajor As String, ByVal lngStudentNumber As Long, _ ByVal sngGPA As Single) mstrFirstName = strFirstName mstrLastName = strLastName mstrMajor = strMajor mlngStudentNumber = lngStudentNumber msngGPA = sngGPA End Sub End Class 'Declare and instantiate collection called VBClass Dim VBClass As New Collection() 'Declare and instantiate an object of the student class Dim clsStudent As New Student("Jeff", "Salvage", _ "Computer Science", 123456789, 3.9) 'Add the student object to the collection VBClass.Add(clsStudent, "Jeff Salvage") 'instantiate another object of the student class clsStudent = New Student("John", "Nunn", "Pre Med", 987654321, 4.0) 'Add the 2nd student to the collection VBClass.Add(clsStudent, "John Nunn") The Visual Basic .NET Coach

  40. Chapter 8 – Arrays and Structures Retrieving Values from a Collection Retrieving a value from a collection returns a reference to the item you request. It allows you to easily access a value stored in the collection without removing the value from the collection. There are two ways you can retrieve values that you have stored in a collection. Both use the Item method. The most intuitive way to retrieve items is to look it up using the KeyValue you added it to the collection with. See the following syntax: VariableName = CollectionName.Item(KeyValue) If you wanted to retrieve the student with the KeyValue "John Nunn“ from the VBClass collection, you would use the following code: Dim clsRetrievedStudent As Student clsRetrievedStudent = VBClass.Item("John Nunn") The Visual Basic .NET Coach

  41. Chapter 8 – Arrays and Structures Retrieving Values from a Collection Continued The other way you can retrieve items from a collection is by using the items index. As each item is added to a collection, it is given an index. In the previous example, the first student added to the collection is given the index 1, and the second student is given the index 2. Therefore, if you want to access the object containing Jeff Salvage’s information, you would use an index of 1, while if you wanted to access the object containing John Nunn’s information, you would use an index of 2: 'Declare object to hold a student Dim clsRetrievedStudent As Student 'Assign a student from the collection at index 1 to the object clsRetrievedStudent = VBClass.Item(1) 'Output information from the retrieved object MsgBox(clsRetrievedStudent.FirstName & " " & clsRetrievedStudent.LastName) 'Assign another student from the collection at index 2 to the object clsRetrievedStudent = VBClass.Item(2) 'Output information from the 2nd student MsgBox(clsRetrievedStudent.FirstName & “ “ & clsRetrievedStudent.LastName) The Visual Basic .NET Coach

  42. Chapter 8 – Arrays and Structures Deleting Values from a Collection To delete a value from a collection without returning it, use the Remove method. The Remove method can be used in two ways, just like the Item method. Either you can delete a value by using the KeyValue that you added it to the collection with or you can use the index of the item. The syntax to delete an object from a collection using the KeyValue is as follows: CollectionName.Remove(KeyValue) If you wanted to delete the student with the KeyValue "Jeff Salvage", you would use the following code: VBClass.Remove("Jeff Salvage") The syntax to delete an object from a collection using the index is as follows: CollectionName.Remove(Index) If you wanted to delete the first student in the collection, you would use the following code: VBClass.Remove(1) The Visual Basic .NET Coach

  43. Chapter 8 – Arrays and Structures Drill 8.11 Does the following code execute without error? If so, is anything left in the collection? Dim VBClass As New Collection() Dim clsStudent As New Student("Jeff", "Salvage", _ "Computer Science", 123456789, 3.9) VBClass.Add(clsStudent, "Jeff Salvage") clsStudent = New Student("John", "Nunn", "Pre Med", 987654321, 4.0) VBClass.Add(clsStudent, "John Nunn") VBClass.Remove(2) VBClass.Remove(1) Answer: The code does not produce an error and nothing is left in the collection when it’s done. The Visual Basic .NET Coach

  44. Chapter 8 – Arrays and Structures Example: Student Class with Collections for Grades Problem Description Create a Student class that can track a student’s first name, last name, student number, major, and any number of class grades (0 to 4). The class should have properties to access each of the values being tracked and a method to return the GPA. Problem Discussion A property must exist for each value tracked. The first name, last name, and major should all be Strings, while the student number should be a Long. Since you want to be able to store any number of grades, a collection is an ideal choice. This will allow you to add, remove, and look up grades by using the methods that are built into a collection. By implementing the storage of grades as a collection, no additional information is required to write the GPA method. The Visual Basic .NET Coach

  45. Chapter 8 – Arrays and Structures Problem Solution The GPA method will calculate the average of the grades contained within the collection. A For loop is used to add each grade to a total. By accessing the Count method of a collection, the GPA method can determine the total number of grades and calculate the average. Public Class Student 'Property Declarations for Student Private mstrFirstName As String Private mstrLastName As String Private mlngStudentNumber As Long Private mstrMajor As String Private mintGrades As Collection 'FirstName Get and Set statements Public Property FirstName() As String Get Return mstrFirstName End Get Set(ByVal Value As String) mstrFirstName = Value End Set End Property The Visual Basic .NET Coach

  46. Chapter 8 – Arrays and Structures Problem Solution Continued Student class continued: 'LastName Get and Set statements Public Property LastName() As String Get Return mstrLastName End Get Set(ByVal Value As String) mstrLastName = Value End Set End Property 'StudentNumber Get and Set statements Public Property StudentNumber() As Long Get Return mlngStudentNumber End Get Set(ByVal Value As Long) mlngStudentNumber = Value End Set End Property The Visual Basic .NET Coach

  47. Chapter 8 – Arrays and Structures Problem Solution Continued Student class continued: 'Major Get and Set statements Public Property Major() As String Get Return mstrMajor End Get Set(ByVal Value As String) mstrMajor = Value End Set End Property 'Grades Get and Set statements Public Property Grades() As Collection Get Return mintGrades End Get Set(ByVal Value As Collection) mintGrades = Value End Set End Property The Visual Basic .NET Coach

  48. Chapter 8 – Arrays and Structures Problem Solution Continued Student class continued: 'Constructor for Student Class Public Sub New(ByVal strFirstName As String, _ ByVal strLastName As String, _ ByVal lngStudentNumber As Long, _ ByVal strMajor As String) mstrFirstName = strFirstName mstrLastName = strLastName mlngStudentNumber = lngStudentNumber mstrMajor = strMajor End Sub 'GPA method Public Function GPA() As Single Dim intSum As Integer Dim intGrade As Integer intSum = 0 For Each intGrade In mintGrades intSum += intGrade Next Return intSum / mintGrades.Count() End Function End Class The Visual Basic .NET Coach

  49. Chapter 8 – Arrays and Structures Collections of Different Objects The following code creates a collection called People and stores a person that was created from the Employee class and the Student class. 'Declare and instantiate a collection of people Dim People As New Collection() 'Declare and instantiate the student Jeff Salvage Dim clsStudent As New Student("Jeff", "Salvage", _ 123456789, "Computer Science") 'Declare and instantiate the employee Nelson Brown Dim clsEmployee As New Employee("Nelson", "Brown", 8, 8, 7, 7, 9, 50.0) 'Add the student Jeff Salvage to the collection People.Add(clsStudent, "Jeff Salvage") 'Add the employee Nelson Brown to the collection People.Add(clsEmployee, "Nelson Brown") The Visual Basic .NET Coach

  50. Chapter 8 – Arrays and Structures 8.4 Structures A structure in Visual Basic .NET can be thought of as a class with fewer features. Specifically, a structure cannot be inherited as classes can. Other than that, they are very similar except for the fact that structures are allocated quicker than objects. However, the area of memory in which they are allocated is limited, and therefore, structure use should be limited to constructs that require speed. Objects are reference type variables and must be allocated with a New command. Structures are value type variables and can be instantiated without the New command in the same manner as Integers, Decimals, and Booleans. Structures should be used with caution. Inheritance is a key concept that will allow you to reuse code in an efficient manner. Choosing a structure implementation over a class will limit the future expansion of your construct. By allocating memory for a structure from the stack as opposed to the heap, you could have memory allocation problems. The heap, while slower than the stack, is much larger. If a large number of structures are stored in an application, it could lead to problems. The Visual Basic .NET Coach

More Related