Presentation is loading. Please wait.

Presentation is loading. Please wait.

Brief description on how to navigate within this presentation (ppt)

Similar presentations


Presentation on theme: "Brief description on how to navigate within this presentation (ppt)"— Presentation transcript:

1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf
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

2 Chapter 4 Decisions and Conditions
McGraw-Hill © 2006 The McGraw-Hill Companies, Inc. All rights reserved.

3 Objectives (1 of 2) Use If statements to control the flow of logic.
Understand and use nested If statements. Read and create action diagrams that illustrate the logic in a selection process. Evaluate conditions using the comparison operators. Combine conditions using And, Or, AndAlso, and OrElse. Test the Checked property of radio buttons and check boxes. Perform validation on numeric fields.

4 Objectives (2 of 2) Use a Case structure for multiple decisions.
Use one event procedure to respond to the events for multiple controls and determine which control caused the event. Call an event procedure from another procedure. Create message boxes with multiple buttons and choose alternate actions based on the user response. Debug projects using breakpoints, stepping program execution, and displaying intermediate results.

5 If Statements Used to make decisions
If true, only the Then clause is executed, if false, only Else clause, if present, is executed Block If…Then…Else must always conclude with End If Then must be on same line as If or ElseIf End If and Else must appear alone on a line Note: ElseIf is 1 word, End If is 2 words A powerful capability of the computer is its ability to make decisions and to take alternate courses of action based on the outcome

6 If…Then…Else – General Form
If (condition) Then statement(s) [ElseIf (condition) Then statement(s)] [Else End If Logic with the Else 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 Logic without the Else

7 If…Then…Else - Example
unitsDecimal = Decimal.Parse(unitsTextBox.Text) If unitsDecimal < 32D Then .freshmanRadioButton.Checked = True Else .freshmanRadioButton.Checked = False End IF When the number of unitsDecimal is less than 32, select the radio button for Freshman; otherwise, make sure the radio button is deselected

8 Conditions Test in an If statement is based on a condition
Six relational operators are used for comparison Negative numbers are less than positive numbers An equal sign is used to test for equality Strings can be compared, enclose strings in quotes JOAN is less than JOHN HOPE is less than HOPELESS Numbers are always less than letters 300ZX is less than Porsche

9 The Helpful Editor When entering IF statements the editor automatically adds the Then and End If The editor attempts to correct errors by supplying a colon if multiple statements are entered on a line The colon is a statement terminator Good programming practices dictate that there should be only statement per line—so remove the extra colon if found and correct the syntax The VS code editor is very helpful when If statements are entered

10 The Six Relational Operators
The test in an IF statement if based on a condition. To form conditions comparison operators are used. > < = <> >= <= *Refer to Table 4.1 on p. 145

11 Comparing Strings Comparison begins with the left-most character and proceeds one character at a time left to right If a character in one string is not equal to the corresponding character in the 2nd string the comparison terminates The string with the lower-ranking character is judge less than the other Ranking is based on ANSI code, an established order (collating sequence) for all letters, numbers, and special characters String variables can be compared to other string variables, string properties, or string literals enclosed in quotes ANSI stands for American National Standards Institute

12 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 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

13 Combining Logical Operators
Compound conditions can combine multiple logical conditions When both And and Or are evaluated And is evaluated before the Or Use parenthesis to change the order of evaluation—inside the parenthesis is evaluated first If saleDecimal > Or discountRadioButton.Checked _ And stateTextBox.Text.ToUpper( ) <> "CA" Then ' Code here to calculate the discount. End If

14 Short-Circuit Operations
VB.NET 2005 adds 2 new operators that provide short-circuit evaluation for compound conditions: AndAlso and OrElse VB evaluates both expressions for True or False, then evaluates the And The OrElse is designed to short circuit when the first condition evaluates True AndAlso and OrElse are used for advanced programming when the 2nd expression should not be executed for some reason

15 Nested If Statements If tempInteger > 32 Then
commentLabel.Text = "Hot" Else commentLabel.Text = "Moderate" End If commentLabel.Text = "Freezing" 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.

16 Using If Statements with Radio Buttons & Check Boxes
Instead of coding the CheckedChanged events, use If statements to see which are selected 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 Use If Statements to determine which options are selected

17 Enhancing Message Boxes
For longer, more complex messages, store the message text in a String variable and use that variable as an argument of the Show method VB will wrap longer messages to a second line Include ControlChars to control the line length and position of the line break in multiple lines of output Combine multiple NewLine constants to achieve double spacing and create multiple message lines 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.

18 Message String Example
Dim formattedTotalString As String Dim formattedAvgString As String Dim messageString As String formattedTotalString = totalSalesDecimal.ToString("N") formattedAvgString = averageSalesDecimal.ToString("N") messageString = "Total Sales: " & formattedTotalString _ & ControlChars.NewLine & "Average Sale: " & _ formattedAvgString MessageBox.Show(messageString, "Sales Summary", _ MessageBoxButtons.OK)

19 Message Box - Multiple Lines of Output
ControlChars.NewLine Used to force to next line Message box created by conantenating two NewLine characters at the end of each line

20 Displaying Multiple Buttons
Use MessageBoxButtons constants to display more than one button in the Message Box Message Box's Show method returns a DialogResult object that can be checked to see which button the user clicked Declare a variable to hold an instance of the DialogResult type to capture the outcome of the Show method

21 Message Box - Multiple Buttons
Display Yes and No buttons on a message box using MessageBoxButtons. YesNo MessageBoxButtons.YesNo

22 Declaring an Object Variable for the Method Return
Dim whichButtonDialogResult As DialogResult whichButtonDialogResult = MessageBox.Show _ ("Clear the current order figures?", "Clear Order", _ MessageBoxButtons.YesNo, MessageBoxIcon.Question) If whichButtonDialogResult = DialogResult.Yes Then ' Code to clear the order. End If To capture the information about the outcome of a method variables must be declared so it can hold an instance of the DialogResult type

23 Input Validation Check to see if valid values were entered by user before beginning calculations—called validation Check for a range of values (reasonableness) If Integer.Parse(Me.hoursTextBox.Text) <= 10 Then ‘ Code to perform calculations…. Check for a required field (not blank) If nameTextBox.Text <> "" Then ... 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

24 Performing Multiple Validations
Use nested If statement to validate multiple values on a form --OR-- Use Case structure to validate multiple values Simpler and clearer than nested If No limit to number of statements that follow a Case statement When using a relational operator must use the word Is Use the word To to indicate a range of constants 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

25 Sharing an Event Procedure
Add events to the Handles clause at the top of an event procedure Allows the procedure to respond to events of other controls Good professional technique is to set up a module-level variable to hold the selection a user makes Key to using a shared event procedure is the sender argument Cast (convert) sender to a specific object type using the CType function A very handy feature of VB.NET is the ability to share an event procedure for several controls

26 Calling Event Procedures
Reusable code General Form [Call] ProcedureName ( ) Keyword Call is optional and rarely used Examples Call clearButton_Click (sender, e) --OR-- clearButton_Click (sender, e) 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

27 Calling Event Procedures Example
A form with buttons that perform overlapping functions The New Order button must do the same tasks as Clear for Next Item


Download ppt "Brief description on how to navigate within this presentation (ppt)"

Similar presentations


Ads by Google