CSC110 Fall 20041 Chapter 5: Decision Visual Basic.NET.

34
CSC110 Fall 2004 1 Chapter 5: Chapter 5: Decision Decision Visual Basic.NET Visual Basic.NET
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    223
  • download

    3

Transcript of CSC110 Fall 20041 Chapter 5: Decision Visual Basic.NET.

CSC110 Fall 2004 1

Chapter 5:Chapter 5:DecisionDecision

Visual Basic.NETVisual Basic.NET

2CSC110 Fall 2004

ObjectivesObjectives

Understand relational and logical operators and Understand relational and logical operators and use them in logical expressionsuse them in logical expressions

Code the If block structure to solve various Code the If block structure to solve various programming problems that involve decisionsprogramming problems that involve decisions

Appreciate and design various alternatives to the Appreciate and design various alternatives to the If blockIf block

Understand and use the Select Case block Understand and use the Select Case block structurestructure

3CSC110 Fall 2004

Logical ExpressionsLogical Expressions

If statement has simple syntax:If statement has simple syntax:– If If ConditionCondition Then Then StatementStatement

» Condition: an expression that can be evaluated as Condition: an expression that can be evaluated as true or falsetrue or false

» Statement: a VB statementStatement: a VB statement

4CSC110 Fall 2004

Relational OperatorsRelational Operators

Used to compare operands and decide if the relationship is Used to compare operands and decide if the relationship is truetrue– Examples include =, >, and <=Examples include =, >, and <=

With string data, “a” is greater than “A”With string data, “a” is greater than “A”– To make comparison case insensitive, set To make comparison case insensitive, set Option CompareOption Compare to to

“Text”“Text”» Set in code with Set in code with Option Compare TextOption Compare Text statement statement» Set as default in properties page for projectSet as default in properties page for project

Logical expression can be part of assignment statementLogical expression can be part of assignment statement– Left side of expression must be a variable or a property of a Left side of expression must be a variable or a property of a

control that can be set to True or Falsecontrol that can be set to True or False

5CSC110 Fall 2004

Logical OperatorsLogical Operators

Compares two or more expressions and Compares two or more expressions and returns appropriate valuereturns appropriate value– NotNot operator negates operand on its right operator negates operand on its right

– AndAnd operator returns True when all expressions operator returns True when all expressions are Trueare True

– OrOr operator returns True if one or more operator returns True if one or more expressions are Trueexpressions are True

6CSC110 Fall 2004

Order of OperationsOrder of Operations

If a1 <= a2 or a3 > a4 and a5 < a6 ThenIf a1 <= a2 or a3 > a4 and a5 < a6 Then AndAnd has precedence over has precedence over OrOr All comparison operators have precedence All comparison operators have precedence

over all logical operatorsover all logical operators Use parentheses to alter the order of Use parentheses to alter the order of

evaluationevaluation

7CSC110 Fall 2004

The If BlockThe If Block

Similar to If statement, but statements to Similar to If statement, but statements to be executed are not on same line as If be executed are not on same line as If keywordkeyword– Allows you to execute more than one Allows you to execute more than one

statement if condition is Truestatement if condition is True Terminated with End If statementTerminated with End If statement

8CSC110 Fall 2004

The If…Then…Else…End If The If…Then…Else…End If BlockBlock

Adds an Adds an ElseElse clause clause– Contains statements to be Contains statements to be

executed if the condition is executed if the condition is

FalseFalse Terminated with Terminated with End IfEnd If

keywordkeyword Either clause can be left Either clause can be left

blankblank– Often used for statements that Often used for statements that

will be carried out only if will be carried out only if condition is Falsecondition is False

If chkSort.Checked Then

cboSort.Enabled = True

Else

cboSort.Enabled = False

End If

9CSC110 Fall 2004

If…Then…ElseIf…Then…Else…If…Then…ElseIf…Then…Else…End If BlockEnd If Block

Used when a decision Used when a decision depends on several depends on several conditionsconditions

ElseIfElseIf keyword used to keyword used to define each conditiondefine each condition

Often has a “catch-all” Often has a “catch-all”

ElseElse clause clause

Terminated with Terminated with End IfEnd If

If Score >= 90 Then

Grade = “A”

ElseIf Score >=80 Then

Grade = “B”

Else

Grade = “C”

End If

ElseIf Clause also contains Then keyword

10CSC110 Fall 2004

If Statement ConsiderationsIf Statement Considerations Varying conditionsVarying conditions

– The The ElseIfElseIf block is useful when conditions vary block is useful when conditions vary– Conditions can be based on entirely different factorsConditions can be based on entirely different factors

Nesting If BlocksNesting If Blocks– Using another Using another If blockIf block in either the in either the Then clauseThen clause or or

