Wyo VB Lecture Notes
Objective #1: Declare an array.
- An array is a special kind of variable that can store multiple values.For example,
if you wanted
to
store
five exam grades, it would be more efficient to use an array
instead of 5 separate variables.
Instead of declaring 5 variables with the separate statements
Dim mScore1 As Integer = 0
Dim mScore2 As Integer = 0
Dim mScore3 As Integer = 0
Dim mScore4 As Integer = 0
Dim mScore5 As Integer = 0
you can declare one array named mScores with one simple declaration statement
Dim mScores(5) As Integer
still giving you the ability to store many values but with only one variable name rather than 5 or more. Notice that when we name an array variable we usually use the plural form of a word rather than the singular form (mScores rather than mScore ).
-
This declaration statement
Dim mScores(5) As Integer
creates one array named mScores that has six positions.
Each position of the array can store a separate exam score. The positions are numbered from 0 to 5 for a total of 6 positions.
Therefore the length of the array mScores is considered to be 6 simply because that is how many values it can hold. This is a little confusing since the number 5 is typed into the parentheses in the declaration statement but since there are 6 numbered positions from 0 to 5, the length is considered to be 6. (Note that in other computer languages such as Java when a 5 is typed in the parentheses of the declaration statement, the length is considered to also be 5 since the numbering goes from 0 to the length minus one.)
-
You can declare arrays to be as long as you want up to lengths of 1000 or larger!
- While arrays can be declared as local variables within a method, it is usually more efficient to declare an array at the top of the form as a module variable.
- By default if you declare an array with the statement
Dim mScores(5) As Integer
then the value zero is stored in each position of the array.
However, an array can be initialized in its declaration statement by including the initial
values in a set of curly braces. In this case, you must type empty parenthesis as in this example:
Dim mScores() As Integer = {77, 90, 73, 80, 91}
Objective #2: Use an array to store data.
- You can display a value from an array with statements such as these:
lblOutput.Text = mScores(2)
or
MessageBox.Show(mScores(2))
- However, attempting to access an element that doesn't exist causes an error as in
lblOutput.Text = mScores(20)
since the array mScores above does not have a value stored in subscript position 20!
- The statements
J = 3
MessageBox.Show(mScores(J))
would cause the value 80 to be displayed in a message box since the variable J is 3 and the value 80 is in subscript position 3 of the array.
- You can change a value stored in an array by using this notation. The statement
mScores(1) = 99
would overwrite the 90 with a 99 since 90 is in subscript position 1.
- The length of an array can be determined by using the Length method.
For example,
Dim mScores() As Integer = {77, 90, 73, 80, 91}
MessageBox.Show(mScores.Length())
would cause the number 5 to appear in a message box since the length of the array mScores is 5.
Don't be confused since the value 91 is stored in subscript position 4 however the length of the array is considered to be 5.
- The following example shows how the length of an array can be used as the
upper
bound of a For loop. This loop will traverse the whole array and display each value in a message box one at a time!
For J = 0 To mScores.Length() - 1
MessageBox.Show(mScores(J))
Next
- Here is a code segment that computes the running
total of the elements in an array
Dim mScores() As Integer = {73, 77, 82, 71, 98}
Dim sum As Integer = 0
Dim J As Integer = 0
For J = 0 To mScores.Length() - 1
sum = sum + mScores(J)
Next
Notice that you must start the loop variable J at 0 since the first subscript position of the array is position zero and you must stop J at
the length of the array minus 1. That is, be sure to subtract one from length!
- In addition to storing integers in an array, you can declare an array to store strings or any other variable data type as in
Dim mNames() As String = {"Alfred", "Betty", "Chris", "Donna", "Edgar"}
However, you cannot store two different data types in the same array. That is you cannot mix integers and strings.
You will not be tested on the information below.
Objective #2: Use Array library methods that are built into Visual Basic.
- The Clear method allows you to set one or more of the elements of an array of integers to zero. For example,
Array.Clear(mScores, 0, 4)
would set all of the elements from index position 0 to index position 4 equal to zero.
- The Reverse method reverses the elements in an array. It is used like this Array.Reverse(mScores)
- The BinarySearch method searches an array for a value and returns the index position where the value is found. For example,
Dim mScores() As Integer = {77, 90, 73, 80, 91}
MessageBox.Show(Array.BinarySearch(mScores, 90)
causes the value 1 to display in the message box since the value 90 is found in index position 1 of the array.
- The Sort method sorts an array. The following statement rearranges the elements in mScores so they are in ascending order:
Array.Sort(mScores)
- Here's a method that shuffles the elements in an array. It is adapted from an example at http://www.vb-helper.com/howto_randomize_array.html
Dim numbers() As Integer = {1, 2, 3, 4, 5}
Dim numItems As Integer = 5
Private Sub RandomizeArray()
Dim i As Integer = 0
Dim j As Integer = 0
Dim tmp As Integer = 0
Randomize
For i = 1 To numItems - 1
j = Int((numItems - i + 1) * Rnd + i) ' Pick a random entry
tmp = numbers(i) ' Swap the numbers
numbers(i) = numbers(j)
numbers(j) = tmp
Next i
End Sub
Objective #3 - Create arrays of objects.
- Previously we learned how to create arrays of Integer's, Double's, and String's.
We also previously learned how to make an object (e.g. textbox, label, button, picturebox, etc) using code and without double-clicking the VB Toolbox. Well, we can put all of this together to create
an array of one kind of object using code. For example, you can create 10 or more "alien" pictureboxes and place them on the screen avoiding the need to create them individually using the
mouse. Why would you want to do this? For one, you have more flexibility and control when creating objects with code. Also, it would be very tedious and time consuming to create and edit 30 "alien" picture
boxes when you could use a loop in your computer program do the same thing.
- To declare an array of picture boxes you would use the statement
Dim picSpaceInvaders(5) As New PictureBox
If you want the array to be module-level, you would use the statement
Dim picSpaceInvaders(5) As PictureBox
without using the keyword New. Then in the Form_Load method perhaps, you would use the code
For J = 1 To 5
picSpaceInvaders(J) = New PictureBox ' spaceinvader.gif graphic must be placed in bin/Debug folder
picSpaceInvaders(J).Image = Image.FromFile(Application.StartupPath + "\spaceinvader.gif")
picSpaceInvaders(J).SizeMode = PictureBoxSizeMode.AutoSize
picSpaceInvaders(J).Left = J * 50 ' spreading space invaders out horizontally across the screen
picSpaceInvaders(J).Top = 50 ' top row of space invaders on y-axis
Me.Controls.Add(picSpaceInvaders(J))
Next
The Me.Controls.Add method must be used to actually place each new picture box onto the current form.
This technique is illustrated in a program named something like ArrayOfObjects or SpaceInvaders in the HandOut/Interesting Demos folder.
Objective #4: Use ArrayLists.
- An ArrayList is similar to an array. It can also store multiple items and is primarily used when you need to store objects rather than numbers. To declare an
ArrayList, you use
Dim list As New ArrayList
In a Form1_KeyDown method, you could use something like
If e.KeyCode = Keys.Space Then
Dim next As New Label
next.Top = 50
next.Height = 50
Me.Controls.Add(next)
list.Add(next)
You can also use a For Each loop such as
For Each temp in Me.list
Label.Top += 5
Next
and
For Each control in Me.Controls
If (TypeOF(control) Is Label) Then
control.Top += 5
End If
Next
- The following code segment demonstrates how an ArrayList of PictureBoxes can be used to shoot many bullets
Dim picBullets As New ArrayList
Dim numBullets As Integer = 0
Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If (e.KeyCode = Keys.Space) Then
picBullets.Add(New PictureBox())
picBullets(numBullets).BackColor = Color.Black
picBullets(numBullets).Left = 150
picBullets(numBullets).Top = 200
picBullets(numBullets).Width = 3
picBullets(numBullets).Height = 5
Me.Controls.Add(picBullets(numBullets))
numBullets += 1
End If
End Sub
Private Sub tmrBullets_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrBullets.Tick
For J = 0 To picBullets.Count - 1
If (Not (picBullets(J) Is Nothing)) Then
picBullets(J).Top -= 5
If (picBullets(J).Top <= 0) Then
Me.Controls.Remove(picBullets(J))
picBullets(J) = Nothing
End If
End If
Next
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
picBullets = New ArrayList()
End Sub
- The Count property of an ArrayList keeps track of how many elements are in the ArrayList.