Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

50
Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions

Transcript of Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

Page 1: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

Microsoft Visual Basic: Reloaded

Chapter SixRepeating Program Instructions

Page 2: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

■ 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

Overview

Page 3: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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)

Page 4: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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

Page 5: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

Do While...Loop Repetition Statement

■ Using a Do While...Loop statement, this codefinds the first power of 3 greater than 50.

Dim product As Integer = 3Do While product <= 50

product *= 3Loop

■ The condition in the Do While...Loopstatement, product <= 50, is referred to as theloop-continuation condition.

■ When the loop-continuation condition becomes false, the Do While...Loop statement finishes executing.

Page 6: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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 loop-termination condition remains False.

This is known as a loop-termination condition.

Page 7: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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 = 3Do Until product > 50

product *= 3Loop

■ 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.

Page 8: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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.

Page 9: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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 += 1Loop While counter <= 3

Page 10: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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 loop-termination 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.

Page 11: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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 += 1Loop Until counter > 3

Page 12: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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.

Page 13: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

Car Payment Calculator Application

Results displayed in tabular format

ListBox control

Page 14: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

Designing the Car PaymentCalculator Application

When the user clicks the Calculate ButtonInitialize loan length to two yearsClear the ListBox of any previous calculation

resultsAdd a header to the ListBox

Get down payment from a TextBoxGet sticker price from a TextBoxGet annual interest rate from a TextBox

Calculate loan amount (sticker price – down payment)

Calculate monthly interest rate (annual interest rate / 12)

Page 15: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

Designing the Car PaymentCalculator 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 ListBoxIncrement loan length in years by one year

Page 16: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

■ 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

Clearing and Changing a ListBox’s Contents

Page 17: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

Car Payment Calculator Application

ListBox header

Page 18: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

Concatenate Strings

■ The ampersand symbol (&) is called the string-concatenation operator. This operator combines its two operands into one string value.

■ The constant ControlChars.Tab inserts a tab character into the string.

Page 19: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

1 Public Class CarPaymentCalculatorForm

2 ' handles Calculate Button's Click event

3 Private Sub calculateButton_Click(ByVal sender As System.Object, _

4 ByVal e As System.EventArgs) Handles calculateButton.Click

5

6 Dim years As Integer = 2 ' repetition counter

7 Dim months As Integer = 0 ' payment period

8 Dim price As Decimal = 0 ' car price

9 Dim downPayment As Decimal = 0 ' down payment

10 Dim interest As Double = 0 ' interest rate

11 Dim monthlyPayment As Decimal = 0 ' monthly payment

12 Dim loanAmount As Decimal = 0 ' cost after down payment

13 Dim monthlyInterest As Double = 0 ' monthly interest rate

14

15 ' remove text displayed in ListBox

16 paymentsListBox.Items.Clear()

Clear the ListBox

Page 20: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

17

18 ' add header to ListBox

19 paymentsListBox.Items.Add("Months" & ControlChars.Tab & _

20 ControlChars.Tab & "Monthly Payments")

21

22 ' retrieve user input and assign values

23 ' to their respective variables

24 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 loanAmount = price - downPayment

30 monthlyInterest = interest / 12

31

Add a header to the ListBox

Page 21: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

32 ' calculate payments for two, three, four and five year loans

33 Do While years <= 5

34 ' calculate payment period

35 months = 12 * years

36

37 ' calculate monthly payment using Pmt

38 monthlyPayment = _

39 Pmt(monthlyInterest, months, -loanAmount)

40

41 ' display payment value

42 paymentsListBox.Items.Add(months & ControlChars.Tab & _

43 ControlChars.Tab & String.Format("{0:C}", _

44 monthlyPayment))

45

46 years += 1 ' increment counter

47 Loop

48 End Sub ' calculateButton_Click

49 End Class ' CarPaymentCalculatorForm

Do While...Loop repeats its body while years is less than or equal to 5

Page 22: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

Calculating the Monthly Payment Amounts witha 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.

Page 23: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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

