VB Chapter 6
Download
Report
Transcript VB Chapter 6
Microsoft Visual Basic:
Reloaded
Chapter Six
Repeating Program Instructions
Overview
■ Repetition Structure
■ Do While...Loop, Do Until...Loop, Do
Loop...While, and Do Loop...Until
repetition statements
■ String Concatenation
■ Using ListBoxes
■ Display a dialog box using the InputBox
function
■ Enable and disable a control
■ Refresh the screen
■ Delay program execution
2009 Pearson Education, Inc. All rights reserved.
The Repetition Structure
■ Repetition structure (or loop): a structure that
repeatedly processes one or more program
instructions until a condition is met
■ Looping condition: the requirement for repeating
the instructions
■ Loop exit condition: the requirement for not
repeating the instructions
■ Pretest loop: condition is evaluated before the
instructions within the loop are processed (0 or
more times)
■ Posttest loop: condition is evaluated after the
instructions within the loop are processed (at least
once)
2009 Pearson Education, Inc. All rights reserved.
Do While...Loop Repetition Statement
■ A repetition statement can repeat actions,
depending on the value of a condition.
■ If you go to the grocery store with a list of items to
purchase, you go through the list until you have
each item:
Do while there are more items on my shopping list
Put next item in cart
Cross it off my list
2009 Pearson Education, Inc. All rights reserved.
Do While...Loop Repetition Statement
■ Using a Do While...Loop statement, this code
finds the first power of 3 greater than 50.
Dim product As Integer = 3
Do While product <= 50
product *= 3
Loop
■ The condition in the Do While...Loop
statement, product <= 50, is referred to as the
loop-continuation condition.
■ When the loop-continuation condition becomes
false, the Do While...Loop statement finishes
executing.
2009 Pearson Education, Inc. All rights reserved.
Do Until...Loop Repetition Statement
■ These statements describe the repetitive actions that
occur during a shopping trip:
Do until there are no more items on my shopping list
Put next item in cart
Cross it off my list
■ Statements in the body of a Do Until...Loop are
executed repeatedly for as long as the looptermination condition remains False.
This is known as a loop-termination condition.
2009 Pearson Education, Inc. All rights reserved.
Do Until...Loop Repetition Statement
■ Using a Do Until...Loop, this code finds the first power of
3 larger than 50:
Dim product As Integer = 3
Do Until product > 50
product *= 3
Loop
■ Failure to provide the body of a Do Until...Loop
statement with an action that eventually causes the
condition in the Do Until...Loop to become true
creates an infinite loop.
2009 Pearson Education, Inc. All rights reserved.
Do...Loop While Repetition Statement
■ Do...Loop While repetition statement is similar to
the Do...While Loop statement, except that the
loop-termination condition is tested after the loop body
is performed.
■ Consider the example of packing a suitcase:
You place an item in the suitcase, then determine whether the
suitcase is full.
As long as the suitcase is not full, you continue to put items in
the suitcase.
2009 Pearson Education, Inc. All rights reserved.
Do...Loop While Repetition Statement
■ The following application segment displays the
numbers 1 through 3 in a ListBox:
Dim counter As Integer = 1
Do
displayListBox.Items.Add(counter)
counter += 1
Loop While counter <= 3
2009 Pearson Education, Inc. All rights reserved.
Do...Loop Until Repetition Statement
■ The Do...Loop Until statement is similar to the
Do...Until Loop statement, except that the looptermination condition is tested after the loop body is
performed.
■ Imagine that you place an item in the suitcase, then
determine whether the suitcase is full. As long as the
condition “the suitcase is full” is False, you continue
to put items into the suitcase.
2009 Pearson Education, Inc. All rights reserved.
Do...Loop Until Repetition Statement
■ This application segment displays the numbers 1
through 3 in a ListBox:
Dim counter As Integer = 1
Do
displayListBox.Items.Add(counter)
counter += 1
Loop Until counter > 3
2009 Pearson Education, Inc. All rights reserved.
Car Payment Calculator Application
■Typically, banks offer car loans for periods ranging from two to five
years. Borrowers repay the loans in monthly installments. The
amount of each monthly payment is based on the length of the loan,
the amount borrowed and the interest rate. Create an application that
allows the customer to enter the price of a car, the down-payment
amount and the annual interest rate of the loan. The application
should display the loan’s duration in months and the monthly
payments for two-, three-, four- and five-year loans. The variety of
options allows the user to easily compare repayment plans and
choose the most appropriate.
2009 Pearson Education, Inc. All rights reserved.
Car Payment Calculator Application
Results
displayed in
tabular
format
ListBox
control
2009 Pearson Education, Inc. All rights reserved.
Designing the Car Payment
Calculator Application
When the user clicks the Calculate Button
Initialize loan length to two years
Clear the ListBox of any previous calculation results
Add a header to the ListBox
Get down payment from a TextBox
Get sticker price from a TextBox
Get annual interest rate from a TextBox
Calculate loan amount (sticker price – down payment)
Calculate monthly interest rate (annual interest rate / 12)
2009 Pearson Education, Inc. All rights reserved.
Designing the Car Payment
Calculator Application
Do while loan length is less than or equal to five years
Convert the loan length in years to number of months
Calculate monthly payment based on loan amount,
monthly interest rate and loan length in months
Insert result into ListBox
Increment loan length in years by one year
2009 Pearson Education, Inc. All rights reserved.
Clearing and Changing a ListBox’s Contents
■ The ListBox is initially cleared and then displays the
number of monthly payments and the amount per payment.
■ To clarify what information is being displayed, a line of
text—called a header—is added to the ListBox by the
Method Add
2009 Pearson Education, Inc. All rights reserved.
Car Payment Calculator Application
ListBox
header
2009 Pearson Education, Inc. All rights reserved.
Concatenate Strings
■ The ampersand symbol (&) is called the stringconcatenation operator. This operator combines
its two operands into one string value.
■ The constant ControlChars.Tab inserts a tab
character into the string.
2009 Pearson Education, Inc. All rights reserved.
1
2
3
4
Public Class CarPaymentCalculatorForm
' handles Calculate Button's Click event
Private Sub calculateButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles calculateButton.Click
5
6
Dim years As Integer = 2 ' repetition counter
7
8
Dim months As Integer = 0 ' payment period
Dim price As Decimal = 0 ' car price
9
10
11
Dim downPayment As Decimal = 0 ' down payment
Dim interest As Double = 0 ' interest rate
Dim monthlyPayment As Decimal = 0 ' monthly payment
12
13
14
Dim loanAmount As Decimal = 0 ' cost after down payment
Dim monthlyInterest As Double = 0 ' monthly interest rate
15
16
' remove text displayed in ListBox
paymentsListBox.Items.Clear()
Clear the ListBox
2009 Pearson Education, Inc. All rights reserved.
17
18
19
20
' add header to ListBox
paymentsListBox.Items.Add("Months" & ControlChars.Tab & _
ControlChars.Tab & "Monthly Payments")
21
22
' retrieve user input and assign values
23
24
' to their respective variables
downPayment = Val(downPaymentTextBox.Text)
25
price = Val(priceTextBox.Text)
26
interest = Val(interestTextBox.Text) / 100
27
28
' determine amount borrowed and monthly interest rate
29
30
loanAmount = price - downPayment
monthlyInterest = interest / 12
Add a header to the ListBox
31
2009 Pearson Education, Inc. All rights reserved.
32
' calculate payments for two, three, four and five year loans
33
Do While years <= 5
Do While...Loop repeats its
body while years is less than or
equal to 5
34
' calculate payment period
35
36
months = 12 * years
37
' calculate monthly payment using Pmt
38
monthlyPayment = _
39
40
Pmt(monthlyInterest, months, -loanAmount)
41
' display payment value
42
paymentsListBox.Items.Add(months & ControlChars.Tab & _
43
44
ControlChars.Tab & String.Format("{0:C}", _
monthlyPayment))
45
46
47
48
years += 1 ' increment counter
Loop
End Sub ' calculateButton_Click
49 End Class ' CarPaymentCalculatorForm
2009 Pearson Education, Inc. All rights reserved.
Calculating the Monthly Payment Amounts with
a Do While...Loop Repetition Statement
■ This loop is an example of counter-controlled
repetition.
This uses a counter (years) to control the number of times
that a set of statements executes.
Counter-controlled repetition also is called definite repetition,
because the number of repetitions is known before the
repetition statement begins.
2009 Pearson Education, Inc. All rights reserved.
Accessing Items in a List Box
Figure 6-27: How to access an item in a list box
2009 Pearson Education, Inc. All rights reserved.
The SelectedItem and SelectedIndex
Properties
■ SelectedItem property:
Contains the value of the selected item in the list
If nothing is selected, it contains the empty string
■ SelectedIndex property:
Contains the index of the selected item in the list
If nothing is selected, it contains the value -1
■ Default list box item: the item that is selected
by default when the interface first appears
2009 Pearson Education, Inc. All rights reserved.
The SelectedItem and SelectedIndex
Properties
Figure 6-29: Item selected in the animalListBox
2009 Pearson Education, Inc. All rights reserved.
Figure 6-30: How to use
the SelectedItem and
SelectedIndex
properties
2009 Pearson Education, Inc. All rights reserved.
The SelectedItem and SelectedIndex
Properties
Figure 6-31: How to select the default list box item
2009 Pearson Education, Inc. All rights reserved.
Class Average Application
■A teacher regularly gives quizzes to a class of 10
students. The grades on these quizzes are integers in
the range from 0 to 100 (0 and 100 are both valid
grades). The teacher would like you to develop an
application that computes the class average for
one quiz.
2009 Pearson Education, Inc. All rights reserved.
Class Average Application
■ Enter nine other grades between 0 and 100.
■ Note that the Add Grade Button is disabled once
you have entered 10 grades (Fig. 10.3).
Disabled Add Grade Button
Ten quiz grades entered
Figure 10.3 | Class Average application after 10 grades have been input.
2009 Pearson Education, Inc. All rights reserved.
Class Average Application
■ Click the Average Button to calculate the
average of the 10 quizzes (Fig. 10.4).
Label displaying average
Click to calculate class average
Figure 10.4 | Displaying the class average.
2009 Pearson Education, Inc. All rights reserved.
Designing the Class Average Application
When the user clicks the Add Grade Button
If an average has already been calculated for a set of grades
Clear the output Label and the ListBox
Retrieve grade entered by user in the Enter grade:TextBox
Display the grade in the ListBox
Clear the Enter grade: TextBox
Transfer focus to the Enter grade: TextBox
If the user has entered 10 grades
Disable the Add Grade Button
Transfer focus to the Average Button
2009 Pearson Education, Inc. All rights reserved.
Designing the Class Average Application
When the user clicks the Average Button
Set total to zero
Set grade counter to zero
Do
Read the next grade in the ListBox
Add the grade to the total
Add one to the grade counter
Loop While the grade counter is less than 10
Calculate the class average by dividing the total by 10
Display the class average
Enable the Add Grade Button
Transfer focus to the Enter grade: TextBox
2009 Pearson Education, Inc. All rights reserved.
Checking if Average Has Been Calculated
■ This code tests whether averageResultLabel
displays any text by comparing the Text property’s
value to the empty string.
Figure 10.10 | Clearing the output Label and ListBox after a calculation.
2009 Pearson Education, Inc. All rights reserved.
Adding Entered Grades to ListBox
■ Line 13 (Fig. 10.11) Adds the grade entered in
gradeTextBox to gradesListBox’s Items property.
The grade is displayed in the ListBox.
■ Method Clear deletes the grade from the TextBox so
that the next grade can be entered.
Figure 10.11 | Adding the grade input to the ListBox and
clearing the Enter grade: TextBox.
2009 Pearson Education, Inc. All rights reserved.
Transferring the Focus to a Control
■ Calling gradeTextBox’s Focus method places the
cursor in the TextBox for the next grade input
(Fig. 10.12).
■ This process is called transferring the focus.
Figure 10.12 | Transferring the focus to the TextBox control.
2009 Pearson Education, Inc. All rights reserved.
Disabling a Button
■ Your application should accept exactly 10 grades.
– Items’s Count property returns the number of items
displayed in the Grade list: ListBox.
– If 10 grades have been entered, addButton’s Enabled
property is set to False (Fig. 10.13).
Figure 10.13 | Application accepts only 10 grades.
2009 Pearson Education, Inc. All rights reserved.
Calculating the Class Average
■ Use the Integer total (Figure 10.14 ) to calculate
the sum of the 10 grades.
■ The result of the averaging calculation can be a
floating-point value; therefore, you declare a Double
variable to store the class average.
Figure 10.14 | Initialization phase of class-average calculation.
2009 Pearson Education, Inc. All rights reserved.
Calculating the Class Average (Cont.)
■ The Do...Loop Until statement should iterate
until the value of gradeCounter is greater than
or equal to 10.
■ The items in a ListBox are accessed by their
position number, starting from position number 0.
Figure 10.15 | Do...Loop Until summing grades.
2009 Pearson Education, Inc. All rights reserved.
Calculating the Class Average (Cont.)
■ After the average is displayed, the application resets,
and another list of grades can be entered.
Figure 10.16 | Displaying the result of the average calculation.
2009 Pearson Education, Inc. All rights reserved.
1 Public Class ClassAverageForm
2
' handles Add Grade Button’s Click event
3
Private Sub addButton_Click(ByVal sender As System.Object, _
4
ByVal e As System.EventArgs) Handles addButton.Click
5
6
' clear previous grades and calculation result
7
If averageResultLabel.Text <> "" Then
8
averageResultLabel.Text = ""
9
gradesListBox.Items.Clear()
10
End If
11
12
' display grade in ListBox
13
gradesListBox.Items.Add(Val(inputTextBox.Text))
14
gradeTextBox.Clear() ' clear grade from TextBox
15
gradeTextBox.Focus() ' transfer focus to TextBox
16
2009 Pearson Education, Inc. All rights reserved.
17
' prohibit users from entering more than 10 grades
18
19
20
If gradesListBox.Items.Count >= 10 Then
addButton.Enabled = False ' disable Add Grade Button
averageButton.Focus() ' transfer focus to Average Button
21
22
End If
End Sub ' addButton_Click
23
24
25
' handles Average Button’s Click event
Private Sub averageButton_Click(ByVal sender As System.Object, _
26
27
ByVal e As System.EventArgs) Handles averageButton.Click
28
' initialization phase
29
30
Dim total As Integer = 0
Dim gradeCounter As Integer = 0
31
32
Dim grade As Integer = 0
Dim average As Double = 0
33
2009 Pearson Education, Inc. All rights reserved.
34
' sum grades in ListBox
35
Do
36
' read grade from ListBox
37
38
grade = gradesListBox.Items(gradeCounter)
total += grade ' add grade to total
39
gradeCounter += 1 ' increment counter
40
Loop Until gradeCounter >= 10
41
42
average = total / 10 ' calculate average
43
44
averageResultLabel.Text = String.Format(“{0:F}”, average)
addButton.Enabled = True ' enable Add Grade Button
45
46
gradeTextBox.Focus() ' reset focus to Enter grade: TextBox
End Sub ' averageButton_Click
47 End Class ' ClassAverageForm
2009 Pearson Education, Inc. All rights reserved.
Adding Items to a List Box (cont'd.)
Figure 6-19: How to use the Items collection’s Add method
43
2009 Pearson Education, Inc. All rights reserved.
The InputBox Function
■ InputBox function: displays a predefined dialog
box that allows the user to enter data
Contains a text message, an OK button, a Cancel button, and
an input area
■ InputBox function returns:
The user’s entry if the user clicks the OK button
An empty string if the user clicks the Cancel button or the
Close button on the title bar
2009 Pearson Education, Inc. All rights reserved.
The InputBox Function
• InputBox function arguments:
– prompt: the message to display inside the dialog box
– title: the text to display in the dialog box’s title bar
– defaultResponse: a prefilled value for the user input
2009 Pearson Education, Inc. All rights reserved.
Figure 6-16: How
to use the
InputBox
function
2009 Pearson Education, Inc. All rights reserved.
The InputBox Function
Figure 6-16: How to use the InputBox function (cont'd.)
2009 Pearson Education, Inc. All rights reserved.
The Color Viewer Application
■ Enabled property: used to enable or disable a
control
When False, the control appears dimmed (grayed out),
indicating it is not available for use
■ Refresh method: ensures that the computer
processes any previous lines of code that affect
the interface’s appearance
■ Sleep method: delays program execution
Argument is specified in milliseconds
2009 Pearson Education, Inc. All rights reserved.
The Color Viewer Application
Figure 6-38: MainForm in the Color Viewer application
2009 Pearson Education, Inc. All rights reserved.
The Color Viewer Application
Figure 6-39: View Colors button’s Click event procedure
2009 Pearson Education, Inc. All rights reserved.