Presentation is loading. Please wait.

Presentation is loading. Please wait.

Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Similar presentations


Presentation on theme: "Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved."— Presentation transcript:

1 Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

2

3

4  Chapter 4 began our introduction to the types of building blocks that are available for problem solving.  In this chapter, we demonstrate the For … Next, Select … Case, Do … Loop While and Do … Loop Until control statements.  We explore the essentials of counter-controlled repetition and demonstrate nested repetition statements.  We introduce the Exit program control statement for terminating a control statement immediately, and  we introduce the Continue program control statement for terminating the current iteration of a repetition statement.  Finally, we discuss the logical operators, which enable you to form more powerful conditional expressions in control statements.

5  Counter-controlled repetition requires: ◦ the name of a control variable (or loop counter) that is used to determine whether the loop continues to iterate ◦ the initial value of the control variable ◦ the increment (or decrement) by which the control variable is modified each time through the loop ◦ the condition that tests for the final value of the control variable (that is, whether looping should continue). © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

6  The For…Next repetition statement specifies counter-controlled repetition details in a single line of code.  In general, counter-controlled repetition should be implemented with For … Next.  Figure 5.1 illustrates the power of For … Next statement by displaying the even integers from 2 to 10.  The ForCounter_Load event handler is called when you execute the program.

7

8  When the For … Next statement (lines 10–13) is reached, the control variable counter is declared as an Integer and initialized to 2, thus addressing the first two elements of counter-controlled repetition—the control variable’s name and its initial value.  Next, the implied loop-continuation condition counter <= 10 is tested. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

9  The To keyword is required in the For … Next statement.  The optional Step keyword specifies the increment, that is, the amount that’s added to counter after each time the For … Next body is executed.  If Step and the value following it are omitted, the increment defaults to 1.  You typically omit the Step portion for increments of 1. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

10  The increment of a For … Next statement could be negative, in which case it’s called a decrement, and the loop actually counts downward.  If the loop-continuation condition is initially false (for example, if the initial value is greater than the final value and the increment is positive), the For … Next ’s body is not performed.  Instead, execution proceeds with the first statement after the For … Next.

11

12  First Iteration of the Loop ◦ In Fig. 5.1, the initial value of counter is 2, so the implied loop-continuation condition ( counter <= 10 ) is true, and the counter ’s value 2 is appended to outputLabel ’s Text property (line 12). ◦ The required Next keyword (line 13) marks the end of the For … Next repetition statement. ◦ When Next is reached, variable counter is incremented by the Step value ( 2 ), and the implied loop- continuation test is performed again.

13  Second and Subsequent Iterations of the Loop ◦ Now, the control variable is equal to 4. ◦ This value still does not exceed the final value, so the program performs the body statement again. ◦ This process continues until the counter value 10 has been displayed and the control variable counter is incremented to 12, causing the implied loop-continuation test to fail and the loop to terminate. ◦ The program continues by performing the first statement after the For … Next statement (line 14).

14

15  Figure 5.2 takes a closer look at the For … Next statement of Fig. 5.1.  The first line of the For … Next statement sometimes is called the For…Next header.  It specifies each of the items needed for counter- controlled repetition with a control variable.

16

17  The general form of the For … Next statement is For initialization To finalValue Step increment statement Next where the initialization expression initializes the loop’s control variable, finalValue determines whether the loop should continue executing and increment specifies the amount the control variable should be incremented (or decremented) each time through the loop.

18  In Fig. 5.1, the counter variable is declared and initialized in the For … Next header.  The counter variable may be declared before the For … Next statement.  For example, the code in Fig. 5.1 could have been written as Dim counter As Integer For counter = 2 To 10 Step 2 outputLabel.Text &= counter & " " Next  Although both forms are correct, declaring the control variable in the For … Next header is clearer and more concise. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

