Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 4 Decisions and Conditions."— Presentation transcript:

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

2 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-2 Chapter Objectives - 1 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 Boolean expressions using the relational or comparison operators Combine expressions using logical operators && (and), || (or), and ! (not) Test the Checked property of radio buttons and check boxes

3 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-3 Chapter Objectives - 2 Perform validation on numeric fields using if statements Use a switch structure for multiple decisions Use one event handler to respond to the events for multiple controls Call an event handler from other methods 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

4 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-4 if Statements - 1 A decision made by the computer formed as a question If the condition is true –Do one thing If the condition is false –Do something else if the sun is shining (condition) go to the beach (action to take if condition is true) else go to class(action to take if condition is false)

5 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-5 if Statements - 2 In an if statement –When the condition is true Only the statement following the if is executed –When the condition is false Only the statement following the else clause, if present, is executed Use braces to include multiple statements in the if or else portion of statement Always use braces –Good programming practice

6 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-6 if Statement – General Form Condition to test is placed in parentheses if and else statements do not have semicolons –A semicolon terminates the statement –Any statement following the semicolon executes unconditionally Indent for readability and clarity if (condition) { // Statement(s) } [else { // Statement(s) }]

7 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-7 if Statement - Examples Type an if statement –Press Enter Editor places insertion point on blank line, indented Multiple statements must be in braces –Editor places braces directly under if or else statements unitsDecimal = decimal.Parse(unitsTextBox.Text); if (unitsDecimal < 32m) { freshmanRadioButton.Checked = true; } else { freshmanRadioButton.Checked = false; }

8 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-8 Charting if Statements A Uniform Modeling Language (UML) activity diagram is a useful tool for showing the logic of an if statement Helps to organize thoughts and design projects more quickly UML includes several types of diagrams –Activity diagram is a visual planning tool for decisions and actions for an entire application or a single method

9 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-9 Boolean Expressions - 1 The test in an if statement is based on a Boolean expression (condition) Use relational (comparison) operators –Comparison is evaluated to either true or false Formed with variables, constants, object properties and arithmetic expressions Must be made on like data types –i.e. Strings to strings or numeric value to numeric value

10 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-10 Boolean Expressions - 2 The Relational Operators SymbolRelation testedExamples >greater than decimal.Parse(amountTextBox.Text > limitDecimal correctInteger > 75 <less than int.Parse(salesTextBox.Text) < 10000 saleDecimal < limitDecimal ==equal to passwordTextBox.Text == “101” nameTextBox.Text == nameString !=not equal to freshmanRadioButton.Checked != true nameTextBox.Text != “” >=greater than or equal toint.Parse(quantityTextBox.Text) >= 500 <=less than or equal tocountInteger <= maximumInteger

11 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-11 Comparing Numeric Variables and Constants Algebraic comparisons are used –Sign of the number is taken into account –2 is less than –1 Use two equal signs to test for equality ( == ) if (decimal.Parse(priceTextBox.Text) == maximumDecimal) A single equal sign (=) means replacement in an assignment statement –Generates a compiler error if used in a comparison

12 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-12 Comparing Character Data - 1 Use relational operators to compare data stored in char data type –C# stores characters using 16-bit Unicode –Latin alphabet, numerals, punctuation have same values in ANSI code as Unicode –ANSI has established order (collating sequence) A char variable can be compared to –A literal, another char variable, an escape sequence or the code number

13 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-13 Comparing Character Data - 2 Compare char variable to a literal –Enclose char literal in single or double quotes –Compares to the value of the literal –Without quotes compares to code number (from ANSI code chart) (sexChar == ‘F’) //Compare to the uppercase letter ‘F’. (codeChar != ‘\0’) //Compare to a null character (character 0). (codeChar == ‘9’) //Compare to the digit 9. (codeChar == 9) //Compare to the ANSI code 9 (Tab char).

14 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-14 Comparing Strings Compare strings with equal to (==) and not equal to (!=) operators Comparison starts at leftmost character, proceeds one character at a time As soon as one character is not equal to the corresponding character –Comparison is terminated –Boolean expression returns false

15 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-15 The CompareTo Method Tests for less than or greater than aString.CompareTo(bString) –Returns zero if the strings are equal –Returns a positive number if aString is greater than bString –Returns a negative number if bString is greater than aString if (aString.CompareTo(bString) > 0) //Is aString > than bString?

16 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-16 Testing for True or False Shortcuts when testing for true or false C# evaluates expression in if statement If condition is a Boolean variable or property, it holds true or false values if (blueRadioButton.Checked == true) is equivalent to if (blueRadioButton.Checked)

17 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-17 Comparing Uppercase and Lowercase Characters String comparisons are case sensitive –Uppercase “Y" is not equal to lowercase “y" User input may be uppercase, lowercase, or a combination To compare uppercase and lowercase characters –Convert user input to all uppercase or all lowercase Use ToUpper and ToLower methods of the string class to convert Compare to the correct case of the literal if (nameTextBox.Text.ToUpper() == "PROGRAMMING") { // Do something. }

18 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-18 Compound Boolean Expressions Test more than one condition by joining conditions with logical operators Logical Operator MeaningExample || (or) If one expression or both expressions are true, the entire expression is true int.Parse(numberLabel.Text) == 1 || int.Parse(numberLabel.Text) == 2 && (and) Both expressions must be true for the entire expression to be true int.Parse(numberTextBox.Text > 0 && int.Parse(numberTextBox.Text) < 10 ! (not) Reverses the Boolean expression so that a true expression will evaluate false and vice versa ! foundBool

19 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-19 Combining Logical Operators When combining logical operators –Can use multiple && and || operators –If both && and || are used, && is evaluated before || –Change the order of evaluation with parentheses if (saleDecimal > 1000.0m || discountRadioButton.Checked && stateTextBox.Text.ToUpper() != "CA") { //Code here to calculate the discount. }

20 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-20 Short-Circuit Operations When evaluating a compound Boolean expression, the second condition may short- circuit (not be evaluated) –There is no need to evaluate the second expression if the first expression has an || and evaluates true the first expression has an && and evaluates false To force the second comparison to be made, use a single comparison operator: –& (and) –| (or)

21 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-21 Nested if Statements An if statement that contains additional if statements Nest ifs in the true block Nest ifs in the else block –Code is simpler when else if is used if statements can be nested as deeply as desired –Projects are difficult to follow and may not perform correctly when ifs are too deeply nested

22 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-22 Coding an else if To nest in the else statement, use else if (on one line), or as two separate statements if (tempInteger <= 32) { commentLabel.Text = "Freezing"; } else if (tempInteger > 80) { commentLabel.Text = "Hot"; } else { commentLabel.Text = "Moderate"; } if (tempInteger <= 32) { commentLabel.Text = "Freezing"; } else { if (tempInteger > 80) { commentLabel.Text = "Hot"; } else { commentLabel.Text = "Moderate"; } Note that the indentation changes when else if is on one line.

23 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-23 Using if Statements with Radio Buttons and Check Boxes Use if statements instead of taking action in CheckedChanged event handlers Use if statements to determine which options are selected Make programs consistent with standard Windows applications –Place code in Click event handlers of buttons i.e. OK or Apply button

24 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-24 Checking the State of a Radio Button Group To check the state of multiple radio buttons, use a nested if in a button’s click event handler if (freshmanRadioButton.Checked) { freshmanCountInteger++; } else if (sophmoreRadioButton.Checked) { sophomoreCountInteger++; } else if (juniorRadioButton.Checked) { juniorCountInteger++; } else if (seniorRadioButton.Checked) { seniorCountInteger; } Only one radio button can be selected at a time.

25 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-25 Changing and Testing Radio Buttons When one button’s checked property is true, all others are automatically set to false –Use this fact to easily clear a set of radio buttons Add an extra button to the group –Set Visible property to false –To clear visible buttons, set Checked property of the invisible radio button to true –Use to verify through code that user has made a selection Test Checked property of invisible radio button

26 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-26 Checking the State of Multiple Check Boxes To test the state of multiple check boxes, use separate if statements –Any number of boxes can be selected if (discountCheckBox.Checked) { // Calculate the discount. } if (taxableCheckBox.Checked) { // Calculate the tax. } if (deliveryCheckBox.Checked) { //Calculate the delivery charges. {

27 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-27 Enhancing Message Boxes Control the format of the message Display multiple buttons –Check to see which button the user clicked –Perform alternate actions depending on the user’s selection

28 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-28 Displaying the Message String Message string displayed in a message box can be –A string literal (enclosed in quotes) –A string variable Create a variable for the message Format the message Call the Show method –Above three steps make code easier to read and follow

29 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-29 Combining Values into a Message String Concatenate a literal and the value from a variable –Include an extra space inside the literal to separate the variable’s value from the literal string messageString = “Total Sales: ” + totalDecimalSales.ToString(“C”); MessageBox.Show(messageString, “Sales Summary”, MessageBoxButtons.OK);

30 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-30 Creating Multiple Lines of Output - 1 Long messages wrap to a second line Insert a NewLine (\n) character in the string message string formattedTotalString = totalSalesDecimal.ToString("N"); string formattedAvgString = averageSaleDecimal.ToString("N"); string messageString = "Total Sales: " + formattedTotalString + "\n" + "Average Sale: " + formattedAvgString; MessageBox.Show(messageString, "Sales Summary", MessageBoxButtons.OK);

31 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-31 Creating Multiple Lines of Output - 2 Combine multiple NewLine constants for double spaced or multiple line messages // Concatenate the text for the message string summaryString = "Drinks Sold: " + drinksInteger.ToString() + "\n\n" + "Number of Orders: " + ordersInteger.ToString() + “n\n" + "Total Sales: " + totalSalesDecimal.ToString("C"); // Display the message box. MessageBox.Show(summaryString, "Juice Bar Sales Summary", MessageBoxButtons.OK, MessageBoxIcon.Information);

32 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-32 Using the Character Escape Sequences Other constants are available from the character escape sequence (\) list Escape SequenceDescription \' Includes a single quote in a character literal \" Includes a double quote in a string literal \\ Includes a backslash in a string literal \n New line \r Carriage return \b Backspace character \t Horizontal tab

33 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-33 Displaying Multiple Buttons Choose buttons to display in a message box using the MessageBoxButtons constants –Returns a DialogResult object

34 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-34 Declaring an Object Variable for the Method Return - 1 Capture information about the Show method’s outcome –Declare a variable to hold an instance of the DialogResult type DialogResult whichButtonDialogResult; –Assign the return value of the Show method to the new variable string messageString = "Clear the current order figures?"; whichButtonDialogResult = MessageBox.Show(messageString, "Clear Order", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

35 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-35 Declaring an Object Variable for the Method Return - 2 –Check the value of the return –Compare to the DialogResult constants Yes, No, Ok, Retry, Abort and Cancel if (whichButtonDialogResult == DialogResult.Yes) { // Code to clear the order. }

36 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-36 Specifying a Default Button and Options Two additional signatures for the MessageBox.Show method –Display multiple buttons and make one the default (the Accept button) –Right-Align text by setting MessageBoxOptions argument // Make the No button (Button2) the default button // and right-align the message. whichButtonDialogResult = MessageBox.Show(messageString, "Clear Order", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2, MessageBoxOptions.RightAlign);

37 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-37 Input Validation Validation – Checking to verify appropriate values have been input Validation may verify: –Input is numeric –A specific value –A range of values –Required items are entered

38 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-38 Checking for a Range of Values Check reasonableness of a value –Example – A company does not allow more than 10 hours to be worked in a single day if (int.Parse(hoursTextBox.Text) > 10) { MessageBox.Show("Too many hours.", "Invalid Data", MessageBoxButtons.OK); }

39 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-39 Checking for a Required Field - 1 Compare a text box value to an empty string if (nameTextbox.Text != “”) Test in an if statement, invalid entries caught in true portion if (nameTextBox.Text == “”) { MessageBox.Show(“Required entry.”, “Invalid Data”, MessageBoxButtons.OK); } else { //Good data - - Perform some action. }

40 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-40 Checking for a Required Field - 2 Check separately for blank or nonnumeric data –Display a meaningful message to the user –Check for blanks first, a blank field will throw an exception with a parsing method if (quantityTextBox.Text != "") // Not blank. { try quantityDecimal = decimal.Parse(quantityTextBox.Text); catch // Nonnumeric data. { messageString = "Nonnumeric data entered for quantity."; MessageBox.Show(messageString, "Data Entry Error"); } else // Missing data. { messageString = "The quantity is required."; MessageBox.Show(messageString, "Data entry error"); }

41 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-41 Performing Multiple Validations - 1 Avoid displaying multiple message boxes in a row Use a nested if statement Check second value only if first value passes test Exit processing if a problem is found with any field

42 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-42 Performing Multiple Validations - 2 if (nameTextBox.Text != "") { try { unitsDecimal = decimal.Parse(unitsTextBox.Text); if (freshmanRadioButton.Checked || sophomoreRadioButton.Checked || juniorRadioButton.Checked || seniorRadioButton.Checked) { // Data valid - - Do calculations or processing here. } else { MessageBox.Show(“Please select grade level.”, “Data Entry Error”, MessageBoxButtons.OK); } catch(FormatException) { //Display error message }

43 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-43 The switch Statement - 1 Provides flexible and powerful alternative to if statements for testing multiple conditions switch (expression) { case testValue1: [statement(s); break;] [ case testValue2: statements(s); break;] [default:] statements(s); break;] }

44 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-44 The switch Statement - 2 The test values must be the same data type as the expression There is no limit to the number of case blocks and no limit to the number of statements following each case statement default clause is optional, code executes only if no other case is matched The break statements for each case, including the default, are required Only the statements in the first matched case execute

45 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-45 Sharing an Event Handler - 1 Multiple controls can share an event-handling method Code an event-handling method Click the Events button in the Properties window Drop down the list for an event and select the previously written method

46 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-46 Sharing an Event Handler - 2 Radio button example –Write code in CheckedChanged event of one button of radio button group –Rename the method to reflect its purpose Right-click on method name in Code Editor and select Refractor/Rename –Set the method for every radio button in the group –Declare a class-level variable to hold selection –In OK button event-handling method, take action based on selection

47 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-47 Sharing an Event Handler - 3 Radio button example (cont.) –sender argument is passed to CheckChanged method, defined as a generic object –Cast sender to a RadioButton type to use its Name property –Use a switch statement to determine which radio button is selected

48 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-48 Calling Event Handlers Never duplicate code Write code once in an event-handling method –“Call” the method from another method by naming the method Entire method is executed Execution returns to statement following the call –Include parentheses, leave empty if no arguments –If method requires arguments, place arguments within parentheses

49 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-49 Debugging C# Projects Debugging tools help find and eliminate logic and run-time errors Follow program logic in Debug mode –Single-step through code –WriteLine method of Console class Debug toolbar and Debug menu contain debugging tools

50 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-50 Writing to the Output Window Place Console.WriteLine methods in code to display useful information without breaking program execution Console.WriteLine(“calculateButton method entered.”); Console.WriteLine(quantityTextBox); Console.WriteLine(“quantityInteger = ” + quantityInteger);

51 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-51 Pausing Execution with the Break All Button Click the Break All button on the Debug toolbar –Project enters Debugging mode at the current line Better to choose location of break –Force a break with a breakpoint

52 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-52 Forcing a Break - 1 Place mouse pointer in gray margin at left edge of the Editor window on a line of executable code –Click in margin and line is highlighted in red and a large red dot displays in margin Start execution, project will halt at breakpoint and go into debug mode Remove breakpoint by clicking on red dot or clear all breakpoints from the Debug menu

53 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-53 Forcing a Break - 2 Toggle breakpoints on/off by clicking in Editor’s gray left margin area Breakpoint

54 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-54 Checking the Current Values of Expressions Quickly check the current value of a variable, a control, a Boolean expression, or an arithmetic expression –Break execution using a breakpoint –Point to the name of the expression –Current contents of expression pop up in a small label called a DataTip, when the expression is in scope

55 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-55 Stepping through Code - 1 The best way to debug a project is to trace program execution line by line –Break execution with a breakpoint or choose a stepping command Step Into (F11) – Executes next line of code, continue stepping through code by repeatedly choosing Step Into command Step Over (F10) – Executes next line of code, displays only the lines of code in the current method being analyzed Step Out (Shift + F11) – Rapidly executes a called method, returns to debug mode at the statement following the call

56 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-56 Stepping through Code - 2 Continue Program Execution –Press F5 or choose Continue from the Debug toolbar or menu –Choose Restart to restart execution from beginning Stopping Execution –Press Shift + F5 or select Stop Debugging from the Debug toolbar or menu

57 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-57 Stepping through Code - 3 Edit and Continue –Stop execution, make minor modifications to the code, and continue execution without recompiling –If changes are too major, the debugger does not allow the changes Stop program execution, make the changes and recompile the program

58 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-58 The Locals Window Displays all objects and variables within scope at debug time Display Locals window from the toolbar or the Debug/Windows/Locals menu Expand the "this" entry to see state of form’s controls and the values of class-level variables

59 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 4-59 The Autos Window Automatically displays all variables and control contents referenced in current statement –Also displays a few statements on either side of the current statement Autos window available when program stops at a breakpoint Select Locals or Autos tab in the debugging window


Download ppt "McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 4 Decisions and Conditions."

Similar presentations


Ads by Google