1 / 34

Chapter 5: Decision

Chapter 5: Decision. Visual Basic.NET. Objectives. Understand relational and logical operators and use them in logical expressions Code the If block structure to solve various programming problems that involve decisions Appreciate and design various alternatives to the If block

buffy
Télécharger la présentation

Chapter 5: Decision

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 5:Decision Visual Basic.NET CSC110 Fall 2004

  2. Objectives • Understand relational and logical operators and use them in logical expressions • Code the If block structure to solve various programming problems that involve decisions • Appreciate and design various alternatives to the If block • Understand and use the Select Case block structure CSC110 Fall 2004

  3. Logical Expressions • If statement has simple syntax: • If Condition Then Statement • Condition: an expression that can be evaluated as true or false • Statement: a VB statement CSC110 Fall 2004

  4. Relational Operators • Used to compare operands and decide if the relationship is true • Examples include =, >, and <= • With string data, “a” is greater than “A” • To make comparison case insensitive, set Option Compare to “Text” • Set in code with Option Compare Text statement • Set as default in properties page for project • Logical expression can be part of assignment statement • Left side of expression must be a variable or a property of a control that can be set to True or False CSC110 Fall 2004

  5. Logical Operators • Compares two or more expressions and returns appropriate value • Not operator negates operand on its right • And operator returns True when all expressions are True • Or operator returns True if one or more expressions are True CSC110 Fall 2004

  6. Order of Operations • If a1 <= a2 or a3 > a4 and a5 < a6 Then • And has precedence over Or • All comparison operators have precedence over all logical operators • Use parentheses to alter the order of evaluation CSC110 Fall 2004

  7. The If Block • Similar to If statement, but statements to be executed are not on same line as If keyword • Allows you to execute more than one statement if condition is True • Terminated with End If statement CSC110 Fall 2004

  8. Adds an Else clause Contains statements to be executed if the condition is False Terminated with End If keyword Either clause can be left blank Often used for statements that will be carried out only if condition is False The If…Then…Else…End If Block • If chkSort.Checked Then • cboSort.Enabled = True • Else • cboSort.Enabled = False • End If CSC110 Fall 2004

  9. Used when a decision depends on several conditions ElseIfkeyword used to define each condition Often has a “catch-all” Else clause Terminated with End If If…Then…ElseIf…Then…Else…End If Block ElseIf Clause also contains Then keyword • If Score >= 90 Then • Grade = “A” • ElseIf Score >=80 Then • Grade = “B” • Else • Grade = “C” • End If CSC110 Fall 2004

  10. If Statement Considerations • Varying conditions • The ElseIf block is useful when conditions vary • Conditions can be based on entirely different factors • Nesting If Blocks • Using another If block in either the Then clause or the Else clause • Nested block must be terminated before returning to the outer block • Indent each nested block to enhance readability • Use comments liberally • Especially for nested If blocks CSC110 Fall 2004

  11. "If" statement and option buttons CSC110 Fall 2004

  12. Messages in Message boxes • Special window displaying message to user • Form: MsgBox “message” [,buttons][, “t.b. caption”] • Example: MsgBox “Numeric ID only”, vbOkOnly, “Error” CSC110 Fall 2004

  13. Displaying a Message String • Use & to concatenate strings (“Concatenate” means join end to end) • The VB intrinsic constant vbCRLF creates a new line in a string MsgBox strMessage, vbOKOnly, stTitle CSC110 Fall 2004

  14. Message box return values Constant Value Description vbOK 1 OK button pressed. vbCancel 2 Cancel button pressed. vbAbort 3 Abort button pressed. vbRetry 4 Retry button pressed. vbIgnore 5 Ignore button pressed. vbYes 6 Yes button pressed. vbNo 7 No button pressed. CSC110 Fall 2004

  15. Input Validation • Checking a data type: IsNumeric & IsDate • IsNumeric checks & returns true or false If IsNumeric(txtQty.Text) Then lblDue.Caption = curPrice + CInt(txtQty.text) • Validating value ranges If Val(txtHours.Text) > 10 And _ Val(txtHours.Text) <= 80 Then ... CSC110 Fall 2004

  16. Data Validation • IsDate returns true or false depending on whether or not a value is a date If IsDate(txtData.text) Then … • the VarType function return a number that corresponds to the data type stored in a variant. If VarType(varValue) = 0 Then... CSC110 Fall 2004

  17. Calling Event Procedures • An event procedure is a subprocedure that reacts to a specific event such as a button click. • You can call any given event procedure from multiple locations, as long as the procedure is in the same form or is public • Example: Call cmdCalculate_Click • Suffix is event, prefix is object name CSC110 Fall 2004

  18. Hands on Programming Example CSC110 Fall 2004

  19. Select Case Block • Useful when decision depends on different results of the same expression • Begins with Select Case statement • Each condition coded with Case criterion • Should have “catch all” Case Else clause • Terminated with End Selectstatement • Criteria are mutually exclusive • Once a criterion is found to be true, that block is executed • Place most restrictive criterion at top CSC110 Fall 2004

  20. Syntax Rules • To test for equality, give the value, • i.e. Case 80 • To test several values for equality, separate list with commas, • i.e. Case 80, 81, 85 • To specify a closed range, insert the “To” keyword between upper and lower bounds • i.e. Case 80 to 90 • To specify an open range, use the “Is” keyword • i.e. Case Is < 0 CSC110 Fall 2004

  21. Nesting Select Case Blocks • Similar to nesting If blocks • Nested blocks must terminate before returning to outer block • Make extensive use of comments CSC110 Fall 2004

  22. If Statement Nested Inside Select Case Statement If block is terminated before returning to Select Case block CSC110 Fall 2004

  23. Application Example:Tuition Calculator • Analyze and determine system requirements • Calculate student tuition • Based on residence status and hours taken • Design visual interface • Need controls for hours taken and residence • Use radio buttons for status, since limited number of options that won’t change • Use text box for hours taken CSC110 Fall 2004

  24. Visual Interface Checked property of In State radio button set to true to create Default Tuition displayed in label, formatted to look like text box CSC110 Fall 2004

  25. Code Solution Select Case with If then Blocks CSC110 Fall 2004

  26. Code solution Nested Select Case CSC110 Fall 2004

  27. An Alternative Solution • Use combo boxes to display residence status and range of hours taken • Offers more flexibility, but code is not as clear CSC110 Fall 2004

  28. Visual Interface Items added to combo box at runtime; SelectedIndex property used to set default value CSC110 Fall 2004

  29. Code the Solution SelectedIndex property used to determine which option is selected CSC110 Fall 2004

  30. Block Level Declarations • Variables may be declared inside a block • Variables exist only inside the block • You may declare the same variable name inside each block • i.e. a variable named ID may be declared in the If block, the ElseIf block, and Else block • While you can do this, it is confusing to read and debug • You may not declare a variable name if you have declared a module-level variable with same name CSC110 Fall 2004

  31. Summary • Two structures commonly used to handle decisions: If and Select Case • If structure involves testing whether the condition following If keyword is True or False • Relational operators include =, <>, and <. Each compares two operands to determine if relation is True • Commonly used logical operators include And, Or, and Not CSC110 Fall 2004

  32. Summary If Block • If operational precedence is confusing, use parentheses to encloses expression(s) • Four ways to construct If structure • Simple If statement • Simple If block • If…Else block • If…ElseIf…Else block • If blocks can be nested CSC110 Fall 2004

  33. Summary • Use comments to explain the purpose of the condition • Computer evaluates logical or relational expressions differently than we might interpret them • String comparisons can be “Binary” (case sensitive) or “Text” (case insensitive) • A < a “Cat” < “cat” CSC110 Fall 2004

  34. Summary Select Case • Select Case structure can replace If…ElseIf block when decision depends on the result of a single expression • Select Case structure can be nested and can also be nested with If structure • Tuition calculation example illustrates how Select Case structure can be nested • You can declare block level variables in both the If blocks and the Case blocks CSC110 Fall 2004

More Related