19  The difference between the two forms is that if the initialization expression in the For … Next statement header declares the control variable (as we’ve done in Fig. 5.1), the control variable can be used only in the body of the For … Next statement—it will be unknown outside the For … Next statement.  This restricted use of the control-variable name is known as the variable’s scope, which specifies where the variable can be used in a program.  If the control variable is declared before the For … Next control statement, it can be used from the point of declaration, inside the control statement’s body and after the control statement as well.

20  The starting value, ending value and increment portions of a For … Next statement can contain arithmetic expressions.  The expressions are evaluated once (when the For … Next statement begins executing) and used as the starting value, ending value and increment of the For … Next statement’s header.  For example, assume that x = 2 and y = 10.  The header For j As Integer = x To 4 * x * y Step y \ x is equivalent to the header For j As Integer = 2 To 80 Step 5

21 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

22  The activity diagram of the For … Next statement in Fig. 5.1 is shown in Fig. 5.3.  This activity diagram makes it clear that the initialization occurs only once and that incrementing occurs after each execution of the body statement. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

23  In each For … Next statement presented so far, we declared the control variable’s type in the For … Next statement’s header.  For any local variable that is initialized in its declaration, the variable’s type can be determined based on its initializer value—this is known as local type inference.  Recall that a local variable is any variable declared in the body of a method. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

24  For example, in the declaration Dim x = 7 the compiler infers that the variable x should be of type Integer, because the compiler assumes that whole- number values, like 7, are Integer values.  In the declaration Dim y = -123.45 the compiler infers that the variable y should be of type Double, because the compiler assumes that floating- point literals, like -123.45, are Double values. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

25

26  In the declaration Dim z = 987.65D the compiler infers that the variable z should be of type Decimal, because the value 987.65 is followed by the literal type character D, which indicates that the value is of type Decimal.  Some common literal type characters include C for Char ( "T"C ), F for Single ( 123.45F ), S for Short ( 123S ) and L for Long ( 123L ). © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

27  You can also use local type inference with control variables in the header of a For … Next statement.  For example, the For … Next header For counter As Integer = 1 To 10 can be written as For counter = 1 To 10  In this case, counter is of type Integer because it is initialized with an Integer literal ( 1 ). © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

28  The following examples demonstrate different ways of varying the control variable in a For … Next statement.  In each case, we write the appropriate For … Next header using local type inference. ◦ Vary the control variable from 1 to 100 in increments of 1. For i = 1 To 100 or For i = 1 To 100 Step 1 ◦ Vary the control variable from 100 to 1 in increments of -1 (decrements of 1 ). For i = 100 To 1 Step -1 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

29 ◦ Vary the control variable from 7 to 77 in increments of 7. For i = 7 To 77 Step 7 ◦ Vary the control variable from 20 to 2 in increments of -2 (decrements of 2 ). For i = 20 To 2 Step -2 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

30 ◦ Vary the control variable over the sequence of the following values: 2, 5, 8, 11, 14, 17, 20. For i = 2 To 20 Step 3 ◦ Vary the control variable over the sequence of the following values: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0. For i = 99 To 0 Step -11 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

31  Consider the following problem statement: ◦ A person invests $1000.00 in a savings account. Assuming that all the interest is left on deposit, calculate and print the amount of money in the account at the end of each year for up to 10 years. Allow the user to specify the principal amount, the interest rate and the number of years. To determine these amounts, use the following formula: a = p (1 + r) n ◦ where  p is the original amount invested (that is, the principal)  r is the annual interest rate (for example,.05 stands for 5%)  n is the number of years  a is the amount on deposit at the end of the nth year. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

32  This problem involves a loop that performs the indicated calculation for each year the money remains on deposit.  Figure 5.4 shows the GUI for this application.  We introduce the NumericUpDown control, which limits a user’s choices to a specific range of values—this helps to avoid data entry errors.  In this program, we use the control to allow the user to choose a number of years from 1 to 10.  The control’s Minimum property specifies the starting value in the range.  Its Maximum property specifies the ending value in the range. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

