Collections and classes. Projects in this ppt Collection interface practice The microwave oven...

Post on 20-Dec-2015

217 views 2 download

Transcript of Collections and classes. Projects in this ppt Collection interface practice The microwave oven...

Collections and classes

Projects in this ppt

• Collection interface practice

• The microwave oven simulator

• Bank account

A collection is

• Linear, like an array• Not static, but extensible in length• Homogeneous, but made up of key-value

pairs that don’t have to have the same data type.

• You don’t always reference indices, although you may– You can reference “before” or “after”– You can get an index out of range error, as with

an array, if you use an illegal index

Adding items

• GivenDim guys as Collectionguys= new Collection• Then use:

mycollection.add(theItem)• Ormycollection.add(theItem, keyval)• Ormycollection.add(theItem, keyval,beforeguy)• Ormycollection.add(theItem, keyval,,afterguy)

An interface to test collection

Suppose 9999 is added with key=“Special”

“Find” entry with key=“Special”

Code for Find button uses the collection.contains() method

Private Sub btnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFind.Click

Dim key As String key = txtKey.Text If Guys.Contains(key) Then lstdisplay.Items.Add("Found") Else lstdisplay.Items.Add("Not Found") End If End Sub

Removing “Special” value

Adding “before” another key uses collection.add(data,key,beforewhichone)

Private Sub btnBefore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBefore.Click

data = txtData.Text keyVal = txtKey.Text Dim before As String before = txtPosition.Text Guys.Add(data, keyVal, before)

Display() End Sub

Add Jim before Sue

Add before another key

Object-Oriented programming

• Object-oriented languages make abstractions and simplifications of real world entities which need to be modeled to define “objects” in the software.

• Essential features of the real-world “object” are “properties” of the software object.

• Essential functionality of the real-world entity becomes a service or method or function of the software entity.

• Objects have fields and methods. Fields hold values, methods do stuff.

• A “student” object might have fields: name, address, GPA, and so on.

Object-Oriented programming continued

• Simple accessor and mutator methods allow a programmer to get or set field values of an object.

• Get and set are the words which are used to define these methods in VB, although attributes of a class called its “properties” can also be used to get at this information in VB

• So a student object might have a String field called Name, and methods getName() to retrieve the name and setName(toNewName) to change the name.

• We won’t talk about these methods for quite a while, but in VB they are called subs and functions.

OOP…building your own classes in VB

• OOP refers to object-oriented programming. A class is a definition of an object.

• Objects are programmatic analogies to real-life entities.

• Objects have fields, constructors and methods.• VB supports objects. Notice, your form is a

“class”.• A class is an instantiation of an object

Microwave project

Building a class: select vb class

Code for time classPublic Class Time Dim minutes, seconds As Integer Public Sub New(ByVal mtmp As Integer, ByVal sectmp

As Integer) minutes = mtmp seconds = sectmp End SubPublic Sub New() minutes = 0 seconds = 0 End SubEnd Class

constructor

• Constructor for a class is New()

• Multiple constructors are allowed – see previous slide

• Arguments passed depend on the class being constructed

Adding an instance of a class to a project

Getter/Setter methods (Accessor and mutator methods)

• Accessor methods are called get

• Mutator methods are called set

• These appear in VB as properties of fields

Time class with minute propertyPublic Class Time Dim minutes, seconds As Integer Public Sub New(ByVal mtmp As Integer, ByVal sectmp As Integer) minutes = mtmp seconds = sectmp End Sub Public Property minute() As Integer Get ‘code goes here End Get Set(ByVal Value As Integer)

‘code goes here End Set End PropertyEnd Class

Constructor setting properties

Public Sub New(ByVal mtmp As Integer, ByVal sectmp As Integer)

minute = mtmp 'using type checking of property

second = sectmp

End Sub

The entire time classPublic Class Time Dim minutes, seconds As Integer Public Sub New(ByVal mtmp As Integer, ByVal sectmp As Integer) minute = mtmp 'using type checking of property second = sectmp End Sub Public Property minute() As Integer Get Return minutes End Get Set(ByVal Value As Integer) If Value >=0 and Value < 60 Then minutes = Value Else minutes = 0 End If End Set End Property Public Property second() As Integer Get Return seconds End Get Set(ByVal Value As Integer) If Value >=0 and Value < 60 Then seconds = Value Else seconds = 0 End If End Set End PropertyEnd Class

Timer object• you can get a timer from the tookbox and add it

(to your component tray)

Microwave, running

Microwave done

Using a timer

• Be sure to enable your timer.Tmrclock.enabled=true• ' Sets the timer interval to 1 seconds. tmrclock.Interval = 1000 strtime = "“• Be sure to start your timerTmrclock.start()• In the microwave example, the timer needs to be

“reset” when they press the start button.

