Upcoming SlideShare
×

# Chapter 04

855 views

Published on

Published in: Sports, Technology
0 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

• Be the first to like this

Views
Total views
855
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
20
0
Likes
0
Embeds 0
No embeds

No notes for slide
• Brief description on how to navigate within this presentation (ppt) The first time a Key Term from the chapter is used in the ppt it will display in blue Gold colored text boxes display coding examples Slides will be numbered (# of #) when multiple slides on same topic (Slide title) Speaker notes are included where appropriate for slides (*)Denotes either a comment for page reference to textbook or slide reference in ppt
• A powerful capability of the computer is its ability to make decisions and to take alternate courses of action based on the outcome
• A decision made by the computer is formed as a questions: Is a given condition true or false? If it is true, do one thing, if it is false, do something else
• When the number of unitsDecimal is less than 32, select the radio button for Freshman; otherwise, make sure the radio button is deselected
• Diamond shape symbol (decision symbol) represents a condition Branches from the decision symbol indicate which path to take for different results
• The VS code editor is very helpful when If statements are entered
• *Refer to Table 4.1 on p. 145
• String variables can be compared to other string variables, string properties, or string literals enclosed in quotes ANSI stands for American National Standards Institute
• When comparing strings, the case of the characters is important—an uppercase Y is not equal to a lowercase y Users may type a name or word in upper or lower case or a combination both there are checks for all possibilities
• Compound conditions can be used to test more than once condition Create compound conditions (key term) by joining conditions with logical operators (key term) *Refer to table on p. 152
• If statements that contain additional If statements are said to be nested If statements. You can nest Ifs in both the Then and Else. In fact, you may continue to nest Ifs within Ifs as long as each If has an End If.
• Use If Statements to determine which options are selected
• It’s time to add features to control the format of the message, display multiple buttons, check which button the user clicks, perform alternate actions depending on the user’s selection, etc.
• Message box created by conantenating two NewLine characters at the end of each line
• Several other intrinsic constants from the ControlChars list are available in addition to the NewLine constant. Type “ControlChars” and a period into the editor to see the complete list
• Display Yes and No buttons on a message box using MessageBoxButtons. YesNo
• To capture the information about the outcome of a method variables must be declared so it can hold an instance of the DialogResult type
• When multiple buttons are displayed programmers may want one of the buttons to be the default button Alignment can also be established by using the MessageBox options argument
• Validation is a form of self-protection and it is better to reject bad data then to spend hours tying to find an error only to discover that the problem was caused by a “user error” Finding and correcting the error early can often keep the program from producing erroneous results or halting with a run-time error Data validation may include checking the reasonableness of a value or that a value has been entered into a required field By checking separately for blank or nonnumeric data, you can display a better message to the user
• When there is a need to validate several input fields how many message boxes should display for the user? Avoid displaying multiple message boxes in a row by using a nested If statement—the second value is checked if the first one passes and if a problem is found in a single field it exits
• A very handy feature of VB.NET is the ability to share an event procedure for several controls
• If you wish to perform a set of instructions in more thanone location, you don’t have to duplicate the code—write the instructions once, in an event procedure, and “call” the procedure from another procedure When an event procedure is called the entire procedure is executed and then execution returns to the statement following the call
• ### Chapter 04

3. 3. Objectives (1 of 2) <ul><li>Use If statements to control the flow of logic. </li></ul><ul><li>Understand and use nested If statements. </li></ul><ul><li>Read and create action diagrams that illustrate the logic in a selection process. </li></ul><ul><li>Evaluate conditions using the comparison operators. </li></ul><ul><li>Combine conditions using And, Or, AndAlso, and OrElse. </li></ul><ul><li>Test the Checked property of radio buttons and check boxes. </li></ul><ul><li>Perform validation on numeric fields. </li></ul>
4. 4. Objectives (2 of 2) <ul><li>Use a Case structure for multiple decisions. </li></ul><ul><li>Use one event procedure to respond to the events for multiple controls and determine which control caused the event. </li></ul><ul><li>Call an event procedure from another procedure. </li></ul><ul><li>Create message boxes with multiple buttons and choose alternate actions based on the user response. </li></ul><ul><li>Debug projects using breakpoints , stepping program execution, and displaying intermediate results. </li></ul>
5. 5. If Statements <ul><li>Used to make decisions </li></ul><ul><li>If true, only the Then clause is executed, if false, only Else clause, if present, is executed </li></ul><ul><li>Block If…Then…Else must always conclude with End If </li></ul><ul><li>Then must be on same line as If or ElseIf </li></ul><ul><li>End If and Else must appear alone on a line </li></ul><ul><li>Note: ElseIf is 1 word, End If is 2 words </li></ul>
6. 6. If…Then…Else – General Form If (condition) Then statement(s) [ ElseIf (condition) Then statement(s)] [ Else statement(s)] End If Logic with the Else Logic without the Else
7. 7. If…Then…Else - Example <ul><li>IF </li></ul><ul><li>unitsDecimal = Decimal.Parse(unitsTextBox.Text) </li></ul><ul><li>If unitsDecimal < 32D Then .freshmanRadioButton.Checked = True </li></ul><ul><li>Else .freshmanRadioButton.Checked = False </li></ul><ul><li>End IF </li></ul>
8. 8. Charting If Statements <ul><li>A Uniform Modeling Language (UML) activity diagram is a useful tool for showing the logic of an IF statement </li></ul><ul><li>Can be used to help programmers organize their thoughts and design projects more quickly </li></ul><ul><li>UML includes several types of diagrams </li></ul><ul><ul><li>Activity diagram-visual planning tool for decisions/actions for either the entire application or single procedure </li></ul></ul>
9. 9. <ul><li>Test in an If statement is based on a condition </li></ul><ul><li>Six relational operators are used for comparison </li></ul><ul><li>Negative numbers are less than positive numbers </li></ul><ul><li>An equal sign is used to test for equality </li></ul><ul><li>Strings can be compared, enclose strings in quotes </li></ul><ul><ul><li>JOAN is less than JOHN </li></ul></ul><ul><ul><li>HOPE is less than HOPELESS </li></ul></ul><ul><li>Numbers are always less than letters </li></ul><ul><ul><li>300ZX is less than Porsche </li></ul></ul>Conditions
10. 10. The Helpful Editor <ul><li>When entering IF statements the editor automatically adds the Then and End If </li></ul><ul><li>The editor attempts to correct errors by supplying a colon if multiple statements are entered on a line </li></ul><ul><ul><li>The colon is a statement terminator </li></ul></ul><ul><ul><li>Good programming practices dictate that there should be only statement per line—so remove the extra colon if found and correct the syntax </li></ul></ul>
11. 11. The Six Relational Operators The test in an IF statement if based on a condition. To form conditions comparison operators are used. > < = <> >= <=
12. 12. Comparing Strings <ul><li>Comparison begins with the left-most character and proceeds one character at a time left to right </li></ul><ul><li>If a character in one string is not equal to the corresponding character in the 2 nd string the comparison terminates </li></ul><ul><li>The string with the lower-ranking character is judge less than the other </li></ul><ul><ul><li>Ranking is based on ANSI code , an established order (collating sequence) for all letters, numbers, and special characters </li></ul></ul>
13. 13. Comparing Upper and Lowercase Characters <ul><li>Use ToUpper and ToLower methods of the String class to return the uppercase or lowercase equivalent of a string, respectively </li></ul>If nameTextBox.Text.ToUpper( ) = “BASIC&quot; Then ' Do something. End If When converting name TextBox.Text to uppercase it must be compared to an uppercase literal (“BASIC”) if it is to evaluate as True
14. 14. Compound Condition If maleRadioButton.Checked And _ Integer.Parse(ageTextBox.Text) < 21 Then minorMaleCountInteger += 1 End If If juniorRadioButton.Checked Or seniorRadioButton.Checked Then upperClassmanInteger += 1 End If
15. 15. Combining Logical Operators <ul><li>Compound conditions can combine multiple logical conditions </li></ul><ul><li>When both And and Or are evaluated And is evaluated before the Or </li></ul><ul><li>Use parenthesis to change the order of evaluation—inside the parenthesis is evaluated first </li></ul>If saleDecimal > 1000.0 Or discountRadioButton.Checked _ And stateTextBox.Text.ToUpper( ) <> &quot;CA&quot; Then ' Code here to calculate the discount. End If
16. 16. Short-Circuit Operations <ul><li>VB.NET 2005 adds 2 new operators that provide short-circuit evaluation for compound conditions: </li></ul><ul><ul><li>AndAlso and OrElse </li></ul></ul><ul><li>VB evaluates both expressions for True or False, then evaluates the And </li></ul><ul><li>The OrElse is designed to short circuit when the first condition evaluates True </li></ul><ul><li>AndAlso and OrElse are used for advanced programming when the 2 nd expression should not be executed for some reason </li></ul>
17. 17. Nested If Statements If tempInteger > 32 Then If tempInteger > 80 Then commentLabel.Text = &quot;Hot&quot; Else commentLabel.Text = &quot;Moderate&quot; End If Else commentLabel.Text = &quot;Freezing&quot; End If
18. 18. Using If Statements with Radio Buttons & Check Boxes <ul><li>Instead of coding the CheckedChanged events, use If statements to see which are selected </li></ul><ul><li>Place the If statement in the Click event for a Button, such as an OK or Apply button; VS checks to see which options are selected </li></ul>
19. 19. Enhancing Message Boxes <ul><li>For longer, more complex messages, store the message text in a String variable and use that variable as an argument of the Show method </li></ul><ul><li>VB will wrap longer messages to a second line </li></ul><ul><li>Include ControlChars to control the line length and position of the line break in multiple lines of output </li></ul><ul><li>Combine multiple NewLine constants to achieve double spacing and create multiple message lines </li></ul>
20. 20. Message String Example Dim formattedTotalString As String Dim formattedAvgString As String Dim messageString As String formattedTotalString = totalSalesDecimal.ToString(&quot;N&quot;) formattedAvgString = averageSalesDecimal.ToString(&quot;N&quot;) messageString = &quot;Total Sales: &quot; & formattedTotalString _ & ControlChars. NewLine & &quot;Average Sale: &quot; & _ formattedAvgString MessageBox.Show(messageString, &quot;Sales Summary&quot;, _ MessageBoxButtons.OK)
21. 21. Message Box - Multiple Lines of Output ControlChars.NewLine Used to force to next line
22. 22. ControlChars Constants Quotation mark character Quote Vertical tab character (not useful in Microsoft Windows VerticalTab Formfeed character (not useful in Microsoft Windows) FormFeed Backspace character Back Tab character Tab Character with a value of zero NullChar New line character. Same effect as a carriage return/linefeed character combination NewLine Line feed Lf Carriage return Cr Carriage return/linefeed character combination CfLf Description ControlChar Constant
23. 23. Displaying Multiple Buttons <ul><li>Use MessageBoxButtons constants to display more than one button in the Message Box </li></ul><ul><li>Message Box's Show method returns a DialogResult object that can be checked to see which button the user clicked </li></ul><ul><li>Declare a variable to hold an instance of the DialogResult type to capture the outcome of the Show method </li></ul>
24. 24. Message Box - Multiple Buttons MessageBoxButtons.YesNo
25. 25. Declaring an Object Variable for the Method Return Dim whichButtonDialogResult As DialogResult whichButtonDialogResult = MessageBox.Show _ (&quot;Clear the current order figures?&quot;, &quot;Clear Order&quot;, _ MessageBoxButtons.YesNo, MessageBoxIcon.Question) If whichButtonDialogResult = DialogResult.Yes Then ' Code to clear the order. End If
26. 26. Specifying a Default Button and Options <ul><li>Use a different signature for the Message Box Show method to specify a default button </li></ul><ul><li>Add the MessageBoxDefaultButton argument after the MessageBoxIcons argument </li></ul><ul><li>Set message alignment with MessageBoxOptions argument </li></ul>
27. 27. Input Validation <ul><li>Check to see if valid values were entered by user before beginning calculations—called validation </li></ul><ul><li>Check for a range of values (reasonableness) </li></ul><ul><ul><li>If Integer.Parse(Me.hoursTextBox.Text) <= 10 Then </li></ul></ul><ul><ul><li>‘ Code to perform calculations…. </li></ul></ul><ul><li>Check for a required field (not blank) </li></ul><ul><ul><li>If nameTextBox.Text <> &quot;&quot; Then ... </li></ul></ul>
28. 28. Performing Multiple Validations <ul><li>Use nested If statement to validate multiple values on a form </li></ul><ul><li>--OR-- </li></ul><ul><li>Use Case structure to validate multiple values </li></ul><ul><ul><li>Simpler and clearer than nested If </li></ul></ul><ul><ul><li>No limit to number of statements that follow a Case statement </li></ul></ul><ul><ul><li>When using a relational operator must use the word Is </li></ul></ul><ul><ul><li>Use the word To to indicate a range of constants </li></ul></ul>
29. 29. Sharing an Event Procedure <ul><li>Add events to the Handles clause at the top of an event procedure </li></ul><ul><ul><li>Allows the procedure to respond to events of other controls </li></ul></ul><ul><li>Good professional technique is to set up a module-level variable to hold the selection a user makes </li></ul><ul><li>Key to using a shared event procedure is the sender argument </li></ul><ul><ul><li>Cast (convert) sender to a specific object type using the CType function </li></ul></ul>
30. 30. Calling Event Procedures <ul><li>Reusable code </li></ul><ul><li>General Form </li></ul><ul><ul><li>[Call] ProcedureName ( ) </li></ul></ul><ul><ul><li>Keyword Call is optional and rarely used </li></ul></ul><ul><li>Examples </li></ul><ul><ul><li>Call clearButton_Click (sender, e) </li></ul></ul><ul><ul><li>--OR-- </li></ul></ul><ul><ul><li>clearButton_Click (sender, e) </li></ul></ul>
31. 31. Calling Event Procedures Example <ul><li>A form with buttons that perform overlapping functions </li></ul><ul><li>The New Order button must do the same tasks as Clear for Next Item </li></ul>
32. 32. Debugging Tools <ul><li>Use Debug Menu and Debug options on VB Standard toolbar </li></ul><ul><li>Place Debug.WriteLine method in code </li></ul><ul><li>Set BreakPoints to stop at a particular location in code and watch what happens </li></ul><ul><li>Step Into , Step Over , Step Out </li></ul><ul><li>Edit and Continue </li></ul><ul><li>Locals Window, and Autos Window </li></ul><ul><ul><li>View the values of properties, variables, mathematical expressions, and conditions </li></ul></ul>
33. 33. Debug Menu and Toolbar The debugging buttons on the VB standard toolbar The debugging options on the Debug menu showing the keyboard shortcut keys
34. 34. Writing to the Immediate Window <ul><li>Debug.WriteLine( TextString ) </li></ul><ul><li>Debug.WriteLine( Object ) </li></ul>Debug.WriteLine(&quot;calculateButton procedure entered&quot;) Debug.WriteLine(quantityTextBox)
35. 35. Breakpoints Toggle Breakpoints On/Off by clicking in Editor's gray left margin indicator
36. 36. Edit and Continue When attempting to continue execution after making changes in Debugging mode this dialog box appears if the edits are too major—Click Restart to recompile and run again
37. 37. Locals Window Shows values of local variables that are within scope of current statement
38. 38. Autos Window Automatically adjusts to show variables and properties that appear in previous and next few lines