33  Its Value property specifies the current value displayed in the control.  You can also use this property programmatically to obtain the current value displayed.  The control provides up and down arrows that allow the user to scroll through the control’s range of values.  In this example, we use 1 as the minimum value, 10 as the maximum value and 1 as the initial value for this control.  The Increment property specifies by how much the current number in the NumericUpDown control changes when the user clicks the control’s up (for incrementing) or down (for decrementing) arrow. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

34  We use the Increment property’s default value, 1.  When the user changes the value in a NumericUpDown control, a Value-Changed event occurs.  If you double click the yearUpDown control in design mode, the IDE generates the event handler yearUpDown_ValueChanged to handle the Value-Changed event.  The Interest Calculator program is shown in Fig. 5.5. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

35

36

37

38

39  Decimal Variables ◦ Lines 9–10 in the calculateButton_Click event handler declare and initialize two Decimal variables. ◦ Type Decimal should be used for monetary calculations such as those required in the Interest Calculator application. ◦ Line 9 declares pricipal as type Decimal. ◦ Variable principal is initialized to the value in principalTextBox and rate (line 10) is initialized to the value in interestRateTextBox. ◦ Line 15 declares amount as a Decimal. ◦ This variable stores the amount on deposit at the end of each year. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

40  Using the Val Function to Convert String s to Numbers ◦ This application uses TextBox es to read numeric input. ◦ Unfortunately, we cannot prevent users from accidentally entering nonnumeric input, such as letters and special characters like $ and @ in the TextBox es. ◦ Lines 9–10 use the built-in Val function to prevent inputs like this from terminating the application. ◦ Previously, you’ve used the method Format, which is part of class String. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

41  When a method not part of a class, it’s called a function.  Function Val obtains a value from a String of characters, such as a TextBox ’s Text property.  The value returned is guaranteed to be a number.  We use Val because this application is not intended to perform arithmetic calculations with characters that are not numbers.  Val reads its argument one character at a time until it encounters a character that is not a number.  Once a nonnumeric character is read, Val returns the number it has read up to that point. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

42  Val ignores whitespace (for example, "33 5" will be converted to 335 ).  Val recognizes the decimal point as well as plus and minus signs that indicate whether a number is positive or negative (such as -123 ).  Val does not recognize such symbols as commas and dollar signs.  If Val receives an argument that cannot be converted to a number (for example, "b35", which begins with a nonnumeric character, or an empty string), it returns 0. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

43  Performing the Interest Calculations ◦ The For … Next statement (lines 18–22) varies the control variable yearCounter from 1 to yearUpDown.Value in increments of 1. ◦ Line 19 performs the calculation from the problem statement a = p (1 + r) n where a is the amount, p is the principal, r is the rate and n is the yearCounter. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

44  Formatting Currency Output ◦ Lines 20–21 display the amount on deposit at the end of each year in the resultsListBox. ◦ The text includes the current yearCounter value, a tab character ( vbTab ) to position to the second column and the result of the method call String.Format("{0:C}", amount). © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

45  The C (“currency”) format specifier indicates that its corresponding value ( amount ) should be displayed in monetary format—with a dollar sign to the left and commas in the proper locations.  For example, the value 1334.50, when formatted using the C format specifier, will appear as “ $1,334.50.” This may differ based on your locale throughout the world. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

46  Other commonly used format specifiers include: ◦ F for floating-point numbers—sets the number of decimal places to two (introduced in Section 4.10). ◦ N for numbers—separates every three digits with a comma and sets the number of decimal places to two. ◦ D for integers © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

47  A Warning About Function Val ◦ Although the value returned by Val is always a number, it’s not necessarily the value the user intended. ◦ For example, the user might enter the text $10.23, which Val evaluates to 0 without reporting an error. ◦ This causes the application to execute incorrectly. ◦ Visual Basic provides two ways to handle invalid input. ◦ One way is to use string-processing capabilities to examine input. We discuss these throughout this book. ◦ The other form of handling invalid input is called exception handling, where you write code to handle errors that may occur as the application executes (Chapter 7). © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

