arrays code: arrays controls: control arrays, picturebox, timer
Post on 13-Jan-2016
256 Views
Preview:
TRANSCRIPT
Arrays
Code: Arrays Controls: Control Arrays, PictureBox, Timer
Seeding Random Number Generators Because the numbers are given by an
algorithm, the same numbers come up each time the algorithm runs
A “seed” is a parameter in the random number generator; changing the seed, changes algorithm results
Randomize seeds the generator off the clock so the program is different at different times Randomize should only be done once, perhaps
in a form_initialize method
Variable Arrays If a group of variables are
of the same type (e.g. all int’s) (Note: same type does not mean same value)
and play a similar role (i.e. the code for them is nearly identical),
it is convenient to make them an array For example, grade1, grade2, …
becomes grade(0), grade(1), …. Chapter 7 in Deitel, Deitel and Nieto
Arrays in Memory Recall variables correspond to
memory locations The elements of an array are
stored in consecutive memory locations
When you refer to the entire array, you “point” to the first memory location
Before ArraysDim Grade1 As IntegerDim Grade2 As IntegerDim Grade3 As IntegerDim Grade4 As IntegerDim Grade5 As IntegerDim Grade6 As Integer
BECOMES
Dim Grade(5) As Integer
After ArraysAverage = (Grade1 + Grade2 + Grade3 +
_ Grade4 + Grade5 + Grade6) / 6
BECOMES
Average = 0For i = 0 To 5 Average = Average + Grade(i)Next iAverage = Average / 6
Array Vocabulary Array: refers to the entire set of related
variables Element: refers to one member of the
array Index: (a.k.a. subscript) is an integer
(0,1,2,…) that is associated with each element
Grade is the array, Grade(3) is an element in that array, that element has an index 3 (note: it is the fourth item)
More Array Vocabulary Option Base:
If you declare Grade(5), VB makes an array with six elements Grade(0) through Grade(5), that is, it starts indexing at 0
If you want to start indexing at 1, you can type Option Base 1 (just below Option Explicit)
Note: Control Arrays are always zero based (regardless of Option Base)
Average, High and Low
Average, High and Low
Average, High and Low
Average, High and LowOption ExplicitConst SCORENUMBER As Integer = 5
Private Sub cmdEnter_Click() Dim Score(SCORENUMBER - 1) As Integer Dim i As Integer Dim Sum As Integer Dim Min As Integer Dim Max As Integer Dim Average As Double
Average, High and Low
Score(0) = InputBox("Enter Score 1: ")
Sum = Score(0) Min = Score(0) Max = Score(0)
‘Enter first score outside of loop and make it the ‘min and the max
Average, High and LowFor i = 1 To SCORENUMBER - 1 Score(i) = InputBox("Enter Score " & i + 1 & ": ") Sum = Sum + Score(i) If Score(i) < Min Then Min = Score(i) End If If Score(i) > Max Then Max = Score(i) End If Next i
Average, High and LowAverage = Sum / SCORENUMBER
txtAverage.Text = Average txtHigh.Text = Max txtLow.Text = MinEnd Sub
Private Sub Form_Load() lblInstruct.Caption = "Click the button below to begin " & _ "entering the " & SCORENUMBER & " scores and “ &
_ “calculate " & “their average, high and low."End Sub
Scaling To scale something is to change its size
(e.g. the number of elements in an array) If a program is written in a way which
facilitates various size changes, it is said to be “scalable”
The use of the constant SCORENUMBER in the previous code made it scalable, since the code would only one change if the size of the score array was varied
Array as argument of function 1
Const NUMBEROFGRADES As Integer = 5Private Sub cmdEnter_Click() Dim Grades(NUMBEROFGRADES-1) As Integer Dim Ave As Double Dim i As Integer For i = 0 To NUMBEROFGRADES-1 Grades(i) = InputBox("Enter Grade " & i, "Grades") Next i Ave = Average(Grades) txtAverage.Text = AveEnd Sub
Array as argument of function 2
Private Function Average(mArray() As Integer) As Double Dim i As Integer Average = 0.0 For i = LBound(mArray) To UBound(mArray) Average = Average + mArray(i) Next i Average = Average / (UBound(mArray) -
LBound(mArray) + 1)End Function
Bounds The Lower Bound is the lowest
index in an array The Upper Bound is the highest
index in an array Lbound(ArrayName) finds the
lower bound Ubound(ArrayName) finds the
upper bound of an array
Shuffle'randomly shuffles an array of stringsPrivate Sub Shuffle(mArray() As String) ‘Strings only Dim i As Integer Dim Swap As String Dim j As Integer dim lb as Integer lb = LBound(mArray) dim ub as Integer ub = UBound(mArray)
For i = lb To ub j = lb + Int((ub - lb + 1) * Rnd()) Swap = mArray(i) mArray(i) = mArray(j) mArray(j) = Swap Next iEnd Sub
By Reference In VB the default situation is that
variables are passed to a function “by reference” (whether or not they are arrays)
That is, if the variable is changed in the function, it is also changed in the caller
More about this in a future lecture
Control array If a group of controls are
of the same type (e.g. all CommandButtons)
and play a similar role (i.e. the code for them is nearly identical),
it is convenient to make them an array
(p. 274 in Deitel, Deitel and Nieto)
Array of TextBoxes
Code for Array of Textboxes
Option Explicit
Private Sub cmdSumHours_Click() Dim i As Integer 'Counter Dim Total As Integer Total = 0 For i = 0 To txtHours.Ubound ‘Ubound is a property NOT
function
Total = Total + txtHours(i).Text Next i txtSum.Text = TotalEnd Sub
Which button was pressed?
Which button revisited (code)
Option ExplicitDim StoreButtonIndex As Integer
Private Sub cmdButton_Click(Index As Integer) StoreButtonIndex = IndexEnd Sub
Private Sub cmdWhich_Click() txtWhich.Text = cmdButton(StoreButtonIndex).Caption
& _ " was last pressed."End Sub
Comes automatically and tells us which button was pressed
Collection of Forms The index property comes into play when a
control is an element in an array Notice that forms do not have an index
property However there is a way to apply these
scaling ideas to forms Forms have an order, the order in which
they are loaded The third form loaded can be referred to as
Forms(2) (zero-based counting) Doesn’t matter what it was named
Toward Scaling with Forms
Option ExplicitDim FormIndex As Integer
Private Sub optForm_Click(Index As Integer) FormIndex = Index + 1End Sub
Private Sub cmdGoToForm_Click() Me.Hide Forms(FormIndex).ShowEnd Sub
Private Sub Form_Load() 'the order in which forms are loaded 'is their order in the collection Call Load(frmNumber1) Call Load(frmNumber2) Load frmNumber3 ‘note alternate syntax for calling subsEnd Sub
PictureBox The pictureBox control (not Image control)
is found near the top of the control in the VB IDE
The properties we will use Picture: refers to the picture to be shown
We’ll load the pictures during runtime instead of during development
Index: since we will make an array of PictureBoxes
Tag: an internal labeling, we can give matching PictureBoxes the same Tag and use that property to test for a match
PictureBox (Cont.) We will load the picture using the
function LoadPicture(filename) which loads an image file include “the complete path” e.g. LoadPicture(“a:\dice2.gif”) If the image files are in the project folder,
one can use App.Path e.g. LoadPicture(App.Path & “\dice2.gif”)
LoadPicture() empties the PictureBox Note: no argument in LoadPicture()
Craps Example
Craps codeOption Explicit
Private Sub cmdRoll_Click() Dim i As Integer Dim Die_Value As Integer For i = 0 To picDie.UBound Die_Value = Int(Rnd() * 6 + 1) picDie(i).Picture = LoadPicture(App.Path & "\dice" & Die_Value & ".gif") Next iEnd Sub
Private Sub cmdClear_Click() Dim i As Integer For i = 0 To picDie.UBound picDie(i).Picture = LoadPicture() Next iEnd Sub
Timer Important Properties
Interval: the amount of time in milliseconds between Timer events
Enabled: When True, Timer events occur, when False, no Timer events occur
Events/Methods Timer: when the timer is enabled a
Timer event occurs roughly every N milliseconds, where N is the Interval property
Stop Watch
Stop Watch CodeOption ExplicitPrivate Sub cmdStart_Click() tmrStopWatch.Enabled = Not tmrStopWatch.Enabled If tmrStopWatch.Enabled Then cmdStart.Caption = "Stop" Else cmdStart.Caption = "Start" End IfEnd Sub
Private Sub tmrStopWatch_Timer() txtTimer.Text = txtTimer.Text + 0.1 ‘interval = 100End Sub
top related