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

Slides:



Advertisements
Similar presentations
CS0004: Introduction to Programming Select Case Statements and Selection Input.
Advertisements

1.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Chapter 4 Decisions and Conditions Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
Programming with Microsoft Visual Basic th Edition
Microsoft Visual Basic: Reloaded Chapter Five More on the Selection Structure.
Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.
Chapter 4 Decisions and Conditions Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
The IDE (Integrated Development Environment) provides a DEBUGGER for locating and correcting errors in program logic (logic errors not syntax errors) The.
Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.
1 Chapter 4 The Fundamentals of VBA, Macros, and Command Bars.
Comparing Numeric Values If Val(Text1.Text) = MaxPrice Then (Is the current numeric value stored in the Text property of Text1 equal to the value stored.
CSC110 Fall Chapter 5: Decision Visual Basic.NET.
C++ for Engineers and Scientists Third Edition
IS 1181 IS 118 Introduction to Development Tools VB Chapter 03.
Chapter Four The Selection Structure
Microsoft Visual Basic 2008: Reloaded Fourth Edition
Chapter 4: The Selection Structure
Tutorial 11 Using and Writing Visual Basic for Applications Code
Enhancing User Interaction Through Programming
Chapter 4 Decisions and Conditions Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Five More on the Selection Structure.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 6 Decisions and Conditions.
Chapter 5 Menus, Common Dialog Boxes, and Methods Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Chapter 4: The Selection Process in Visual Basic.
Chapter 4: The Selection Structure Programming with Microsoft Visual Basic 2005, Third Edition.
Chapter 4: The Selection Structure
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 4 Decisions and Conditions.
4-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Copyright © 2001 by Wiley. All rights reserved. Chapter 4: The Selection Process in Visual Basic Selection Process Two Alternative Structure If..Then..ElseIf.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 8 Dental Payment Application Introducing CheckBox es and Message Dialogs.
Chapter 4 Decisions and Conditions Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
Program Design and Coding
Microsoft Visual Basic 2012 CHAPTER THREE Program Design and Coding.
Microsoft Visual Basic 2010 CHAPTER THREE Program Design and Coding.
Decisions and Debugging Part06dbg --- if/else, switch, validating data, and enhanced MessageBoxes.
Chapter 5: More on the Selection Structure Programming with Microsoft Visual Basic 2005, Third Edition.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Chapter 5: More on the Selection Structure
Programming with Microsoft Visual Basic th Edition
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
Chapter Four The Selection Structure Programming with Microsoft Visual Basic th Edition.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
Controlling Program Flow with Decision Structures.
Microsoft Visual Basic 2012 CHAPTER FIVE Decision Structures.
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 11 So Many Paths … So Little Time.
Chapter 10 So Many Paths … So Little Time (Multiple-Alternative Selection Structures) Clearly Visual Basic: Programming with Visual Basic nd Edition.
Chapter Five More on the Selection Structure Programming with Microsoft Visual Basic th Edition.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Chapter 4: Decisions and Conditions
A variable is a name for a value stored in memory.
Chapter 4: Decisions and Conditions
Brief description on how to navigate within this presentation (ppt)
Files.
The Selection Structure
CHAPTER FIVE Decision Structures.
Chapter 4: The Selection Structure
Microsoft Access Illustrated
Programming with Microsoft Visual Basic 2008 Fourth Edition
CHAPTER FIVE Decision Structures.
Making Decisions in a Program
Chapter 3: Introduction to Problem Solving and Control Statements
Objectives After studying this chapter, you should be able to:
Microsoft Visual Basic 2005: Reloaded Second Edition
Brief description on how to navigate within this presentation (ppt)
Chapter 4 Decisions and Conditions
Brief description on how to navigate within this presentation (ppt)
Presentation transcript:

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

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved. 4-2 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.

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved. 4-3 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.

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved. 4-4 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.

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved. 4-5 If…Then…Else — General Form If (condition) Then statement(s) [ElseIf (condition) Then statement(s)] [Else statement(s)] End If Logic of an If /Then/ Else statement Logic of an If statement without the Else

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved. 4-6 If…Then…Else — Example unitsDecimal = Decimal.Parse(unitsTextBox.Text) If unitsDecimal < 32D Then freshmanRadioButton.Checked = True Else freshmanRadioButton.Checked = False End IF

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved. 4-7 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 diagrams. Activity diagram-visual planning tool for decisions/actions for either the entire application or single procedure

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved. 4-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

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved. 4-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 one statement per line— so remove the extra colon if found, and correct the syntax.

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved The Six Relational Operators The test in an IF statement if based on a condition. To form conditions, comparison operators are used. > >= <=

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved 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 2 nd string, the comparison terminates. The string with the lower-ranking character is judged less than the other. Ranking is based on ANSI code, an established order (collating sequence) for all letters, numbers, and special characters.

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved 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.

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved 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

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved 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— condition inside the parenthesis is evaluated first. If saleDecimal > D Or discountRadioButton.Checked _ And stateTextBox.Text.ToUpper( ) <> "CA" Then ' Code here to calculate the discount. End If

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved Short-Circuit Operations Visual Basic has 2 operators that provide short- circuit evaluation for compound conditions: the 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 2 nd expression should not be executed for some reason.

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved Nested If Statements If tempInteger > 32 Then If tempInteger > 80 Then commentLabel.Text = "Hot" Else commentLabel.Text = "Moderate" End If Else commentLabel.Text = "Freezing" End If

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved Nested If Statements If tempInteger <= 32 Then commentLabel.Text = "Freezing" Else If tempInteger > 80 Then commentLabel.Text = "Hot" Else commentLabel.Text = "Moderate" End If

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved Nested If Statements If tempInteger <= 32 Then commentLabel.Text = "Freezing" Else If tempInteger <= 80 Then commentLabel.Text = "Moderate" Else commentLabel.Text =“Hot" End If

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved Nested If Statements If tempInteger > 80 Then commentLabel.Text = "Hot" Else If tempInteger > 32 Then commentLabel.Text = "Moderate” Else commentLabel.Text = "Freezing" End If

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved Using If Statements with Radio Buttons & Check Boxes Instead of coding the CheckedChanged events, use If statements to see which are selected. Place your code in the Click event of Buttons, such as an OK or Apply button; VS checks to see which options are selected.

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved Checking Radio Buttons If BeignRadioButton.Checked then BackColor = Color.Beige ElseIF BlueRadioButton.Checked then BackColor = Color.Blue ElseIf YellowRadioButton.Checked then BackColor = Color.Yellow Else BackColor = Color Gray End If 4-21

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved Checking Check Boxes If FastShipCheckBox.Checked Then TotalDecimal += FastShipRateDecimal End If If GiftWrapCheckBox.Checked then TotalDecimal += WRAP_AMOUNT_Decimal End If 4-22

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved 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.

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved Message String Example Dim formattedTotalString As String Dim formattedAvgString As String Dim messageString As String formattedTotalString = totalSalesDecimal.ToString("N") formattedAvgString = averageSaleDecimal.ToString("N") messageString = "Total Sales: " & formattedTotalString _ & Environment.NewLine & "Average Sale: " & _ formattedAvgString MessageBox.Show(messageString, "Sales Summary", _ MessageBoxButtons.OK)

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved Message Box — Multiple Lines of Output ControlChars.NewLine Used to force to next line

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved ControlChars Constants ControlChar ConstantDescription CfLfCarriage return/linefeed character combination CrCarriage return LfLine feed NewLineNew line character. Same effect as a carriage return/linefeed character combination NullCharCharacter with a value of zero TabTab character BackBackspace character FormFeedFormfeed character (not useful in Microsoft Windows) VerticalTabVertical tab character (not useful in Microsoft Windows QuoteQuotation mark character

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved 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.

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved Message Box - Multiple Buttons MessageBoxButtons.YesNo

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved 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

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved 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.

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved 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(HoursTextBox.Text) <= 10 Then ‘ Code to perform calculations…. Check for a required field (not blank). If NameTextBox.Text <> "" Then...

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved 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 you must use the word Is. Use the word To to indicate a range of constants.

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved Case Select Case TempInteger Case <= 32 CommentLabel.Text = “Freezing” Case <= 80 CommentLabel.Text = “Moderate” Case Else CommentLabel.Text = “Hot” End Select

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved Case Select Case TempInteger Case > 80 CommentLabel.Text = “Hot” Case > 32 CommentLabel.Text = “Moderate” Case Else CommentLabel.Text = “Freezing” End Select

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved End of Discussion

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved 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.

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved 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)

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved 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.

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved Debugging Tools Use Debug Menu and Debug options on VB Standard toolbar. Place Debug.WriteLine method in code. Set BreakPoints to stop at a particular location in code and watch what happens. Step Into, Step Over, Step Out Edit and Continue Locals Window, and Autos Window View the values of properties, variables, mathematical expressions, and conditions.

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved Debug Menu and Toolbar The debugging buttons on the VB standard toolbar The debugging options on the Debug menu showing the keyboard shortcut keys

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved Writing to the Immediate Window Debug.WriteLine(TextString) Debug.WriteLine(Object) Debug.WriteLine("calculateButton procedure entered") Debug.WriteLine(quantityTextBox)

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved Breakpoints Toggle Breakpoints On/Off by clicking in Editor's gray left margin indicator.

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved 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.

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved The Locals Window Shows values of local variables that are within scope of current statement

McGraw-Hill© 2009 The McGraw-Hill Companies, Inc. All rights reserved Autos Window Automatically adjusts to show variables and properties that appear in previous and next few lines