the the Else clauseElse clause– Nested block must be terminated before returning Nested block must be terminated before returning

to the outer blockto the outer block» Indent each nested block to enhance readabilityIndent each nested block to enhance readability

Use comments liberallyUse comments liberally– Especially for nested If blocksEspecially for nested If blocks

11CSC110 Fall 2004

"If" statement and option buttons"If" statement and option buttons

12CSC110 Fall 2004

Messages in Message boxesMessages in Message boxes

Special window displaying message to userSpecial window displaying message to user Form:Form:

MsgBox “MsgBox “messagemessage” [,buttons][, “t.b. ” [,buttons][, “t.b. captioncaption”]”] Example:Example:

MsgBox “Numeric ID only”, vbOkOnly, “Error”MsgBox “Numeric ID only”, vbOkOnly, “Error”

13CSC110 Fall 2004

Displaying a Message StringDisplaying a Message String

Use & to concatenate stringsUse & to concatenate strings(“Concatenate” means join end to end)(“Concatenate” means join end to end)

The VB intrinsic constant vbCRLF creates a The VB intrinsic constant vbCRLF creates a new line in a stringnew line in a string

MsgBox strMessage, vbOKOnly, stTitleMsgBox strMessage, vbOKOnly, stTitle

14CSC110 Fall 2004

Message box return valuesMessage box return valuesConstantConstant ValueValue DescriptionDescription

vbOKvbOK 11 OK button pressed.OK button pressed.

vbCancelvbCancel 22 Cancel button pressed.Cancel button pressed.

vbAbortvbAbort 33 Abort button pressed.Abort button pressed.

vbRetryvbRetry 44 Retry button pressed.Retry button pressed.

vbIgnorevbIgnore 55 Ignore button pressed.Ignore button pressed.

vbYesvbYes 66 Yes button pressed.Yes button pressed.

vbNovbNo 77 No button pressed.No button pressed.

15CSC110 Fall 2004

Input ValidationInput Validation

Checking a data type: IsNumeric & IsDateChecking a data type: IsNumeric & IsDate IsNumericIsNumeric checks & returns true or false checks & returns true or false

If IsNumeric(txtQty.Text) ThenIf IsNumeric(txtQty.Text) Then

lblDue.Caption = curPrice + CInt(txtQty.text)lblDue.Caption = curPrice + CInt(txtQty.text)

Validating value rangesValidating value rangesIf Val(txtHours.Text) > 10 And _If Val(txtHours.Text) > 10 And _

Val(txtHours.Text) <= 80 ThenVal(txtHours.Text) <= 80 Then ... ...

16CSC110 Fall 2004

Data ValidationData Validation

IsDate returns true or false depending on IsDate returns true or false depending on whether or not a value is a datewhether or not a value is a date

If IsDate(txtData.text) ThenIf IsDate(txtData.text) Then … … the VarType function return a number that the VarType function return a number that

corresponds to the data type stored in a corresponds to the data type stored in a variant.variant.

If VarType(varValue) = 0 Then...If VarType(varValue) = 0 Then...

17CSC110 Fall 2004

Calling Event ProceduresCalling Event Procedures

An An event procedureevent procedure is a subprocedure that is a subprocedure that reacts to a specific event such as a button reacts to a specific event such as a button click.click.

You can call any given event procedure You can call any given event procedure from multiple locations, as long as the from multiple locations, as long as the procedure is in the same form or is publicprocedure is in the same form or is public

Example: Example: Call cmdCalculate_ClickCall cmdCalculate_Click Suffix is event, prefix is object Suffix is event, prefix is object namename

18CSC110 Fall 2004

Hands on Programming ExampleHands on Programming Example

19CSC110 Fall 2004

Select Case BlockSelect Case Block

Useful when decision depends on different results Useful when decision depends on different results of the same expressionof the same expression– Begins with Begins with Select CaseSelect Case statement statement

» Each condition coded with Each condition coded with Case criterionCase criterion

– Should have “catch all” Should have “catch all” Case ElseCase Else clause clause

– Terminated with Terminated with End SelectEnd Select statementstatement Criteria are mutually exclusiveCriteria are mutually exclusive

– Once a criterion is found to be true, that block is Once a criterion is found to be true, that block is executedexecuted

– Place most restrictive criterion at topPlace most restrictive criterion at top

20CSC110 Fall 2004

Syntax RulesSyntax Rules

To test for equality, give the value, To test for equality, give the value, – i.e. i.e. Case 80Case 80

To test several values for equality, separate list with To test several values for equality, separate list with commas, commas, – i.e. i.e. Case 80, 81, 85Case 80, 81, 85

To specify a closed range, insert the “To” keyword To specify a closed range, insert the “To” keyword between upper and lower boundsbetween upper and lower bounds– i.e. i.e. Case 80 to 90Case 80 to 90