48  Consider the following problem statement: ◦ Write a program that displays in a TextBox a filled square consisting solely of one type of character, such as the asterisk (*). The side of the square and the character to be used to fill the square should be entered by the user. The length of the side should be in the range 1 to 20. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

49  Your program should draw the square as follows: ◦ Input the fill character and side length of the square. ◦ Ensure that the side is in the range 1 to 20 by using a NumericUpDown control to specify the exact range of allowed values. ◦ Use repetition to draw the square by displaying only one fill character at a time. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

50  After reading the problem statement, we make the following observations: ◦ The program must draw side rows, each containing side fill characters, where side is the value entered by the user. Counter-controlled repetition should be used. ◦ Four variables should be used—one that represents the length of the side of the square, one that represents (as a String ) the fill character to be used, one that represents the row in which the next symbol should appear and one that represents the column in which the next symbol should appear. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

51  GUI for the Square of Characters Application ◦ Figure 5.6 shows the GUI for this application. ◦ We use a NumericUpDown control to allow the user to specify a side length in the range 1 to 20. ◦ The output is displayed in a TextBox with its MultiLine property set to True and its Font property set to the fixed- width font Lucida Console. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

52

53  Evolving the Pseudocode ◦ Let’s proceed with top-down, stepwise refinement. ◦ We begin with a pseudocode representation of the top: Display a square of fill characters ◦ Our first refinement is Input the fill character Input the side of the square Display the square ◦ Here, too, even though we have a complete representation of the entire program, further refinement is necessary. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

54  Displaying the Square ◦ The pseudocode statement Display the square ◦ can be implemented by using one loop nested inside another. ◦ In this example, it is known in advance that there are side rows of side fill characters each, so counter-controlled repetition is appropriate. ◦ One loop controls the row in which each fill character is to be displayed. ◦ A nested loop displays each fill character (one at a time) for that row. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

55  The refinement of the preceding pseudocode statement is For row from 1 to the number of characters in a side For column from 1 to the number of characters in a side Display the fill character Move to the next line of output  The outer For statement initializes row to one to prepare to display the first row and loops while the implied condition row is less than or equal to the number of characters in a side is true—that is, for each row of the square.  Within this For statement, the nested For statement initializes column to one to prepare to display the first fill character of the current row. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

56  The nested (or inner) loop executes while the implied condition column is less than or equal to the number of characters in a side remains true.  Each iteration of the inner loop displays one fill character.  After each row of characters, we move to the next line in the TextBox to prepare to display the next row of the square.  At this point, the outer loop increments variable row by 1.  If the outer loop’s condition is still true, column is reset to 1, and the inner loop executes again, displaying another row of fill characters.  Then, the outer loop increments row by 1 again.  This process repeats until the value of row exceeds side, at which point the square of fill characters is complete. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

57  Completed Pseudocode ◦ The complete second refinement appears in Fig. 5.7. ◦ The pseudocode now is refined sufficiently for conversion to Visual Basic. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

58  Visual Basic Code for the Square of Characters Application ◦ We implement the pseudocode algorithm in the displaySquareButton_Click event handler (Fig. 5.8, lines 5–25). ◦ The nested For … Next statements (lines 15–24) display the square of characters. ◦ The outer loop specifies which row is being displayed and the inner loop (lines 18–21) displays the current row of characters. ◦ We follow each fill character by a space (line 20) to make the output look more like a square. ◦ Line 23 in the outer loop moves the cursor to the next line in the TextBox to begin the next line of output. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

59

60

61

62

63  Occasionally, an algorithm contains a series of decisions that test a variable or expression separately for each value that the variable or expression might assume.  The algorithm takes different actions based on those values.  The Select…Case multiple-selection statement handles such decision making.  Figure 5.9 enhances the Class Average application of Fig. 4.12 by using a Select … Case statement to determine whether each grade is the equivalent of an A, B, C, D or F and to increment the appropriate grade counter.  The program also displays a summary of the number of students who received each grade. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