Page 24: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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

Page 25: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

Figure 6-29: Item selected in the animalListBox

The SelectedItem and SelectedIndex Properties

Page 26: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

Figure 6-30: How to use the SelectedItem and SelectedIndex properties

Page 27: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

Figure 6-31: How to select the default list box item

The SelectedItem and SelectedIndex Properties

Page 28: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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 forone quiz.

Page 29: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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).

Figure 10.3 | Class Average application after 10 grades have been input.

Disabled Add Grade Button

Ten quiz grades entered

Page 30: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

Class Average Application

■ Click the Average Button to calculate theaverage of the 10 quizzes (Fig. 10.4).

Figure 10.4 | Displaying the class average.

Label displaying average

Click to calculate class average

Page 31: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

Designing the Class Average Application

When the user clicks the Add Grade ButtonIf an average has already been calculated for a set of grades

Clear the output Label and the ListBoxRetrieve grade entered by user in the Enter grade:TextBoxDisplay the grade in the ListBoxClear the Enter grade: TextBoxTransfer focus to the Enter grade: TextBox

If the user has entered 10 gradesDisable the Add Grade ButtonTransfer focus to the Average Button

Page 32: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

Designing the Class Average Application

When the user clicks the Average ButtonSet total to zeroSet grade counter to zeroDo

Read the next grade in the ListBoxAdd the grade to the totalAdd one to the grade counter

Loop While the grade counter is less than 10

Calculate the class average by dividing the total by 10Display the class averageEnable the Add Grade ButtonTransfer focus to the Enter grade: TextBox

Page 33: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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.

Page 34: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

■ 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 andclearing the Enter grade: TextBox.

Adding Entered Grades to ListBox

Page 35: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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.

Page 36: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

■ 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.

Disabling a Button

Page 37: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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.

Page 38: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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.

Page 39: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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.

Page 40: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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

Page 41: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

17 ' prohibit users from entering more than 10 grades

18 If gradesListBox.Items.Count >= 10 Then

19 addButton.Enabled = False ' disable Add Grade Button

20 averageButton.Focus() ' transfer focus to Average Button

21 End If

22 End Sub ' addButton_Click

23

24 ' handles Average Button’s Click event

25 Private Sub averageButton_Click(ByVal sender As System.Object, _

26 ByVal e As System.EventArgs) Handles averageButton.Click

27

28 ' initialization phase

29 Dim total As Integer = 0

30 Dim gradeCounter As Integer = 0

31 Dim grade As Integer = 0

32 Dim average As Double = 0

33

Page 42: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

34 ' sum grades in ListBox

35 Do

36 ' read grade from ListBox

37 grade = gradesListBox.Items(gradeCounter)

38 total += grade ' add grade to total

39 gradeCounter += 1 ' increment counter

40 Loop Until gradeCounter >= 10

41

42 average = total / 10 ' calculate average

43 averageResultLabel.Text = String.Format(“{0:F}”, average)

44 addButton.Enabled = True ' enable Add Grade Button

45 gradeTextBox.Focus() ' reset focus to Enter grade: TextBox

46 End Sub ' averageButton_Click

47 End Class ' ClassAverageForm

Page 43: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

Adding Items to a List Box (cont'd.)

43

Figure 6-19: How to use the Items collection’s Add method

Page 44: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

The InputBox Function

■ InputBox function: displays a predefined dialog box that allows the user to enter dataContains 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

Page 45: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

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

Page 46: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

Figure 6-16: How to use the InputBox function

Page 47: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

The InputBox Function

Figure 6-16: How to use the InputBox function (cont'd.)

Page 48: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

The Color Viewer Application

■ Enabled property: used to enable or disable a controlWhen 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 executionArgument is specified in milliseconds

Page 49: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

The Color Viewer Application

Figure 6-38: MainForm in the Color Viewer application

Page 50: Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.

2009 Pearson Education, Inc. All rights reserved.

The Color Viewer Application

Figure 6-39: View Colors button’s Click event procedure