Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 Decisions and Conditions Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.

Similar presentations


Presentation on theme: "Chapter 4 Decisions and Conditions Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved."— Presentation transcript:

1 Chapter 4 Decisions and Conditions Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.

2 4- 2 Objectives Use if statements to control the flow of logic Understand and use nested if statements Read and create flowcharts indicating the logic in a selection process Evaluate conditions using the relational operators Combine conditions using && (and) and || (or) operators

3 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 3 Objectives cont. Test the Checked property of radio buttons and check boxes Perform validation on numeric fields using if statements Use a case structure for multiple decisions Use one event handler to respond to the events for multiple controls and determine which control caused the event

4 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 4 Objectives cont. Call event handlers 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

5 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 5 if Statements A decision made by the computer is formed as a question: Is a given condition true or false? If it is true, do one thing; if it is false, do something else. Sun is shining? Go to classGo to beach false true

6 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 6 if Statements cont. Use block (braces) to include multiple statements in the if or else portion of an if statement Only the first statement following an if or else is considered part of statement unless braces are used if and else do not have semicolons Statements under the if and else clauses are indented

7 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 7 if/else Statement–General Form if (condition) { statement(s); } if (condition) { statement(s); } else { statement(s); } if (condition) { statement(s); } [else if (condition) { statement(s); }] [else { statement(s); }]

8 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 8 The if/else Statement - Example decUnits = decimal.Parse(unitsTextBox.Text); if (decUnits < 32.0M) { freshmanRadioButton.Checked = true; } else { freshmanRadioButton.Checked = false; }

9 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 9 Flowcharting if Statements Flowcharts help programmers organize thoughts and design projects more quickly Diamond-shape is a decision symbol Decision Process false true

10 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 10 Conditions C# provides six relational operators Results of a comparison is true or false Conditions can be formed with variables, constants, object properties, and expressions Comparisons must be made on like types –Compare strings with strings –Compare numeric values with numeric values

11 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 11 Relational Operators SymbolRelation Tested Examples >Greater thandecimal.Parse(amountTextBox.Text)>decLimit inCorrect > 75 <Less thanint.Parse(salesTextBox.Text) < 10000 decSales < decQuota = Equal topasswordTextBox.Text = = “101” decBalance = = decGoal !=not equal tofreshmanRadioButton.Checked != true nameTextBox.Text != “” >=greater than or equal to int.Parse(quantityTextBox.Text) >= 500 decInterestRate >= decMaxRate <=less than or equal to intTotal <= intLimit decQuantity <= OM

12 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 12 Comparing Numeric Variables and Constants Comparison of numeric values uses the sign of the numbers Equals sign (=) is an assignment statement Double equal sign (= =) is used to test for equality

13 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 13 Comparing Character Data Use relational operators to compare character data ANSI establishes an order (collating sequence) for all letters, numbers, and special characters by assigning codes Compare a char variable to a literal, to another char variable, an escape sequence, or the code number

14 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 14 Comparing Strings Cannot use relational operators when comparing strings To be equal, two strings must be exactly the same, including capitalization Use String.Compare or String.CompareTo methods to compare strings for less than or greater to

15 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 15 Comparing Uppercase and Lowercase Characters C# is case sensitive i.e. “y” is not equal to “Y” To compare strings, use ToUpper and ToLower methods of the string class TextString.ToUpper() TextString.ToLower() Example: aTextBox.Text valueRichard aTextBox.Text.ToUpper() value RICHARD aTextBox.Text.ToLower() valuerichard

16 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 16 Testing for true or false Use shortcuts when testing for true or false if (blnSuccessfulOperation = = true) is equivalent to if (blnSuccessfulOperation) if (radBlue.Checked) is equivalent to if (radBlue.Checked = = true)

17 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 17 Compound Conditions Use compound conditions to test more than one condition Use logical operators to join conditions Logical operators are || (or), && (and), and ! (not) Each side of the logical operator must be a complete condition

18 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 18 Compound Conditions cont. Logical Operator Meaning || (or)If one condition or both conditions are true, the entire condition is true && (and)Both conditions must be true for the entire condition to be true ! (not)Reverses the condition so that a true condition will evaluate false and vice versa