64  An extra counter is used to display the number of students who received a perfect score of 100 on the exam.  The GUI uses the same controls as in Fig. 4.12, but we’ve made the classAverageLabel taller to display more output and resized the gradesListBox so that it extends to the bottom of the clearGradesButton. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

65  Instance Variables ◦ For the first time in this example, we declare a variable in the class, but outside all of the class’s event-handling methods. ◦ Such variables—called instance variables—are special because they can be used by all of the class’s methods. ◦ They also retain their values, so a value set by one method in the class can be used by another method. ◦ We do this so that we can increment the letter-grade counters declared in lines 6–11 in the submitGradeButton_Click event handler, then use those variables’ values to display a grade report in the calculateAverageButton_Click event handler. ◦ The variable perfectScoreCount (line 11) counts the number of students who received a perfect score of 100 on the exam. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

66

67

68

69

70

71

72  Method submitGradeButton_Click ◦ In this version of the program, we no longer check whether the user entered a grade before pressing the Submit Grade Button. ◦ Instead, we now use the Val function to convert the user’s input into a number. ◦ If the TextBox is empty, 0 will be added to the ListBox. ◦ Lines 24–38 in submitGradeButton_Click use a Select … Case statement to determine which counter to increment. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

73  A grade in the range 90–100 represents an A, 80–89 represents a B, 70–79 represents a C, 60–69 represents a D and 0–59 represents an F.  We assume that the user enters a grade in the range 0–100.  Line 24 begins the Select … Case statement.  The expression following the keywords Select Case (in this case, grade ) is called the controlling expression.  It is compared in order with each Case.  If a matching Case is found, the code in the Case executes, then program control proceeds to the first statement after the Select … Case statement (line 40). © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

74  The first Case (line 25) determines whether the value of grade is equal to 100.  If so, the statements in lines 26–27 execute, incrementing both aCount (because a grade of 100 is an A) and perfectScoreCount.  A Case statement can specify multiple actions—in this case, incrementing both aCount and perfectScoreCount.  The next Case statement (line 28) determines whether grade is between 90 and 99, inclusive.  In this case, only aCount is incremented (line 29).  Keyword To specifies the range; lines 30–35 use this keyword to present a series of similar Case s. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

75  Each case increments the appropriate counter.  If no match occurs between the controlling expression’s value and a Case label, the optional Case Else (lines 36–37) executes.  We use the Case Else in this example to process all controlling-expression values that are less than 60 — that is, all failing grades.  If no match occurs and the Select … Case does not contain a Case Else, program control simply continues with the first statement after the Select … Case. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

76  Case Else commonly is used to deal with invalid values.  In this example, we assume all values entered by the user are in the range 0–100.  When used, the Case Else must be the last Case.  The required End Select keywords (line 38) terminate the Select … Case statement. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

77

78

79

80  Types of Case Statements ◦ Case statements also can use relational operators to determine whether the controlling expression satisfies a condition. ◦ For example Case Is < 0 uses keyword Is along with the relational operator, <, to test for values less than 0. ◦ Multiple values can be tested in a Case statement by separating the values with commas, as in Case 0, 5 To 9 which tests for the value 0 or values in the range 5–9. ◦ Also, Case s can be used to test String values. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

81  Select … Case Statement UML Activity Diagram ◦ Figure 5.10 shows the UML activity diagram for the general Select … Case statement. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

82

83  The Do…Loop While repetition statement is similar to the While … End While statement and Do While … Loop statement.  In the While … End While and Do While … Loop statements, the loop-continuation condition is tested at the beginning of the loop, before the body of the loop is performed, so these are referred to as pre-test loops. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

84  The Do … Loop While statement tests the loop- continuation condition after the loop body is performed, so it’s referred to as a post-test loop.  In a Do … Loop While statement, the loop body is always executed at least once.  When a Do … Loop While statement terminates, execution continues with the statement after the Loop While clause.  The program in Fig. 5.11 uses a Do … Loop While statement to output the even integers from 2 to 10. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