To specify an open range, use the “Is” keywordTo specify an open range, use the “Is” keyword– i.e. i.e. Case Is < 0Case Is < 0

21CSC110 Fall 2004

Nesting Select Case BlocksNesting Select Case Blocks

Similar to nesting If blocksSimilar to nesting If blocks

– Nested blocks must terminate before Nested blocks must terminate before returning to outer blockreturning to outer block

– Make extensive use of commentsMake extensive use of comments

22CSC110 Fall 2004

If Statement Nested Inside Select If Statement Nested Inside Select Case StatementCase Statement

If block is terminated before returning to Select Case block

23CSC110 Fall 2004

Application Example:Application Example:Tuition CalculatorTuition Calculator

Analyze and determine system requirementsAnalyze and determine system requirements– Calculate student tuitionCalculate student tuition

» Based on residence status and hours takenBased on residence status and hours taken

Design visual interfaceDesign visual interface– Need controls for hours taken and residenceNeed controls for hours taken and residence

» Use radio buttons for status, since limited number of Use radio buttons for status, since limited number of options that won’t changeoptions that won’t change

» Use text box for hours taken Use text box for hours taken

24CSC110 Fall 2004

Visual InterfaceVisual Interface

Tuition displayed in label, formatted to look like text box

Checked property of In State radio button set to true to create Default

25CSC110 Fall 2004

Code Solution Code Solution Select CaseSelect Case with with If then BlocksIf then Blocks

26CSC110 Fall 2004

Code solution Nested Code solution Nested Select CaseSelect Case

27CSC110 Fall 2004

An Alternative SolutionAn Alternative Solution

Use combo boxes to display residence Use combo boxes to display residence status and range of hours takenstatus and range of hours taken– Offers more flexibility, but code is not as clearOffers more flexibility, but code is not as clear

28CSC110 Fall 2004

Visual InterfaceVisual Interface

Items added to combo box at runtime; SelectedIndex property used to set default value

29CSC110 Fall 2004

Code the SolutionCode the Solution

SelectedIndex property used to determine which option is selected

30CSC110 Fall 2004

Block Level DeclarationsBlock Level Declarations

Variables may be declared inside a blockVariables may be declared inside a block– Variables exist only inside the blockVariables exist only inside the block

– You may declare the same variable name inside each You may declare the same variable name inside each blockblock

» i.e. a variable named ID may be declared in the If block, i.e. a variable named ID may be declared in the If block, the ElseIf block, and Else blockthe ElseIf block, and Else block

» While you can do this, it is confusing to read and debugWhile you can do this, it is confusing to read and debug

– You may notYou may not declare a variable name if you have declare a variable name if you have declared a declared a module-levelmodule-level variable with same name variable with same name

31CSC110 Fall 2004

SummarySummary

Two structures commonly used to handle Two structures commonly used to handle decisions: decisions: If If and and Select CaseSelect Case

If structure involves testing whether the condition If structure involves testing whether the condition following If keyword is True or Falsefollowing If keyword is True or False

Relational operators include =, <>, and <. Each Relational operators include =, <>, and <. Each compares two operands to determine if relation is compares two operands to determine if relation is TrueTrue

Commonly used logical operators include And, Or, Commonly used logical operators include And, Or, and Notand Not

32CSC110 Fall 2004

Summary Summary If BlockIf Block

If operational precedence is confusing, use If operational precedence is confusing, use parentheses to encloses expression(s)parentheses to encloses expression(s)

Four ways to construct If structureFour ways to construct If structure– Simple If statementSimple If statement– Simple If blockSimple If block– If…Else blockIf…Else block– If…ElseIf…Else blockIf…ElseIf…Else block

If blocks can be nestedIf blocks can be nested

33CSC110 Fall 2004

SummarySummary Use comments to explain the purpose of the Use comments to explain the purpose of the

conditioncondition Computer evaluates logical or relational Computer evaluates logical or relational

expressions differently than we might expressions differently than we might interpret theminterpret them

String comparisons can be “Binary” (case String comparisons can be “Binary” (case sensitive) or “Text” (case insensitive)sensitive) or “Text” (case insensitive)– A < a “Cat” < “cat” A < a “Cat” < “cat”

34CSC110 Fall 2004

Summary Summary Select CaseSelect Case

Select Case structure can replace If…ElseIf block Select Case structure can replace If…ElseIf block when decision depends on the result of a single when decision depends on the result of a single expressionexpression

Select Case structure can be nested and can also Select Case structure can be nested and can also be nested with If structurebe nested with If structure

Tuition calculation example illustrates how Select Tuition calculation example illustrates how Select Case structure can be nestedCase structure can be nested

You can declare block level variables in both the You can declare block level variables in both the If blocks and the Case blocksIf blocks and the Case blocks