Chapter 14 • Shipping time application using dates and timers • Create and manipulate Date variables. • Execute code at regular intervals using a Timer control. • Retrieve Date input with a DateTimePicker control. • Group controls using a GroupBox control.
51
Embed
Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Chapter 14
• Shipping time application using dates and timers
• Create and manipulate Date variables.
• Execute code at regular intervals using a Timer control.
• Retrieve Date input with a DateTimePicker control.
• Group controls using a GroupBox control.
Chapter 14A seafood distributor has asked you to create an application that will calculate the delivery time for seafood shipped from Portland, Maine, to its distribution center in Las Vegas, Nevada. The distributor has arrangements with local airlines to guarantee that seafood will ship on flights that leave either at noon or at midnight. The airport requires the distributor to drop off the seafood at the airport at least one hour before each flight. When the distributor specifies the drop-off time, the application should display the delivery time in Las Vegas. This application should take into account the three-hour time difference (it’s three hours earlier in Las Vegas) and the six-hour flight time between the two cities. The application should allow the user to select drop-off times within the current day (seafood must be shipped within a day to guarantee freshness). The application should also include a running clock that displays the current time.
Chapter 14• So basically:
– If the shipment is dropped between 11:00AM and 10:59PM, it is shipped at 12:00AM the next day and reaches Las Vegas at 3:00AM the next day
– If the shipment is dropped between 11:00PM and 10:59AM, it is shipped at 12:00PM the same day and reaches Las Vegas at 3:00PM the same day
• To develop this application we use primitive data type Date.
• Date is the visual basic keyword that corresponds to the DateTime structure in Framework Class Library (FLC)
Chapter 14• Dim delivery As Date = New Date (2003, 1,1, 0, 0, 0)• Keyword NEW calls the Date structures constructor• A constructor is a procedure that initializes a class
object or structure value when it is created.
Argument Range Description
Initializing a Date variable using New Date (year, month, day, hour, minute, second)
year Integer values 1–9999 Specifies the year.
month Integer values 1–12 Specifies the month of the year.
day Integer values 1–number of days in month
Specifies the day of the month. Each month has 28 to 31 days depending on the month and year.
hour Integer values 0–23 Specifies the hour of the day. The value 0 represents 12:00 A.M.
minute Integer values 0–59 Specifies the minute of the hour.
second Integer values 0–59 Specifies the number of elapsed seconds in the current minute.
YYYY, MM, DD, H, M, S
Chapter 14•Using Date Members:
– You can access the properties of your new date variable by using the “dot” (.) operator e.g.
•Now to manipulate the date variable “delivery” we call methods associated with the variable.•To assign the current date and time
• To assign current date, you don’t need “new date()” because the date.now property returns a date value
• GroupBox Control: Visually groups related controls by drawing a labeled box around them
• DateTimePicker control allows users to enter date and time information.
Chapter 14 - Pseudocode• When the form loads:
Set range of possible drop-off times to any time in the current dayDetermine the shipments delivery timeDisplay the shipment’s delivery time
• When the user changes the drop-off time:Determine the shipments delivery timeDisplay the shipments delivery time
• After one second has elapsed:Update the current time displayed
• When the displaydeliverytime procedure gets called:Determine the time the shipment flight departsAdd three hours to determine the delivery time (time zone + flight time)Display the delivery time
• When the DepartureTime procedure gets called:Select correct case based on the hour the shipment was dropped offCase where drop-off hours is between the value 0 and 10
Delivery set to depart on noon flight of current dayCase where the drop off hour is 23
Delivery set to depart on noon flight of next dayCase where none of the preceding cases match
Delivery set to depart on midnight flight of current day
Chapter 14• Insert the group box• Insert the label and name it appropriately• Insert the DateTimePicker. Change
Format from Long to Custom and then change the custom format to hh:mm tt
• Select the dateTimePicker ShowUpDown property to true.
• Add a timer control. A timer control generates a tick at regular intervals that further executes an event handler
Chapter 14
• Set the timer control to 1000 mS. Try with 10,000 to notice the difference. Set enabled to true and rename to clockTimer
• Now unlike previous applications, event for this application occurs during the form load
• Store the current date and time in the date variable currentTime– Dim currentTime as Date = Date.Now
Chapter 14• Set the drop off hours. You want to set minimum
and maximum for dropoff times.• dropOffDateTimePicker.MinDate = New Date
• Now since DepartureTime is returning a value, it will be programmed as a function
• Function DepartureTime() As DateDim currentDate As Date = Date.Now
Dim departTime As Date
‘Determine which flight the shipment takes
Sub DisplayDeliveryTime()
'Print initial delivery time Dim delivery As Date = DepartureTime()
'Add 3 hours to departure time and display results delivery = delivery.AddHours(3) lasVegasTimeLabel.Text = delivery.ToLongDateString & " at" & delivery.ToShortTimeString End Sub
Function departuretime() As Date Dim currentdate As Date = Date.Now Dim departtime As Date
Select Case dropOffDateTimePicker.Value.Hour
Case 0 To 10 departtime = New Date(currentdate.Year, currentdate.Month, currentdate.Day, 12, 0, 0) Case 23 currentdate = currentdate.AddDays(1) departtime = New Date(currentdate.Year, currentdate.Month, currentdate.Day, 12, 0, 0) Case Else currentdate = currentdate.AddDays(1) departtime = New Date(currentdate.Year, currentdate.Month, currentdate.Day, 0, 0, 0)
End Select Return departtime
End Function
Add timer event
• Double click the timer– currentTimeLabel.Text =
String.Format("{0:hh:mm:ss tt}", Date.Now)
Chapter 15
• Create variables that can be used throughout the form
• Pass argument by reference i.e. Use ByRef (instead of ByVal)
• Remove data type errors by using option strict
• Change a value from one data type to another using methods in class convert.
Problem
• An organization is collecting donations. A portion of each donation is used to cover the operating expenses of the organization; the rest of the donation goes to the charity. Create an application that allows the organization to keep track of the total amount of money raised. The application should deduct 17% of each donation for operating costs; the remaining 83% is given to the charity. The application should display the amount of each donation after the 17% operating expenses are deducted; it also should display the total amount raised for the charity (that is, the total amount donated less all operating costs) for all donations up to that point.
Problem
• If we follow the methodology we have learned so far, the solution is simple. Create a button click event and add the following code:
• But lets do it differently so that we can learn pass by reference.
Key points
• We need a variable which can store the running value of donations. So we declare an instance variable – a variable that is declared inside a class but outside of all procedure definitions of that class.
• All procedures in the class FundRaiserForm will have access to this variable and will be able to modify its value.
Example of variable types
Public class FundRaiserForm
Dim totalRaised As Decimal ‘Module Scope
Private Sub calculateTotal (ByVal amount As Decimal)
Dim expenses as Decimal ‘Procedure Scope
For expenses =1 to 10 step 5
Dim totalExpenses as Decimal ‘Block Scope
Next
End Class
• totalRaised can be accessed by anyone in the class
• expenses can only be accessed from within calculateTotal
• totalExpenses can only be accessed within the For-Next Statement
Scope of variables
• Module scope – Variables valid for the entire module of class.
• Procedure scope – Variables valid inside the procedure and cannot be accessed from outside.
• Block Scope – Variables valid inside the block and ends at the end of the block
• The Procedure & Block scope variables are called local variables.
Chapter 15 Application
• So After Public Class initialize the variableDim totalRaised As Decimal = 0 ‘Module Variable
• Create calculateDonation functionFunction CalculateDonation(ByVal donatedAmount As
Decimal) As DecimalConst COSTS As Double = 0.17Dim netDonation AS DecimalnetDonation= convert.ToDecimal(donatedAmount – (donatedAmount*Cost)Return netDonation
End Function
App development (Cont.)
• Now Create the button click event handler– Create local variables for the button
Dim donation as Decimal ‘ amount donated ‘Procedure Variable
• Pass-by-value (KeyWord ByVal): Indicates that a variable has been passed by value. Application makes a copy of the variable and changes made to this variable does not affect the original variable.
• Pass-by-reference (ByRef): Indicated that address of memory location of original variable is passed and the called procedure can modify the value of the original variable.
Pass-by-Reference
• ReplaceafterCosts = CalculateDonation(donation)
byCalculateDonation(donation, afterCosts)
• Donation will be passed ByVal and afterCosts will be passed ByRef
• Replace the function CalculateDonation by following sub procedureSub CalculateDonation (ByVal donatedAmount As
Decimal, ByRef netDonation As Decimal)Const Costs As Double = 0.17netDonation=donatedAmount – (donatedAmount*Cost)End Sub
Explanation
• Since netDonation is a pointer to the actual memory location where afterCosts is stored, any changes to netDonation is written on to afterCosts.
• This is tricky and can produce logical errors. Thus it is only used by experienced programmers.
Option Strict
• If I say something costs 50, how will you interpret it? Dollars, yen, euros, pesos, rupees). It makes a difference, right!!!
• If it’s a different currency, you will have to convert it in the currency you have.
• VB does some conversions e.g. integer to decimal without coding. This is implicit conversion.
Data Type Conversions
Data Type Can be implicitly converted to these (larger) types
Boolean Object
Byte Short, Integer, Long, Decimal, Single, Double or Object
Char String or Object
Date Object
Decimal Single, Double or Object
Double Object
Integer Long, Decimal, Single, Double or Object
Long Decimal, Single, Double or Object
Object none
Short Integer, Long, Decimal, Single, Double or Object
Single Double or Object
String Object
LARGER- means can store more data than the type in the left e.g. integer can store values in the range of ± 2.1billion and a long can store in the range of ± 9x1018
This type of conversion is called implicit widening conversion and no data loss happens
Data Type Conversion
• However if we do the reverse, i.e. assign larger type to smaller type, it will create an error
Dim value1 as Double=4.6Dim value2 as Integer = value1
• This will result in 5 being assigned to value2. This is called implicit narrowing conversions
• VB provides a feature called, “Option Strict” which generates a syntax error incase of implicit narrowing conversions.
• Right click project in solutions explorer. Then under compile window set it to on. Or add ‘option strict off’ before the form class.
Option Strict
• Now since implicit conversion is not happening, there are explicit ways to convert data.
• These can be accessed by ‘convert.’
Convert To Use Convert Method Sample Statement
Integer ToInt32 value = Convert.ToInt32( _ Val(inputTextBox.Text))
Decimal ToDecimal value = Convert.ToDecimal( _ Pmt(monthlyInterest, _ months,-loanAmount))
• Index can be 0, positive integer, or an integer expression (e.g. value1+value2)
• So if value1=2 and value2=4 then daysOfWeek(value1+value2)=Sunday
• So A(12) will have 13 elements starting from A(0) to A(12)
• You can perform operations on the array elements e.g. Y=A(0)+A(1)
Index
Arrays
• Arrays need to be declared and initializedDim netUnitsSold As Integer( )
netUnitsSold = New Integer(0 To 12) { }
This tells that its an array
Keyword: Allocates memory
Array Bounds (n-1)
Initializer List: If empty then array initialized by default values e.g. 0 for numeric, false for boolean, and nothing for references
Other ways to declare an array
• Dim salesPerDay As Integer()
• SalesPerDay = New Integer(){2,4,6,8}– Notice array of size 4 (0-3) is automatically
created based on number of elements
• Dim temperature As Double() = New Double(0 to 3) { 23, 24, 25, 45}
Application Total of array• Dim array As Integer()• array = New Integer(9) {} 'array = New Integer(0 To 9) {}• Dim populate As Integer = 0• For populate = 0 To array.GetUpperBound(0) Step 1• array(populate) = populate + 1• Next
• 'Dim array As Integer() = New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}• Dim total As Integer = 0• Dim index As Integer = 0
• 'For index = 0 To 9 Step 1• 'total += array(index)• 'Next
• 'For index = 0 To (array.Length - 1) Step 1• 'total += array(index)• 'Next
• For index = array.GetLowerBound(0) To array.GetUpperBound(0) Step 1• ' array.GetUpperBound(0) 0 because it suggests a one dimensional array.• total += array(index)• Next
A geography teacher would like to quiz students on their knowledge of the flags of various countries. The teacher has asked you to write an application that displays a flag and allows the student to select the corresponding country from a list. The application should inform the user of whether the answer is correct and display the next flag. The application should display five flags randomly chosen from the flags of Australia, Brazil, China, Italy, Russia, South Africa, Spain and the United States. When the application is run, a given flag should be displayed only once.
Pseudocode• On form load
– Sort the country names alphabetically
– Place names in the combo box– Select flags randomly– Display the flag
• When user clicks the Submit Button:– Retrieve country name from
combo box– If selected value matches correct
value • Display correct
– Else Display incorrect– If five images have been
displayed• Append Done to the label text• Disapble buttons and combo box
– Else Disable submit button– Enable Next button
• When user clicks the next button– Randomly choose the next flag
that has not been previously displayed
– Display the flag– Clear the labels text– Set combobox to display its first
item– Update the number of flags
shown– Enable submit button– Disable next flag button
App development
• Step 1 Create an array below class declaration'String Array to store countries Dim options As String() = New String() {"Russia",
'Boolean array to track displayed flags Dim used As Boolean() = New Boolean(0 To
options.GetUpperBound(0)) {}• GetUpperBound returns the index of the last
element in the array (7 in this case) so that “used” array can mirror “options” array
• Options.length will return 8
App development
• Initialize the counter variablesDim count As Integer = 1 'number of flags shown
Dim country As String 'current flag's country
• Add comboBox to the form (combines textBox and listbox)– Rename it to optionsComboBox– Set MaxDropDownItems=4
• ComboBox should be populated when the form loads… so create a form load event
Removing White Spaces• At form load
– optionsComboBox.DataSource = options
• Create function procedure to build the flag-image file’s path name
• The flags are located in the \FlagQuiz\bin\Debug\images folder … Now add these lines
Function BuildPathName() As String
Dim output As String = country
Dim space As Integer = output.IndexOf(" ")
If space > 0 Then
output = output.Remove(space, 1)
End If
Removing White Spaces
• Remove white spaces: Countries like South Africa and United States have space between names which need to be removed to match the file name
• String method IndexOf(“ “) assigns to space the index where space (“ “) character exists e.g. IndexOf(“S”) for united states will return 7 (U is 0 and S is 7
• If no space exists, then indexOff returns -1
• If space if found then remove method removes the space
• So now United States becomes UnitedStates
Ensuring all characters are lower case
output = output.ToLower() ‘Converts string to lower case
output &= ".png“ ‘ Appends .png to country name
output = output.Insert(0, System.Environment.CurrentDirectory & "\images\") ‘At location 0 of the string insert path
Return output
Ensure that same random flag does not get displayed twice
• Create another function:Function GetUniqueRandomNumber() As Integer Dim randomObject As Random = New Random Dim randomNumber As Integer Do randomNumber = randomObject.Next(0, used.Length) ‘
Generates random numbers between two numbers Loop Until used(randomNumber) = False used(randomNumber) = True ‘ Mark index as used Return randomNumber End Function
• So this functions returns an unused random number from a pool of numbers described by indices of the “used” array.
Display Flag
• Now you have full path of the flag• You also have a random number for the flag.• Now get the country details using the random
number and from the country details get the flag imageSub displayFlag() Dim randomNumber As Integer =
GetUniqueRandomNumber() country = options(randomNumber) Dim path As String = BuildPathName() flagPicture.Image = Image.FromFile(path) End Sub
Displaying first flag
• In the form load, after populating the combo box, call the sub procedure
displayFlag( )
• Now create the event handler for the submit button– You know the name of the flag (user input)
and you know the country (Stored in country) so this should be easy
Event Handler• Private Sub submitButton_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles submitButton.Click Dim response As String = Convert.ToString(optionsComboBox.SelectedValue) If response = country Then feedbackLabel.Text = "Correct!" Else feedbackLabel.Text = "Sorry, incorrect!" End If If count >= 5 Then feedbackLabel.Text &= " Done" nextButton.Enabled = False submitButton.Enabled = False optionsComboBox.Enabled = False Else submitButton.Enabled = False nextButton.Enabled = True End If End Sub
Adding the next button event
displayFlag()
feedbackLabel.Text = ""
optionsComboBox.SelectedIndex = 0
count += 1
submitButton.Enabled = True
nextButton.Enabled = False
Sorting Arrays
• If the country names were sorted, the users can find the names much faster.
• Immediately after form loads add array.sort(options)
• Try adding this line after optionsComboBox.DataSource=options and see the difference.