85

86  When program control enters the loop, lines 11–12 execute, displaying the value of counter (at this point, 2 ), then incrementing counter by 2.  Then the loop-continuation condition in line 13 is evaluated.  Variable counter is 4, which is less than or equal to 10, so the Do … Loop While statement executes lines 11–12 again.  In the fifth iteration of the statement, line 11 outputs the value 10, and line 12 increments counter to 12.  At this point, the loop-continuation condition in line 13 evaluates to false, and the program exits the Do … Loop While statement. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

87  Do … Loop While Statement Activity Diagram ◦ The Do … Loop While activity diagram (Fig. 5.12) shows that the loop-continuation condition is not evaluated until after the statement body executes at least once. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

88  Do … Loop Until Repetition Statement ◦ The Do … Loop Until repetition statement is similar to the Do Until … Loop statement, except that the loop-termination condition is tested after the loop body is performed; therefore, the loop body executes at least once. ◦ When a Do … Loop Until terminates, execution continues with the statement after the Loop Until clause. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

89

90  The following code uses a Do … Loop Until statement to reimplement the Do … Loop While statement of Fig. 5.11 Do ' display counter value outputLabel.Text &= counter & " " counter += 2 ' increment counter Loop Until counter > 10  The Do … Loop Until statement activity diagram is the same as the one in Fig. 5.12.  The loop-termination condition ( counter > 10 ) is not evaluated until after the loop body executes at least once.  If this condition is true, the statement exits.  If the condition is false (that is, the condition counter <= 10 is true), the loop continues executing. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

91  There are many forms of the Exit statement, designed to terminate different types of repetition statements.  When the Exit Do statement executes in a Do While … Loop, Do … Loop While, Do Until … Loop or Do … Loop Until statement, the program terminates that repetition statement and continues execution with the first statement after the repetition statement.  Similarly, the Exit For statement and the Exit While statement cause immediate exit from For … Next and While … End While loops, respectively.  The Exit Select statement causes immediate exit from a Select … Case statement. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

92  A Continue statement terminates only the current iteration of a repetition statement and continues execution with the next iteration of the loop.  The Continue Do statement can be executed in a Do While … Loop, Do … Loop While, Do Until … Loop or Do … Loop Until statement.  Similarly, the Continue For statement and Continue While statement can be used in For … Next and While … End While statements, respectively. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

93  When Continue For is encountered in a For … Next statement, execution continues with the statement’s increment expression, then the program evaluates the loop-continuation test.  When Continue is used in another type of repetition statement, the program evaluates the loop-continuation (or loop-termination) test immediately after the Continue statement executes.  If a control variable’s increment occurs in the loop body after the Continue statement, the increment is skipped. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

94  Exit and Continue in Nested Control Statements ◦ Exit For or Continue For can be used in a While … End While statement, as long as that statement is nested in a For … Next statement. ◦ In such an example, the Exit or Continue statement would be applied to the proper control statement based on the keywords used in the Exit or Continue statement—in this example, the For keyword is used, so the For … Next statement’s flow of control will be altered. ◦ If there are nested loops of the same type (for example, a For … Next statement within a For … Next statement), the statement that immediately surrounds the Exit or Continue statement is the one affected. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

95  A condition is an expression that results in a Boolean value—True or False.  So far, we’ve studied only simple conditions, such as count 1000 and number <> -1.  Each selection and repetition statement evaluated only one condition with one of the operators >, =,. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

96  To make a decision that relied on the evaluation of multiple conditions, we performed these tests in separate statements or in nested If … Then or If … Then … Else statements.  To handle multiple conditions more efficiently, the logical operators can be used to form complex conditions by combining simple ones.  Logical operators are And, Or, AndAlso, OrElse, Xor and Not. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

