Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
Section 7 – The BASIC Language II Dates
• The Date class holds a date (between January 1st, 0001 and December 31st, 9999) combined with a time (between 0:00:00 and 23:59:59)
• Constructors of the Date class allow you to initialise it with day, month, year, etc.
• The CDate( ) function converts a String to a Date, but will generate an error if the String isn’t appropriate – use of the IsDate( ) function is recommended
Dim s As String = "21/12/1908" Dim d As Date If IsDate(s) Then d = CDate(s) MsgBox(d.ToLongDateString()) End If
• To add and subtract dates, use:
DateAdd(interval, number, date)
Dim d As New Date(2008, 2, 25) Dim d2 As Date d2 = DateAdd(DateInterval.Day, 5, d) MsgBox("5 days after " & d.ToShortDateString() & " is " & d2.ToShortDateString()) d2 = DateAdd(DateInterval.Month, -6, d) MsgBox("6 months before " & d.ToShortDateString() & " is " & d2.ToShortDateString())
To calculate the difference (elapsed period) between two dates, use:
DateDiff(interval, date1, date2) Dim i As Long i = DateDiff(DateInterval.Day, d, d2)
To extract a specified component (year, month, minute, etc.) from a date, use:
DatePart(interval, date) MsgBox("The current hour is: " & DatePart(DateInterval.Hour, Now()))
The DateTimePicker control • Makes it very simple for users to enter a Date,
Time, or Date+Time • The Value property gives you the actual date
selected
• Use the Format property to specify what you want to be displayed and selectable by the user
Format ‘Long’:
Format ‘Short’:
Format ‘Time’:
Built-in Data Structures • Arrays
o Fundamental mechanism in computing o One name, multiple values, arranged as an
indexed list • .NET Collection Classes
o ArrayLists o HashTables o Dictionaries
o Stacks and Queues Arrays: • Lists of items are written, one at a time, to
successive slots in an array • Items can be retrieved by index • The array can be reorganized – e.g. sorted into
alphabetical or numeric order, items removed, inserted etc.
• Limitations are as for any type of list: o Difficult to insert items without disturbing
existing ones (unless empty space is built-in) o Removing an item leaves a ‘hole’ o Locating an item usually requires an
exhaustive search (start at first item and check each until desired item is found)
• Overcoming these limitations requires programming, or using an alternative data structure
Other Data Structures / Collection Classes: • ArrayList
o Like an array, but no need to specify size o Add new items with the .Add() method
• HashTable o A ‘fast-access’ data structure. Items are
searched/retrieved in a time that is almost independent of the number of them
o Uses a Key object (usually a string) as a look-up value for the Item
• Queue o Like a real queue – items join at the back and
leave from the front • SortedList
o Items added to a SortedList are inserted into the list in a pre-defined order (alphabetical, numerical, by date etc.).
o Insertion is slower than adding an item to the end of an array, but retrieval is much faster (binary search)
• Stack o A ‘pile’ of items – added to and removed from
the top only • Collection
o A ‘general-purpose’ list of arbitrary items/objects, held in the order they were added in
• Dictionary o A Key-Value pair list, designed, like
HashTable, for looking up items by their associated key.
o Available only as a base class for customizing to a specific purpose
Collections • A collection object allows you to store members of
any data type, including object data types and even other collection objects, and retrieve them using a unique key
• Similar to ‘associative arrays’ in other modern languages (which refers to an array indexed by something more meaningful than a simple number)
• Methods of the Collection class: o Add (item [, key, before, after] )
• If you don’t specify before or after, the item is added at the end
• If you don’t specify a key, the item is indexed by integer (same as an array)
o Count o Item(key) o Remove(key)
Example: (BankCollection.sln)
Public Class Form1 Dim accounts As New Collection ' collection of bank accounts Dim b As BankAccount ' currently logged-in instance Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Me.Height = 126 End Sub Private Sub btnLogIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogIn.Click ' does account exist with this name? Try b = accounts.Item(txtName.Text) ' account exists: is password correct? If (b.testPassword(txtPassword.Text)) Then ' password correct ' flow of control will pass to below the Try..End Try block Else ' password wrong MsgBox("Incorrect Password!", MsgBoxStyle.Critical) Return End If Catch ' no account with that name: create one? Dim prompt As String prompt = "There is no account with the name " & txtName.Text & ", do you want to create one?" If MsgBox(prompt, MsgBoxStyle.Information Or MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
' do create one b = New BankAccount(txtName.Text, txtPassword.Text, 0) accounts.Add(b, txtName.Text) Else ' don't create one Return End If End Try ' we only arrive here if an account is logged in Me.Height = 223 txtDetails.Text = b.GetDetails() End Sub Private Sub btnDeposit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeposit.Click Dim amt As Integer Try amt = CInt(InputBox("Deposit How Much? €")) b.Deposit(amt) txtDetails.Text = b.GetDetails() Catch End Try End Sub Private Sub btnWithdraw_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWithdraw.Click Dim amt As Integer Try amt = CInt(InputBox("Withdraw How Much? €")) b.Withdraw(amt) txtDetails.Text = b.GetDetails() Catch End Try End Sub End Class Public Class BankAccount Public AccountName As String Private Password As String Private Balance As Decimal Public Sub New(ByVal Name As String) AccountName = Name End Sub Public Sub New(ByVal Name As String, ByVal Pass As String, ByVal Initial As Decimal) AccountName = Name Password = Pass Balance = Initial End Sub Public Sub Deposit(ByVal amt As Integer) Balance += amt End Sub Public Sub Withdraw(ByVal amt As Integer) Balance -= amt End Sub
Public Function GetDetails() Return AccountName & ControlChars.CrLf & "Balance: €" & Balance End Function Public Function testPassword(ByVal Pass As String) Return (Pass = Password) End Function End Class
To iterate through objects held in a Collection Classes, use “For Each”: Dim s As String = "" Dim ba As BankAccount For Each ba In accounts s = s & ba.getDetails() & ControlChars.CrLf Next MsgBox(s)
HashTable example: • Note that Hash Tables do not easily support being
iterated through • The point of a HashTable is to provide fast look-up
(random) access to the elements, not to provide access to the elements in sequence
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim ht As New Hashtable Dim P1 As New Person(111, "Saravanan", 26) Dim P2 As New Person(222, "Selvakumar", 26) Dim P3 As New Person(333, "Venkatesh", 27) ht.Add(P1.id, P1) ht.Add(P2.id, P2) ht.Add(P3.id, P3) Console.WriteLine("Number of items in the HashTable are : " & ht.Count) Dim P As Person If ht.Contains(111) Then Console.WriteLine("Record Found!") P = CType(ht.Item(111), Person) Console.WriteLine("The age of " & P.name & " is " & P.age) Else Console.WriteLine("Record Not Found!")
End If End Sub End Class Public Class Person Public id As Integer Public name As String Public age As Integer Public Sub New(ByVal i As Integer, ByVal s As String, ByVal a As Integer) id = i name = s age = a End Sub End Class
Queue Example: Dim q As New Queue q.Enqueue("One") q.Enqueue("Two") q.Enqueue("Three") q.Enqueue("Four") q.Enqueue("Five") Console.WriteLine("Number of items in the Queue are : " & q.Count) While q.Count > 0 Console.WriteLine(q.Dequeue()) End While
Stack Example: Dim s As New Stack s.Push("One") s.Push("Two") s.Push("Three") s.Push("Four") s.Push("Five") Console.WriteLine("Number of items in the Stack are : " & s.Count) While s.Count > 0 Console.WriteLine(s.Pop()) End While
Advantages of Sorted Lists • In a list of items in random order, it is necessary to
do an exhaustive search when looking for an item that might be in the list
• Just because we have not met it yet does not mean it is not there
• With a sorted list, it is only necessary to look until you reach the point where the item should have been inserted (in the sort order)
• For example, searching for a particular ‘Smith’ in the phone book, you would know to give up once you got beyond the entries for ‘Smith’
• There are even bigger benefits to searching a sorted list, since it is possible to use a Binary Search algorithm
• At each step of the search, able to dismiss ½ of the remaining items
• To perform a binary search in .NET, use a SortedList collection, or an Array to which the Sort() method has been applied, and use the BinarySearch method (see section 3 of this course)
Formatting Numbers • The FormatNumber() function returns a value
formatted as a number. Its general format is: FormatNumber(value [, trailing digits] [, leading digit]
[, parentheses] [, group digits])
• trailing digits is an integer giving the number of digits following the decimal point; the default is rounding to 2 digits
• leading digit (Boolean) indicates whether a leading 0 is to appear before the decimal point for fractional values
• parentheses (Boolean) indicates whether negative numbers should be displayed inside parentheses
• group digits (Boolean) indicates whether numbers should be grouped between commas.
Format Output
FormatNumber(12345.6789) 12,345.68 FormatNumber(12345.6789,5) 12,345.67890 FormatNumber(12345.6789,,,,False) 12345.68 FormatNumber(-12345.6789) -12,345.68 FormatNumber(-12345.6789,,,True) (12,345.68) FormatNumber(.6789) 0.68 FormatNumber(.6789,,False) .68 FormatNumber(-.6789,4) -0.6789
Formatting Dates and Times • The FormatDateTime() function returns a string
expression representing a date/time value:
FormatDateTime(value [, DateFormat.format]) • value is a date or time value • format is one of the following values: GeneralDate,
LongDate, ShortDate, LongTime, or ShortTime.
Format Output FormatDateTime(Now) 3/6/2008 5:25:55 PM
FormatDateTime(Today) 3/6/2008 FormatDateTime(TimeOfDay) 5:25:55 PM FormatDateTime(Now,DateFormat.LongDate) Thursday, March 06, 2008 FormatDateTime(Today,DateFormat.LongDate) Thursday, March 06, 2008 FormatDateTime(Now,DateFormat.ShortDate) 3/6/2008 FormatDateTime(Today,DateFormat.ShortDate) 3/6/2008 FormatDateTime(Now,DateFormat.LongTime) 5:25:55 PM FormatDateTime(TimeOfDay,DateFormat.LongTime) 5:25:55 PM FormatDateTime(Now,DateFormat.ShortTime) 17:25 FormatDateTime(TimeOfDay,DateFormat.ShortTime) 17:25 General Formatting • The Format() function is a general-purpose function
that returns a string value formatted according to a format string.
• The format strings duplicate numeric and date/time formats produced by the specialized formats described above.
Format(value, "format string")
• The characters shown in the following table are
used to compose the format string. Character Description
0 Digit placeholder. Displays a digit or a zero. If the value has a digit in the position, then it displays; otherwise, a zero is displayed.
# Digit placeholder. Displays a digit or a space. If the value has a digit in the position, then it displays; otherwise, a space is displayed.
. Decimal placeholder; determines how many digits are displayed to the left and right of the decimal separator.
, Thousand separator; separates thousands from hundreds within a number that has four or more places to the left of the decimal separator. Only a single "," is required in the format, between the first set of digit
placeholders.
% Percent placeholder. Multiplies the expression by 100. The percent character (%) is inserted in the position where it appears in the format string.
- + $ ( ) Literal characters; displayed exactly as typed in the format string.
Examples:
Format Output Format(012345.6789,"0.00") 12345.68 Format(012345.6789,"0,0.000") 12,345.679 Format(012345.6789,"00000,0.000000") 012,345.678900 Format(012345.6789,"#.##") 12345.68 Format(012345.6789,"#,#.##") 12,345.68 Format(012345.6789,"$ #,#.##") $ 12,345.68 Format(-012345.6789,"#,#.####") -12,345.6789 Format(-012345.6789,"$#,#.##") -$12,345.68 Format(.6789,"#,#.##") .68 Format(.6789,"0,0.000") 00.679 Format(-.6789," 0.0000") - 0.6789 Format(.6789,"0.00%") 67.89%