Wyo VB - Ch. 4 Notes
Objective #1: Use If statements
to ensure that a certain statements are executed only when a given condition
applies.
Objective #2: Use If/Else and If/ElseIf statements
to select which of two sequences of statements will be executed, depending on
whether a given condition is TRUE or FALSE.
- The If/Else statement can be used to represent a slightly more
complicated scenario than the plain If statement. If the control expression
after the If keyword is FALSE, then the statement(s) after the Else keyword
is executed. The statement(s) following the Else acts as a default.
- The keyword Else appears on a line by itself and is followed by one or more
statements that execute if the If control expression is FALSE.
- Do not forget to type the End If phrase as the last line of an If/Else statement.
If you forget to do this, it will probably cause a compile error or a logic
error which programmers informally call a "dangling else error".
- Example:
If (strLightStatus = "On") Then
....lblLight.Caption = "The light is on."
Else
....lblLight.Caption = "The light is off."
End if
- The If/ElseIf statement can be used to represent even more complicated
scenarios.
- The ElseIf keyword must be followed by a control expression (within parenthesis
for readability) of its own and the keyword Then.
- Example:
If (strTrafficLightStatus = "Red") Then
....lblLight.Caption = "The light is red."
ElseIf (strLightStatus = "Yellow") Then
....lblLight.Caption = "The light is yellow."
End If
- An Else case may also be used with an If/ElseIf statement but it must appear
below the ElseIf part. For example,
If (strTrafficLightStatus = "Red") Then
....lblLight.Caption = "The light is red."
ElseIf (strLightStatus = "Yellow") Then
....lblLight.Caption = "The light is yellow."
Else
....lblLight.Caption = "The light is green."
End If
- You can use as many ElseIf cases as you need but they must be placed after
the If case and above the Else case (if it is used). For example,
If (sngGrade >= 90) Then
lblGrade.Caption = "A"
ElseIf (sngGrade >= 80) Then
lblGrade.Caption = "B"
ElseIf (sngGrade >= 70) Then
lblGrade.Caption = "C"
ElseIf (sngGrade >= 60)
lblGrade.Caption = "D"
Else
lblGrade.Caption = "F"
End If
Notice the necessary use of the >= (greater than or equal to) operator
rather than the > (greater than) operator in the example above since a
student who earns a grade of exactly 90% should receive an A.
Visual Basic will evaluate the If/ElseIf statement above starting with the
If condition. As soon as one of the control expressions is determined to be
TRUE, Visual Basic will execute the body statements of that portion of the
If/ElseIf statement and then skip over the remaining parts. That is, in the
example above, Visual Basic would never display both an A and a B in lblGrade.Caption.
An experienced programmer however wisely uses the Else portion of an If/ElseIf
statement in order to make his or her program's logic even better and safer.
In the following example, the programmer hopes that the Else portion would
never execute but in case of a logic error elsewhere in his/her program, the
Else portion will help him/her figure out where a bug occurs in the program.
If (sngGrade >= 90) Then
lblGrade.Caption = "A"
ElseIf (sngGrade >= 80) Then
lblGrade.Caption = "B"
ElseIf (sngGrade >= 70) Then
lblGrade.Caption = "C"
ElseIf (sngGrade >= 60)
lblGrade.Caption = "D"
ElseIf (sngGrade >= 0)
lblGrade.Caption = "F"
Else
lblGrade.Caption = "An logic error occurred causing
sngGrade to be less than zero!"
End If
- It is necessary to represent the real-life problem accurately in your pseudocode
before you choose which of the three forms of the If statements to use in
your code. If you are not careful, you will unnecessarily complicate your
algorithm (perhaps with an unnecessary If/ElseIf statement) or you will not
fully portray the scenario that you meant to describe. The grade that you
receive for a program will be affected by your choice (and arrangement) of
If statements.
- It is possible and sometimes necessary to nest one If statement within another.
An example of nested If statements follows:
If (sngGrade >= 90) Then
If (sngGrade >= 98) Then
lblGrade.Caption = "A+"
Else
lblGrade.Caption = "A"
End If
ElseIf (sngGrade >= 80) Then
lblGrade.Caption = "B"
Else
lblGrade.Caption = "You earned a C or less."
End If
Notice that a whole If/Else statement is found within the If portion of the
outer If/ElseIf statement. Also notice that blank lines are placed above and
below the inner If/Else statement for increased readability.
- Do not unnecessarily complicate your program or decrease its readability
by using nested If statements when you could have simply used a single If/ElseIf
statement.
Objective #3: Write Basic expressions to form "Boolean
conditions," which are expressions whose possible values are the constants TRUE and
FALSE.
Objective #4: Explain events, parameters, and properties
in more detail than previously.
- The Click event and KeyPress event
are very useful for providing user-friendly interaction in your programs.
- Most events require "incoming" parameters. That is the event can
only work within a procedure if a parameter is "sent to the event"
from the another procedure or the user's input.
- A parameter is simply a variable that represents a
quantity whose value comes from outside of a procedure. That is, the parameter
is not declared as a variable in a Dim statement inside of the given procedure.
In effect, procedures communicate with one another by exchanging parameters.
- When the Click event is used, the user's single mouseclick is "sent
to" the Click event.
- When the KeyPress event is used, the ASCII code of the
key pressed by the user is sent to the KeyPress event as a parameter.
Depending on what the programmer wants the program to do, he or she "reads"
the ASCII value of the keyboard character that the user presses. Often,
the programmer intends for the user to press the Enter key on the
keyboard. When this happens, two ASCII codes are actually generated .
The codes are 13 and 10, which stand for Carriage Return and Line
Feed, respectively. Normally, for practically all other keyboard characters,
only one ASCII value is generated (the "Enter" key is kind of
special in this way.)
Example: KeyAscii is the parameter that VB sends to a text box's KeyPress
event when a user types a key in a text box. In this example, the user's
text box input is displayed in a message box when the Enter key is pressed.
Private Sub txtInput_KeyPress(KeyAscii As Integer)
If (KeyAscii = 13) Then
MsgBox "You typed " & txtInput.Text
End If
End Sub
- The Visible Property is used to make textboxes (or any
other object) visible and invisible depending on certain conditions during
a program's execution. Even though a textbox with a Text Property, "You
have won the game.", may be present on a form, it may be made invisible
for the duration of a game. Then, only if the user actually wins the game,
would the Visible Property be changed to True in order for the user to know
that he or she won the game.
- The MultiLine Property is used to allow textboxes to include
more than a single line of text. Simply toggle the False, which is the default
value for this property, to True in order to be able to enter more than one
line of text into a textbox's Text Property.
Objective #5: Use compound Boolean expressions with
And and Or.
- Often, it is necessary to use complicated, compound Boolean expressions
to represent a real-life scenario in a computer program algorithm. Be careful
to observe the order of operations that Visual Basic observes between arithmetic,
relational (sometimes called "comparison"), and logical (sometimes
called "Boolean") operators.You may need to add parentheses to the
expression.
- A common mistake by novice programmers is to use an incorrect version of the If-Then
statement like the following:
If (sngSideA = sngSideB = sngSideC) Then
' This code is illegal
lblTypeOfTriangle.Caption = "Equilateral"
End If
The Boolean expression, sngSideA = sngSideB = sngSideC, in the If-Then
statement is illegal. That expression must be broken into two or more subexpressions
and joined with the Boolean logical operator, And.
The following statement is correct:
If ((sngSideA = sngSideB) And (sngSideB
= sngSideC)) Then
' This code works!
lblTypeOfTriangle.Caption = "Equilateral"
End If
- The following excerpt is taken from the online help found in Visual Basic.
"When several operations occur in an expression, each part is
evaluated and resolved in a predetermined order. That order is known as operator
precedence. Parentheses can be used to override the order of precedence; that is, they are
evaluated in the left to right order in which they appear. Arithmetic and logical
operators are evaluated in the following order of precedence:
|
Order of Operations of various
kinds of operators in Visual Basic
|
|
Arithmetic
|
|
Relational
|
|
Logical
|
|
| Exponentiation (^) |
|
Equality |
|
Not |
| Negation (-) |
|
Inequality (<>) |
|
And |
| Multiplication and division (*, /) |
|
Less than (<) |
|
Or |
| Integer division (\) |
|
Greater than (>) |
|
Xor |
| Modulus arithmetic (Mod) |
|
Less than or Equal to (<=) |
|
Eqv |
| Addition and subtraction |
|
Greater than or Equal to (>=) |
|
Imp |
| String concatenation (&) |
|
Like |
|
|
| |
|
Is |
|
|
The string concatenation operator (&) is
not an arithmetic operator, but in precedence it does fall after all arithmetic
operators and before all comparison operators. Similarly, the Like operator,
while equal in precedence to all comparison operators, is actually a pattern-matching
operator. The Is operator is an object reference comparison operator. It does
not compare objects or their values; it checks only to determine if two object
references refer to the same object."
You probably will not have to use the Like or Is operators very often,
however the information above may still be useful to you.
Objective #6: Use the Mod operator to test divisibility.
- From your previous math education, you should be familiar with the following
terms that relate to divisibility:
- evenly divisible
Example - 10 is evenly divisible by 2 because 10 divided by 2 leaves a
zero remainder
- common factor
Example - 3 is a common factor of 12 and 24 since it is a factor of 12
(3 * 4 = 12) and it is a factor of 24 (3 * 8 = 24)
- multiple
Example - 20 is a multiple of 5 since 5 times 4 is 20
- divisor
Example - 6 is a divisor of 42 since it divides evenly into 42 (42 divided
by 6 leaves a remainder of 0)
- prime
Example - 13 is prime since it has no divisors except for itself and 1
- The Mod operator in Visual Basic is often used to test whether or
not two numbers are divisible. That is, to find out if one number is evenly
divisible (with no remainder) by another number, you would use the Mod operator.
Divide the two numbers and find the remainder. The remainder is the answer
that the Mod operator returns. Some people call the Mod operator "the
remainder function."
Examples:
Objective #7: Build and concatenate strings for display in multiline
textboxes.
- One uses the Str function to turn a variable that
represents a numeric value into a string. For example, Str(intNumber) would
turn the Integer variable number that is equal to 5 into a string which is
represented by "5" . The double quotes serve as delimiters in this
example. Note, that by including the double quotes around the 5, one denotes
that it is a string and not a numeric value. The two things are very different.
A programmer can use the Val function to turn a string into a numeric value.
- In Visual Basic, you can use the ampersand (&) to concatenate
(that is, join) two strings together into one larger string. The ampersand
is called the concatenation operator in Visual Basic.
Examples:
Objective #8: Use the Visual Basic Timer and Time functions.
- The Time function can be used to display or determine the current
time. For example, the statement
lblCurrentTime.Caption = Time
will cause the current time to be displayed in the caption of the label lblCurrentTime.
- The Timer function can be used to determine the amount of time that
a program takes to execute among other things. Since the Timer function returns
the number of seconds that passed since midnight, it can be used twice in
a program to determine the elapsed time. If you use the statement,
lblStartTime.Caption = Timer
in the Form_Load event and the statement
lblTotalTime.Caption = Timer - Val(lblStartTime.Caption)
somewhere just before a program ends, then the amount of elapsed time will
display in the label lblTotalTime.
Objective #9: Use Select Case statements for multiple selection.
- When a programmer has more than 2 or 3 possible branches, it is more efficient
to use a Select Case statement rather than an If/Then statement or an If/Then/Else
statement. Often a Select Case statement is used because it is easier to read
and understand even though it could be replaced by an If/ElseIf statement.
- Consider a situation in which the variable intGrade is equal to a whole
number between or including 1 and 10. An example of a Select Case statement
is:
Select Case intGrade
Case 10, 9
lblOutput.Caption = "A"
Case 8
lblOutput.Caption = "B"
Case 7
lblOutput.Caption = "C"
Case
6
lblOutput.Caption = "D"
Case Is <= 5
lblOutput.Caption = "F"
Case Else
lblOutput.Caption = "intGrade
must have a bad value"
Beep
End Select
Notice the use of the comma between the 10 and the 9 in the first Case. Also,
notice that the keyword Is must be used in situations like "Case Is <=
5" above. Two or more statements can be placed in any case of the Select
Case statement. The Beep command will cause the computer to beep if
intGrade is unexpectedly not equal to a whole number less than or equal to
10.
- A variable is listed after the keywords Select Case on the first line. This
variable is called the control variable of the Select Case statement.
Depending on the value of that control variable, the computer will perform
the statements in one and only one of the branches under each Case statements.
Each case determines a specific value or range of values that the variable
could take on.
- Once VB determines which case applies given the value of the variable, it
performs the statements in that Case section. Then, the rest of the Select
Case statement is skipped over and the computer program continues with any
code that follows the End Select line.
- While it is not required to specify Case Else as the last section of a Select
Case statement, it is a wise idea since it can be used effectively for error-checking
and input validation.
- It is considered to be good style to indent the body statements within each
case section.