97  Logical And Operator ◦ Suppose we wish to ensure that two conditions are both True in a program before a certain path of execution is chosen. ◦ In such a case, we can use the logical And operator as follows: If gender = "F" And age >= 65 Then seniorFemales += 1 End If ◦ This If … Then statement contains two simple conditions. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

98  The condition gender = "F" determines whether a person is female and the condition age >= 65 determines whether a person is a senior citizen.  The two simple conditions are evaluated first, because the precedences of = and >= are both higher than the precedence of And.  The If … Then statement then considers the combined condition gender = "F" And age >= 65  This condition evaluates to True if and only if both simple conditions are True. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

99  When this combined condition is True, the seniorFemales count is incremented by 1.  However, if either or both simple conditions are False, the program skips the increment and proceeds to the statement following the If … Then statement.  The readability of the preceding combined condition can be improved by adding redundant (that is, unnecessary) parentheses: (gender = "F") And (age >= 65) © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

100  Figure 5.13 illustrates the effect of using the And operator with two expressions.  The table lists all four possible combinations of True and True values for expression1 and expression2.  Such tables often are called truth tables.  Expressions that include relational operators, equality operators and logical operators evaluate to True or False. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

101

102  Logical Or Operator ◦ Now let’s consider the Or operator. ◦ Suppose we wish to ensure that either or both of two conditions are True before we choose a certain path of execution. ◦ We use the Or operator as in the following program segment: If (semesterAverage >= 90 Or finalExam >= 90 ) Then resultLabel.Text = "Student grade is A" End If ◦ This statement also contains two simple conditions. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

103  The condition semesterAverage >= 90 is evaluated to determine whether the student deserves an “A” in the course because of an outstanding performance throughout the semester.  The condition finalExam >= 90 is evaluated to determine whether the student deserves an “A” in the course because of an outstanding performance on the final exam. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

104  The If … Then statement then considers the combined condition (semesterAverage >= 90 Or finalExam >= 90 ) and awards the student an “A” if either or both of the conditions are True.  The text "Student grade is A" is displayed, unless both of the conditions are False.  Figure 5.14 shows the Or operator’s truth table.  The And operator has a higher precedence than Or. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

105

106  Logical AndAlso and OrElse Operators ◦ The logical AND operator with short-circuit evaluation (AndAlso) and the logical inclusive OR operator with short- circuit evaluation (OrElse) are similar to the And and Or operators, respectively, with one exception—an expression containing AndAlso or OrElse operators is evaluated only until its truth or falsity is known. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

107  For example, the expression (gender = "F" AndAlso age >= 65) stops evaluating immediately if gender is not equal to "F" (that is, the entire expression is False ); the second expression is irrelevant because the first condition is False.  Evaluation of the second condition occurs if and only if gender is equal to "F" (that is, the entire expression could still be True if the condition age >= 65 is True ).  This performance feature for the evaluation of AndAlso and OrElse expressions is called short-circuit evaluation. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

108

109  Logical Xor Operator ◦ A condition containing the logical exclusive OR (Xor) operator is True if and only if one of its operands results in a True value and the other results in a False value. ◦ If both operands are True or both are False, the entire condition is False. ◦ Figure 5.15 presents a truth table for the logical exclusive OR operator ( Xor ). ◦ This operator always evaluates both of its operands—there is no short-circuit evaluation. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

110

111  Logical Not Operator ◦ The Not (logical negation) operator enables you to “reverse” the meaning of a condition. ◦ Unlike the logical operators And, AndAlso, Or, OrElse and Xor, which each combine two conditions, the logical negation operator is a unary operator, requiring only one operand. ◦ The logical negation operator is placed before a condition to choose a path of execution if the original condition (without the logical negation operator) is False. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

112  The logical negation operator is demonstrated by the following program segment: If Not (value = 0) Then resultLabel.Text = "The value is " & value End If  The parentheses around the condition value = 0 are necessary because the logical negation operator ( Not ) has a higher precedence than the equality operator.  Figure 5.16 provides a truth table for the logical negation operator. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