19 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 19 Compound Condition Examples if (maleRadioButton.Checked && int.Parse(ageTextBox.Text) < 21) { intMinorMaleCount ++: } if (juniorRadioButton.Checked || seniorRadioButton.Checked) { intUpperClassmanCount ++; }

20 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 20 Combining && and || If there is an && and an ||, the && is evaluated before the || You can change order of evaluation using parentheses; condition inside parentheses will be evaluated first

21 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 21 Short-Circuit Operations When evaluating a compound condition, sometimes the second condition is never evaluated –In an || condition, if the first condition is true, the second condition is not evaluated –In an && condition, if the first condition is false, the second condition is not evaluated This is called short circuiting the operation

22 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 22 Short-Circuit Operations cont. And-Short CircuitAnd-RegularOr-Short CircuitOr-Regular && (Forces comparison to occur) & || (Forces comparison to occur) | Use a single comparison operator to avoid short circuiting

23 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 23 Nested if Statements An if statement that contains additional if statements is a nested if statement You can nest if statements in the else portion of the statement You can nest if s within if s as long as you want Project may become difficult to follow and may not perform as intended when if s are too deeply nested

24 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 24 Nested if Example if (intTemp > 32) { if (intTemp > 80) { commentLabel.Text = “Hot”; } else { commentLabel.Text = “Moderate”; } else { commentLabel.Text = “Freezing”; }

25 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 25 Nested if Flowchart Example maleRadioButton.Checked? ageTextBox.Text<21? Add 1 to intMinorMaleCount Add 1 to intMaleCount Add 1 to intMinorFemaleCount Add 1 to intFemaleCount FalseTrue FalseTrueFalseTrue

26 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 26 Coding an else if The second (nested) if can be placed on a line by itself or on the same line as the else The indentation changes if else if is on one line Most programmers code else if on one line when testing multiple conditions

27 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 27 Coding an else if example if (maleRadioButton.Checked) { if (int.Parse(ageTextBOx.Text) < 21) { intMinorMaleCount ++; } else { intMalecount ++; } else if (int.Parse(ageTextBox.Text) < 21) { intMinorFemaleCount ++; } else { intFemaleCount ++ ; }

28 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 28 Using if Statements with Radio Buttons and Check Boxes Place code in button Click event to check for selected options A “Simple Sample” –Test the Value of a Check Box if (testCheckBox.Checked) { messageLabel.Text = “Check box is checked”; }

29 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 29 Using if Statements with Radio Buttons and Check Boxes cont. A “Simple Sample” cont. –Test the State of Radio Buttons if (freshmanRadioButton.Checked) { messageLabel.Text = “Freshman”; } else { messageLabel.Text = “Sophomore”; }

30 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 30 Checking the State of a Radio Button Group if (freshmanRadioButton.Checked) { intFreshmanCount ++; } else if (sophomoreRadioButton.Checked) { intSophomoreCount ++; } else if (juniorRadioButton.Checked) { intJuniorCount ++; } else { intSeniorCount ++; }

31 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 31 Checking the State of Multiple Check Boxes if (discountCheckBox.Checked) { //Calculate the discount } if (taxCheckBox.Checked) { //Calculate the tax } if (deliveryCheckBox.Checked) { //Deliver it }

32 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 32 Enhancing Message Boxes Control the format of the message Display multiple buttons Check which button the user clicks Perform alternate actions depending on the user selection

33 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 33 Displaying the Message String Message string can be a string literal enclosed in quotes or a string variable May also concatenate several items Create a variable for the message Call the Show method to display the message

34 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 34 Combining Values into a Message String Concatenate a literal with the value from a variable Example: string strMessage; strMessage=“Total Sales: “ + decTotalSales.ToString(“C”); MessageBox.Show(strMessage, “Sales”, MessageBoxButtons.OK);

35 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 35 Creating Multiple Lines of Output Control the line length and position of the split by inserting a new line (\n) character into the string message Combine multiple new line characters for double spacing Example: string strMessage; strMessage=“Total Sales: “ + decTotalSales.ToString(“C”) + “\nAverage Sale: “ + decAverageSale.ToString(“C”); MessageBox.Show(strMessage, “Sales”, MessageBoxButtons.OK);

36 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 36 Displaying Multiple Buttons Use the MessageBoxConstants to choose buttons to display on the message box The Show method returns a DialogResult object Click on Show and press F1 for list of return types, or point to Show and pause

37 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 37 Declaring an Object Variable for the Method Return Declare a variable to hold an instance of the DialogResult type Assign the return value of the Show method to the new variable Check the value of the return and compare to the DialogResult constants

38 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 38 Specifying a Default Button and Options Specify which button is the default (the accept button) with the MessageBoxDefaultButton argument Make a message appear right-aligned with the MessageBoxOptions argument

39 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 39 Input Validation It is better to find and reject bad data early in a program Validation is checking to verify that appropriate values have been provided as input –Make sure data are numeric –Check for specific values –Check a range of values –Make sure required items are entered

40 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 40 Checking for a Range of Values Check the reasonableness of a value Example: if (int.Parse(hoursTextBox.Text) > 10) MessageBox.Show(“Too many hours”,”Invalid Data”, MessageBoxButtons.OK);

41 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 41 Checking for a Required Field Compare a text box value to an empty string literal Check separately for blank or nonnumeric data Check for blanks first

42 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 42 Performing Multiple Validations Use a nested if statement to check several input boxes This will check the second box only if the first passes You can exit the validation processing as soon as a problem is found with a single field

43 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 43 The Case Structure Use the case structure to test a single variable for multiple values In C#, code the case structure with the switch statement Decisions coded with a switch statement can also be coded with nested if statements although the switch statement is simpler and clearer

44 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 44 Switch Statement – General Form switch (expression) { case ConstantList: [Statement(s); break;] [case ConstantList: Statement(s); break;]. [default:] [Statement(s); break;] }

45 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 45 switch Statement cont. The expression in a case structure is a variable or a property to be tested The constant list is the value you want to match, and may be a numeric or string constant There is no limit to the number of statements following a case statement A break must appear after all of the statements for a case statement

46 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 46 The switch Statement - Example switch (intListIndex) { case 0: HandleItemZero(); break; case 1: HandleItems(); break; default: HandleNoSelection(); break; }

47 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 47 The switch Statement cont. To test for a string value, include quotation marks around the literals Capitalization in strings must match exactly The default clause is optional although recommended If no default clause and no case conditions are true, program continues execution at statement following the switch block If more than one case value matches expression, only the first matching case clause executes

48 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 48 Sharing an Event Handler C# allows sharing of an event-handling method for several controls To share an event-handling method among several radio buttons: 1.Double-click on one radio button to create event handler for that button 2.Select another radio button and click on the Events button in Properties window 3.Select an existing method from the drop-down list

49 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 49 Sharing an Event Handler cont. Setup a class-level variable to hold user selection Use the sender argument that is passed to the CheckedChanged method Cast sender to the object type then use its Name property in a switch statement

50 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 50 Sharing an Event Handler - Example Color colorNew; //Declare class-level variable private void blueRadioButton_CheckedChanged(object sender, System.EventArgs e) { RadioButton selectedRadioButton = (radioButton) sender; switch (selectedRadioButton.Name) { case “blueRadioButton”: colorNew = Color.Blue; break; case “redRadioButton”: colorNew = Color.Red; break; } private void okButton_Click(object sender, System.EventArgs e) { this.BackColor = colorNew; //Change the color based on selected radio button }

51 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 51 Calling Event Handlers Write instructions once, in a method, then call that method from another method When you call a method, the entire method is executed then execution returns to the statement following the call General form is MethodName (); Must include the parentheses, even if they are empty

52 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 52 Calling Event Handlers cont. Every event handler requires same two arguments (sender, e) private void summaryButton_Click(object sender, System.EventArgs e) { //... newOrderButton_Click(sender, e); //Call the newOrderButton_Click //event-handling method }

53 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 53 Your Hands-On Programming Example Create a project for R ‘n R – for Reading ‘n Refreshment that calculates the amount due for individual orders and maintains accumulated totals for a summary. Have a check box for takeout items, which are taxable at 8 percent; all other orders are nontaxable. Include radio buttons for the five coffee selections – Cappuccino, Espresso, Latte, Iced cappuccino, and Iced Latte. The prices for each will be assigned as constants.

54 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 54 Your Hand-On Programming Example cont. Use a button for Calculate Selection, which will calculate and display the amount due for each item. Display appropriate error messages for missing or nonnumeric data. A button for Clear for Next Item will clear the selections and amount for the current item. Additional labels in a separate group box will display the summary information for the current order, including subtotal, tax, and total.

55 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 55 Your Hand-On Programming Example cont. Buttons at the bottom of the form will be used for New Order, Summary, and Exit. The New Order button will confirm that the user wants to clear the current order. If the user agrees, clear the current order and add to the summary totals. The Summary button should display a message box with the number of order, the total dollar amount, and the average sale amount per order.

56 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 56 Debugging C# Projects Visual Studio.NET provides many debugging tools to find and eliminate logic and run-time errors Follow program logic in Break mode by single-stepping through code Use the WriteLine method of the Console class Debugging tools are found on the Debug toolbar and Debug menu

57 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 57 Writing to the Output Window Use the Console.WriteLine method in code The Console.WriteLine argument specifies a message to write or an object to track General form Console.WriteLine(TextString); Console.WriteLine(Object); Output of Console.WriteLine method appears in Output window Using Console.WriteLine does not have to break program execution

58 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 58 Pausing Execution with a Break Click on the Break button to pause execution Insert a breakpoint in code –Place mouse pointer in gray margin indicator area at left edge of Editor window and click –Line will be highlighted in red and large red dot will display in margin indicator –Start execution; When program reaches breakpoint, it will halt and go into break time –Remove breakpoint by clicking on red dot in gray margin area or using Debug menu to clear all break points

59 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 59 Checking the Current Values of Expressions During break time –Point to name of expression or highlighted area in the Editor window During run time –Break the execution –Display code in the Editor –Point to the variable or expression to view Current contents of expression appear in pop up label

60 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 60 Stepping through Code Step through code at break time Stepping commands –Step Into –Step Over –Step Out Stepping commands for project execute one line at a time and display the Editor window with the current statement highlighted

61 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 61 Step Into When selected, the next line of code executes and the program pauses again in break time To continue stepping through program execution, continue choosing Step Into command Code will step into any called methods Choose the Continue command to continue execution without stepping

62 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 62 Step Over and Step Out Step Over executes code one line at a time in break time, similar to Step Into Step Over does not display lines of code in any called methods Step Out continues rapid execution until called method completes, then returns to break mode at statement following the Call

63 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 63 Continuing and Stopping Program Execution Press F5 or choose Continue from Debug toolbar or menu to continue rapid execution of program To restart program execution from beginning, choose Restart command Stop execution by pressing Shift + F5, or by selecting Stop Debugging from the Debug toolbar or menu

64 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 64 The Locals and Autos Windows The Locals window displays all objects and variables within scope at break time The Autos window “automatically” displays all variables and control contents that are referenced in the current statement and the three statements on either side of the current one

65 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 65 Debugging Step-by-Step Tutorial In this exercise you will learn to set a breakpoint; pause program execution; single step through program instructions; display the current values in properties, variables, and conditions; and debug a C# program. 1.Test the Project 2.Break and Step Program Execution 3.View the Contents of Properties, Variables, and Conditions 4.Continue Program Execution 5.Test the White Total 6.Correct the Red Total Error 7.Correct the White Total 8.Test the Corrections

66 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 66 Summary C# uses the if / else statement to make decisions. Flowcharts can help visualize the logic of an if / else statement. The conditions for an if statement are evaluated for true or false. Conditions can be composed of the relational operators, which compare numeric items for equality, greater than, or less than.

67 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 67 Summary cont. Conditions can be created using strings and the relational operators = = and != (equal and not equal). The ToUpper and ToLower methods of the String class convert a text value to upper- or lowercase. The && (and) and || (or) operators may be used to combine multiple conditions. A nested if statement contains an if statement within either a true or false action of a previous if statement.

68 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 68 Summary cont. The state of radio buttons and check boxes should be tested with if statements in the event handler of a button. The MessageBox.Show method can display multiline message with the new line (\n) character. You can display multiple buttons on a message box and check selection using DialogResult. Data validation checks the reasonableness or appropriateness of the value in a variable or property.

69 © 2003 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 69 Summary cont. You can assign an event-handling method to a control in the Properties window. You can use the sender argument in an event- handling method to determine which control caused the method to execute. One method can call another method. A variety of debugging tools are available in Visual Studio including writing to the Output window, breaking program execution, displaying contents of variables, and stepping through code.


Download ppt "Chapter 4 Decisions and Conditions Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved."

Similar presentations


Ads by Google