Chapter 04

38
4-1 lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh lskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjh

Transcript of Chapter 04

Page 1: Chapter 04

4-1

aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhfaslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf

Page 2: Chapter 04

Chapter 4Decisions and Conditions

Chapter 44

McGraw-Hill © 2006 The McGraw-Hill Companies, Inc. All rights reserved.

Page 3: Chapter 04

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

Page 4: Chapter 04

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

Page 5: Chapter 04

4-5

If Statements

Used to make decisionsIf true, only the Then clause is executed, if false,

only Else clause, if present, is executedBlock If…Then…Else must always conclude with

End IfThen must be on same line as If or ElseIfEnd If and Else must appear alone on a lineNote: ElseIf is 1 word, End If is 2 words

Page 6: Chapter 04

4-6

If…Then…Else – General Form

If (condition) Thenstatement(s)

[ElseIf (condition) Thenstatement(s)]

[Elsestatement(s)]

End If

Logic with the Else

Logic without the Else

Page 7: Chapter 04

4-7

If…Then…Else - Example

IFunitsDecimal = Decimal.Parse(unitsTextBox.Text)If unitsDecimal < 32D Then

.freshmanRadioButton.Checked = TrueElse

.freshmanRadioButton.Checked = FalseEnd IF

Page 8: Chapter 04

4-8

Charting If Statements

A Uniform Modeling Language (UML) activity diagram is a useful tool for showing the logic of an IF statement

Can be used to help programmers organize their thoughts and design projects more quickly

UML includes several types of diagramsActivity diagram-visual planning tool for

decisions/actions for either the entire application or single procedure

Page 9: Chapter 04

4-9

Test in an If statement is based on a conditionSix relational operators are used for comparisonNegative numbers are less than positive

numbersAn equal sign is used to test for equalityStrings can be compared, enclose strings in

quotesJOAN is less than JOHNHOPE is less than HOPELESS

Numbers are always less than letters300ZX is less than Porsche

Conditions

Page 10: Chapter 04

4-10

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 lineThe colon is a statement terminatorGood programming practices dictate that there should

be only statement per line—so remove the extra colon if found and correct the syntax

Page 11: Chapter 04

4-11

The Six Relational Operators

The test in an IF statement if based on a condition. To form conditions comparison operators are used.

> < = <> >= <=

Page 12: Chapter 04

4-12

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 otherRanking is based on ANSI code, an established order

(collating sequence) for all letters, numbers, and special characters

Page 13: Chapter 04

4-13

Comparing Upper and Lowercase Characters

Use ToUpper and ToLower methods of the String class to return the uppercase or lowercase equivalent of a string, respectively

If nameTextBox.Text.ToUpper( ) = “BASIC" 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

Page 14: Chapter 04

4-14

Compound Condition

If maleRadioButton.Checked And _ Integer.Parse(ageTextBox.Text) < 21 Then

minorMaleCountInteger += 1End If

If juniorRadioButton.Checked Or seniorRadioButton.Checked Then

upperClassmanInteger += 1End If

Page 15: Chapter 04

4-15

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 > 1000.0 Or discountRadioButton.Checked _ And stateTextBox.Text.ToUpper( ) <> "CA" Then

' Code here to calculate the discount.End If

Page 16: Chapter 04

4-16

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

Page 17: Chapter 04

4-17

If tempInteger > 32 ThenIf tempInteger > 80 Then

commentLabel.Text = "Hot"Else

commentLabel.Text = "Moderate"End If

ElsecommentLabel.Text = "Freezing"

End If

Nested If Statements

Page 18: Chapter 04

4-18

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

Page 19: Chapter 04

4-19

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

Page 20: Chapter 04

4-20

Message String Example

Dim formattedTotalString As StringDim formattedAvgString As StringDim messageString As String

formattedTotalString = totalSalesDecimal.ToString("N")formattedAvgString = averageSalesDecimal.ToString("N")messageString = "Total Sales: " & formattedTotalString _ & ControlChars.NewLine & "Average Sale: " & _ formattedAvgStringMessageBox.Show(messageString, "Sales Summary", _ MessageBoxButtons.OK)

Page 21: Chapter 04

4-21

Message Box - Multiple Lines of Output

ControlChars.NewLineUsed to force to next line

Page 22: Chapter 04

4-22

ControlChars Constants

ControlChar Constant Description

CfLf Carriage return/linefeed character combination

Cr Carriage return

Lf Line feed

NewLine New line character. Same effect as a carriage return/linefeed character combination

NullChar Character with a value of zero

Tab Tab character

Back Backspace character

FormFeed Formfeed character (not useful in Microsoft Windows)

VerticalTab Vertical tab character (not useful in Microsoft Windows

Quote Quotation mark character

Page 23: Chapter 04

4-23

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

Page 24: Chapter 04

4-24

Message Box - Multiple Buttons

MessageBoxButtons.YesNo

Page 25: Chapter 04

4-25

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

Page 26: Chapter 04

4-26

Specifying a Default Button and Options

Use a different signature for the Message Box Show method to specify a default button

Add the MessageBoxDefaultButton argument after the MessageBoxIcons argument

Set message alignment with MessageBoxOptions argument

Page 27: Chapter 04

4-27

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

Page 28: Chapter 04

4-28

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 IfNo limit to number of statements that follow a

Case statementWhen using a relational operator must use

the word IsUse the word To to indicate a range of

constants

Page 29: Chapter 04

4-29

Sharing an Event Procedure

Add events to the Handles clause at the top of an event procedureAllows the procedure to respond to events of other

controlsGood professional technique is to set up a module-

level variable to hold the selection a user makesKey to using a shared event procedure is the sender

argumentCast (convert) sender to a specific object type using the

CType function

Page 30: Chapter 04

4-30

Calling Event Procedures

Reusable codeGeneral Form

[Call] ProcedureName ( )Keyword Call is optional and rarely used

ExamplesCall clearButton_Click (sender, e)--OR--clearButton_Click (sender, e)

Page 31: Chapter 04

4-31

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

Page 32: Chapter 04

4-32

Debugging Tools

Use Debug Menu and Debug options on VB Standard toolbar

Place Debug.WriteLine method in codeSet BreakPoints to stop at a particular location in

code and watch what happensStep Into, Step Over, Step OutEdit and ContinueLocals Window, and Autos Window

View the values of properties, variables, mathematical expressions, and conditions

Page 33: Chapter 04

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

Page 34: Chapter 04

4-34

Writing to the Immediate Window

Debug.WriteLine(TextString)Debug.WriteLine(Object)

Debug.WriteLine("calculateButton procedure entered")Debug.WriteLine(quantityTextBox)

Page 35: Chapter 04

4-35

Breakpoints

Toggle Breakpoints On/Off by clicking in Editor's gray left margin indicator

Page 36: Chapter 04

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

Page 37: Chapter 04

4-37

Locals Window

Shows values of local variables that are within scope of current statement

Page 38: Chapter 04

4-38

Autos Window

Automatically adjusts to show variables and properties that appear in previous and next few lines