113  In most cases, you can avoid using logical negation by expressing the condition differently with relational or equality operators.  This flexibility helps you express conditions more naturally.  For example, the preceding statement can be written as follows: If value <> 0 Then resultLabel.Text = "The value is " & value End If © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

114

115  To demonstrate some of the logical operators, let’s consider the following problem: ◦ A dentist’s office administrator wishes to create an application that employees can use to bill patients. The application must allow users to enter the patient’s name and specify which services were performed during the visit. The application will then calculate the total charges. If a user attempts to calculate a bill before any services are specified, or before the patient’s name is entered, an error message will be displayed informing the user that necessary input is missing. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

116  GUI for the Dental Payment Calculator Application ◦ In the Dental Payment Calculator application, you’ll use two new GUI controls— CheckBox es and a message dialog—to assist the user in entering data. ◦ The CheckBox es allow the user to select which dental services were performed. ◦ Programs often use message dialogs to display important messages to the user. ◦ A CheckBox is a small square that either is blank or contains a check mark. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

117  A CheckBox is known as a state button because it can be in the “on” state or the “off” state.  When a CheckBox is selected, a check mark appears in the box.  Any number of CheckBox es can be selected at a time, including none at all.  The text that appears alongside a CheckBox is called the CheckBox label.  If the CheckBox is “on” (checked), its Checked property has the Boolean value True ; otherwise, it’s False ( “ off ” ).  The application’s GUI is shown in Fig. 5.17 and the code is shown in Fig. 5.18. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

118

119

120

121

122  Using Logical Operators ◦ Recall from the problem statement that an error message should be displayed if the user does not enter a name or select at least one CheckBox. ◦ When the user presses the Calculate Button, lines 9–12 test these possibilities using logical operators Not, OrElse and AndAlso. ◦ The compound condition is split into two parts. ◦ If the condition in line 9 is True, the user did not enter a name, so an error message should be displayed. ◦ Short-circuit evaluation occurs with the OrElse operator, so the rest of the condition (lines 10–12) is ignored. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

123  If the user entered a name, then lines 10–12 check all three CheckBox es.  The expression Not cleaningCheckBox.Checked is True if the cleaningCheckBox is not checked—the Checked property has the value False and the Not operator returns True.  If all three CheckBox es are unchecked, the compound condition in lines 10–12 is True, so an error message should be displayed. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

124  Calculating the Total of the Selected Services ◦ If the user entered a name and selected at least one CheckBox, lines 21–42 calculate the total of the selected dental services. ◦ Each condition in lines 26, 31 and 36 uses the value of one of the CheckBox ’s Checked properties as the condition. ◦ If a given CheckBox ’s Checked property is True, the body statement gets the value from the corresponding price Label, converts it to a number and adds it to the total. ◦ Then, line 41 displays the result in the totalCostLabel. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

125  Displaying an Error Message Dialog ◦ Class MessageBox creates message dialogs. ◦ We use a message dialog in lines 17–20 to display an error message to the user if the condition in lines 9–12 is True. ◦ MessageBox method Show displays the dialog. ◦ This method takes four arguments. ◦ The first is the String that’s displayed in the message dialog. ◦ The second is the String that’s displayed in the message dialog’s title bar. ◦ The third and fourth are predefined constants that specify the Button (s) and the icon to show on the dialog, respectively. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

126  Figure 5.19 shows the message box displayed by lines 17–20.  It includes an OK button that allows the user to dismiss (that is, close) the message dialog by clicking the button.  The program waits for the dialog to be closed before executing the next line of code—this type of dialog is known as a modal dialog.  You can also dismiss the message dialog by clicking the dialog’s close box—the button with an X in the dialog’s upper-right corner. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

127

128  Summary of Operator Precedence ◦ Figure 5.20 displays the precedence of the operators introduced so far. ◦ The operators are shown from top to bottom in decreasing order of precedence. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

129


Download ppt "Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved."

Similar presentations


Ads by Google