The clock tick sub Private Sub tmrClock_Tick(ByVal sender As System.Object, ByVal e

As System.EventArgs) Handles tmrclock.Tick If timeobj.second > 0 Then timeobj.second -= 1 ElseIf timeobj.minute > 0 Then timeobj.minute -= 1 timeobj.second = 59 Else tmrclock.Enabled = False Beep() Lbl.Text = "done" pnl.BackColor = Color.Black Return End If Lbl.Text = String.Format("{0:d2}:{1:d2}", timeobj.minute,

timeobj.second)

End Sub

Display time sub Sub displayTime() Dim intsec, intmin As Integer Dim strdisplay As String If strtime.length > 4 Then strtime = strtime.substring(0, 4) End If strdisplay = strtime.padleft(4, convert.tochar("0")) intsec = Convert.ToInt32(strdisplay.Substring(2)) intmin = Convert.ToInt32(strdisplay.Substring(0, 2)) timeobj = New Time(intmin, intsec) Lbl.Text = String.Format("{0:D2}:{1:D2}", intmin,

intsec) End Sub

Start button Private Sub start_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles start.Click Dim intsec As Integer Dim intmin As Integer strtime = strtime.PadLeft(4, Convert.ToChar("0")) intsec = Convert.ToInt32(strtime.substring(2)) intmin = Convert.ToInt32(strtime.Substring(0, 2)) timeobj = New Time(intmin, intsec) Lbl.Text = String.Format("{0:d2}:{1:d2}", timeobj.minute,

timeobj.second) strtime = "" tmrClock.enabled = True pnl.BackColor = Color.Yellow End Sub

Clear button

Private Sub clear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles clear.Click

Lbl.Text = "Microwave"

strtime = ""

timeobj = New Time(0, 0)

tmrClock.enabled = False

pnl.BackColor = Color.Black

End Sub

A button click

Private Sub Btn1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn1.Click

Beep()

strtime &= "1"

displayTime()

End Sub

A sort of bank account project

Button events

• First and last buttons display respectively the customers who are first and last in the customer array

• Next displays the next customer and previous displays the previous customer

The account classPublic Class Account Dim first, last, middle As String Dim balance As Double Dim accountnum As String‘constructor sets name fields, balance and account number info Public Sub New(ByVal ftmp As String, ByVal mtmp As String, ByVal ltmp As

String, ByVal bal As Double, ByVal acct As String) firstName = ftmp midName = mtmp lastName = ltmp acctBalance = bal accountNumber = acct End Sub Public Property firstName() As String Get Return first End Get Set(ByVal ftmp As String) first = ftmp End Set End Property

Account class continuedPublic Property midName() As String Get Return middle End Get Set(ByVal ftmp As String) middle = ftmp End Set End Property Public Property lastName() As String Get Return last End Get Set(ByVal ftmp As String) last = ftmp End Set End Property Public Property acctBalance() As Double Get Return balance End Get Set(ByVal ftmp As Double) balance = ftmp End Set End Property Public Property accountNumber() As String Get Return accountnum End Get Set(ByVal ftmp As String) accountnum = ftmp End Set End PropertyEnd Class

Bank proj uses an array of accounts

Dim customers As Account()

Const num = 20

Dim current As Integer = -1

accounts

Dim i As Integer

For i = 1 To num

customers(i) = New Account("bob" & i, "micky" & i, "jones" & i, 1.0, "0" & i & "0" & i)

Next

The set button sets current customer fields to updated content

Revisiting this entry shows updated data

The get button

• Get button should take a last name or account number and display that person’s information

Data is retrieved

One of the two lookup functions

Private Function lookupName(ByVal last As String) As Integer

Dim temp As Integer = 0 Dim j As Integer For j = 1 To num If last = customers(j).lastName Then temp = j End If Next lookupName = temp End Function

Optional arguments

• There are ways to get around writing two different lookup functions, one for a last name and one for an account number.

• We could send either last name or account number along with a control parameter (1=lastname supplied, 2= accountnumber supplied)

• C++ and VB allow optional arguments to be passed. It doesn’t save a lot of work, but a later slide shows the code with optional arguments.

Preparing to look for a name

Customer is found by last name or acct

Code for get buttonPrivate Sub btnGet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles

btnGet.Click Dim find As Integer If txtLast.Text = "" And txtAccount.Text = "" Then MessageBox.Show("you must enter name or account number", "data entry error",

MessageBoxButtons.OK, MessageBoxIcon.Error) Return Else If txtLast.Text = "" Then find = lookup(, txtAccount.Text) Else find = lookup(txtLast.Text, ) End If If find < 1 Then MessageBox.Show("you must enter valid name or account number", "data entry error",

MessageBoxButtons.OK, MessageBoxIcon.Error) Else current = find display() End If End If End Sub