Wyo VB Ch. 4 Lecture Notes
Objective #1: Use If statements
to ensure that certain statements are executed only when a given condition
applies.
- The If statement (sometimes
called an "If Then statement")
is very useful to represent "what-if" type scenarios in a computer
program's algorithm. The statement works in the same way that you would interpret
an if-then scenario using the English language
- The first line of an If statement
must start with the keyword If.
- The first line of an If statement
must end with the keyword Then.
- One or more statements follow the If
Then line. These statements are considered to be the body of
the If statement.
- You must type End If as
the very last line of the If statement.
- The expression in between the If and
the Then keywords is the control expression.
If the control expression evaluates to TRUE, then Visual Basic will execute
the statement(s) that follow. If the control expression is FALSE, then Visual
Basic ignores the body of the If statement.
- Example:
If (x = 0) Then
lblResult.Text = "x is 0"
End If
- Note that the body of the If statement
is indented to make it easier to read and logically understand.
- Parenthesis are not required to placed around an If statement's
control expression but they add to the readability of the code and should
be used.
- One line If statements can be used in VB if the If statement
would only have one body statement as in
If (x = 0) Then lblResult.Text = "x is 0"
If the If statement has two or more body
statements it must be typed out with the End If line
coming at the end as in
If (x = 0) Then
lblResult.Text = "x is 0"
MessageBox.Show("Goodbye")
End If
Mr. Minich discourages the use of one-line If statements
and prefers that all If statements be typed
out over multiple lines.
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.Text = "The light is on."
Else
lblLight.Text = "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.Text = "The light is red."
ElseIf (strLightStatus = "Yellow") Then
lblLight.Text = "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.Text = "The light is red."
ElseIf (strLightStatus = "Yellow") Then
lblLight.Text = "The light is yellow."
Else
lblLight.Text = "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 (dblGrade >= 90) Then
lblGrade.Text = "A"
ElseIf (dblGrade >= 80) Then
lblGrade.Text = "B"
ElseIf (dblGrade >= 70) Then
lblGrade.Text = "C"
ElseIf (dblGrade >= 60) Then
lblGrade.Text = "D"
Else
lblGrade.Text = "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.Text.
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 (dblGrade >= 90) Then
lblGrade.Text = "A"
ElseIf (dblGrade>= 80) Then
lblGrade.Text = "B"
ElseIf (dblGrade>= 70) Then
lblGrade.Text = "C"
ElseIf (dblGrade>= 60) Then
lblGrade.Text = "D"
ElseIf (dblGrade>= 0) Then
lblGrade.Text = "F"
Else
lblGrade.Text = "A logic error occurred causing dblGrade
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 (dblGrade >= 90) Then
If (dblGrade >= 98) Then
lblGrade.Text = "A+"
Else
lblGrade.Text = "A"
End If
ElseIf (dblGrade >= 80) Then
lblGrade.Text = "B"
Else
lblGrade.Text = "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 VB expressions
to form "Boolean conditions," which are expressions whose possible
values are the constants TRUE and FALSE.
- A common mistake by novice programmers is to use
an incorrect version of the If statement
like the following:
If (dblSideA = dblSideB = dblSideC) Then
lblTypeOfTriangle.Text = "Equilateral"
End If
The Boolean expression, dblSideA
= dblSideB = dblSideC, in the If 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 ((dblSideA = dblSideB) And (dblSideB = dblSideC)) Then
lblTypeOfTriangle.Text = "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 (+ and -) |
|
Greater than or Equal to (>=) |
|
Imp |
String concatenation (& or + in some situations ) |
|
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, Is, Xor, Eqv, and Imp operators very often, however the information above may still be useful to you. Those operators will not be covered on tests or quizzes for this course.
Objective #4: Use collision detection to control animation.
- Collision detection is code that responds to graphics
when they touch each other or a boundary of the form.
- The following code could also be used to detect
a collision by checking to see if the picCircle object "straddles" the
line
If (picCircle.Top < 20
And picCircle.Bottom > 20) Then
MessageBox.Show("Collision
Occurred")
End If
Note that unlike Top, Bottom is a "read only" property of a PictureBox, so it can be used in If statements like the one above but it cannot be used in an assignment statement like picCircle.Bottom = 100
Similarly, Right is a "read only" property.
Objective #5: Generate random numbers within
desired ranges.
- Technically, it is impossible
to generate
a truly random number with a computer since it does not have a mind of
its own to pick numbers at random. The number that the computer generates
must be based on something else such as the number of seconds since midnight. Therefore it is best to describe these numbers as pseudorandom rather than truly random.
- You can use the built-in method Rnd to generate random numbers. The Rnd method returns a decimal number between (but not including) 0 and 1.
- Using the statement
intDiceRoll = Math.Floor(Rnd() * (Hi - Lo + 1)) + Lo
you can generate a random whole number between and including the values substituted for Lo and Hi and store that random number in the variable intDiceRoll.
- Use the Randomize statement first though in the Form_Load method. This "seeds" the VB random number generator so that your program doesn't generate the same random numbers every time it executes.
- There is another way in which random numbers can be produced however this method will not be tested on worksheets or exams in this Visual Basic course. You can use the built-in VB class
named Random to generate random numbers.
- The statement
Dim dice As New Random
declares a Random object named dice.
I don't require that you use a specified prefix when naming Random objects.
- The Next method
returns an integer number between 0 and one less than its parameter. For example,
the statement
MessageBox.Show(dice.Next(6))
displays a pseudorandom integer between or including 0 and 5. If you want
to simulate the roll of a dice, then you must add one to the the value
that
is returned by the Next method as in
MessageBox.Show(dice.Next(6) + 1)
- To seed the Random object,
you use the following statement to declare the Random object.
Dim dice As New Random(1)
with some integer seed value specified in the parentheses.
Any number will work fine. The result will be that the string of random values
generated by the Next method will be the
same pattern of random values. This is helpful when testing and debugging
a program.
- Use the nextDouble method to generate a pseudorandom floating-point
value. The following statement will display a random decimal number between
0 inclusive and 1 exclusive meaning that 0 could be a returned value but
1 will not be a possible returned value.
MessageBox.Show(dice.NextDouble())
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:
You could say that the rule is "when
the Mod of two numbers is zero, then the first number is evenly divisible by the second number." Or, one could say that "when the Mod
of two numbers is zero, then the first number is a multiple of the second number."
- To determine if the variable intNum is prime or composite, you can use the following If statement
If
(intNum = 2 Or intNum = 3 or intNum = 5 Or (intNum Mod 2 <> 0 And intNum Mod 3 <> 0 And intNum Mod 5 <> 0)) Then
MessageBox.Show(intNum + " is prime")
Else
MessageBox.Show(intNum + " is not prime")
End If
Are the extra parentheses in the If statement necessary? This algorithm would work for any value of intNum up to 35. Do you know why?
Objective #7: Use an array to store data.
- An array (also
called a vector or a list) is a set of related variables.
In fact, all of the variables in the array are referenced by the same name
(the name of the array itself). For example,
if you wanted
to
store
John Doe's five exam grades, it would be more efficient to use an array
instead of 5 separate variables.
Instead of declaring 5 variables with the statement
Dim intExam1, intExam2, intExam3, intExam4, intExam5 As Integer
You should declare an array named intExam with the statement
Dim intExam(5) As Integer
This statement creates one array that has six positions.
Each position of the array can store a separate exam value. The size or
length of the array intExam is said
to be 6 simply because that is how many elements it can hold. This
array
has
6 elements not 5 because Visual Basic always includes an element with
position (subscript) zero. You can declare arrays to be as big as you would like in Visual Basic.
- An array can initialized within its declaration statement by include the initial
values in a set of curly braces. In this case, you are not allowed to declare the size of the array so you must leave the parentheses empty. Here is an example:
Dim intExam() As Integer = {77, 90, 73, 80, 91}
- Arrays are useful because they make it easier to program with loops and other structures. They organize data so that it can be manipulated and processed more efficiently. For example, instead of five separate statements that initialize each of John Doe's exam grades to 100 as in:
intExam1 = 100
intExam2 = 100
intExam3 = 100
intExam4 = 100
intExam5 = 100
It would be easier to initialize them with a For loop as in:
For
J = 1 To 5
intExam(J) = 100
Next
- In addition to storing integers in an array (as above), you can declare an array to store strings or any other variable data type as in
Dim strNames() As String = {"Alfred", "Betty", "Chris", "Donna", "Edgar"}
However, you can not store two different data types in the same array. That is you cannot mix integers and strings.
- The values in an array are called elements. The 2 in the statement intExam(2) = 94 is called a subscript or index position. The variable J in
the loop example above is called an index variable,
meaning that it is being used to represent the subscript.
- While arrays can be declared as local variables within a method, it is usually more efficient to declare an array at the top of the form. When you declare any variable at the top of the form, the variable is called a module-level variable rather than a local variable. It is considered to be good style to use a lower case m as a prefix for a module-level variable. So a declaration statement for a module-level array variable might look like this:
Dim mintExamScores(5) As Integer
- The length of an array can be determined by using the Length method.
The following example shows how the length of an array can be used as the
upper
bound of a For loop
For J = 1 To mintExamScores.Length()
MessageBox.Show(mintExamScores(J))
Next
- There are a few static methods of the Array class that are useful with arrays including
The Clear method allows you to set one or more of the elements of an array of integers to zero. For example,
Array.Clear(mintExamScores, 0, 4)
would set all of the elements from index position 0 to index position 4 equal to zero.
The Reverse method reverses the elements in an array. It is used like this Array.Reverse(mintExamScores)
The BinarySearch method searches an array for a value and returns the index position where the value is found. For example,
Dim intExam() As Integer = {77, 90, 73, 80, 91}
MessageBox.Show(Array.BinarySearch(intExam, 90)
causes the value 1 to display in the message box since the value 90 is found in index position 1 of the array.
The Sort method sorts an array. The following statement rearranges the elements in mintExamScores so they are in ascending order:
Array.Sort(mintExamScores)
- Here is a code segment that computes the running
total of the elements in an array
Dim intScores() As Integer = {73, 77, 82, 71, 98}
Dim intSum As Integer = 0
Dim J As Integer = 0
For J = 1 To intScores.Length()
intSum = intSum + intScores(J)
Next
- Parallel arrays are simply two separate arrays that are used together in the logic of an algorithm to store associated data. For example, an array of names and an array of scores where the score in position zero of the scores array belongs to the person whose name is found in position zero of the names array and so on. Two parallel arrays are the same size but they do not have to contain elements of the same data type. The names array would be an array of strings and the scores array would be an array of integers.
- An ArrayList is similar to an array. It can also store multiple items and is primarily used when you need to store objects rather than numbers. To declare an ArrayList, you use
Dim list As New ArrayList
In a Form1_KeyDown method, you could use something like
If e.KeyCode = Keys.Space Then
Dim next As New Label
next.Top = 50
next.Height = 50
Me.Controls.Add(next)
list.Add(next)
You can also use a For Each loop such as
For Each temp in Me.list
Label.Top += 5
Next
and
For Each control in Me.Controls
If (TypeOF(control) Is Label) Then
control.Top += 5
End If
Next
Objective #8: Use String variables.
- A string is
a sequence of characters (letters, digits, and symbols) that may or not spell
an English word. A string can be made up of digits. For example "1234" is
a string. Strings very often spell phrases that can contain a blank space,
such as "John Doe" (where there is a blank space between the 'n'
and the 'D'.)
- The keyword String is
a data type that can be used to allow a variable to store a string. The declaration
statement
Dim strName As String = "John"
declares the string variable strName and
initializes it to the string literal "John". A string literal is a word or
phrase that
is typed inside of double
quotes. A string variable is the variable itself. Often, we simply say "string" to refer to either a string variable or a string literal.
- The " symbol
is considered a string delimiter. In the string literal
" Basic"
the
space before the 'B' is called a leading space.
In the string literal, "Programming ",
the space AFTER the last 'g' is called a trailing
space.
- You can assign a string literal to a String variable
with an assignment statement as in
strName = "John Doe"
assigns the string literal, "John Doe", to the variable, strName.
- The null string (aka empty string) is a special string value that contains
no letters or characters. It is represented by typing two double quotes.
The
following
statement assigns the null string to
strName:
strName = ""
- Concatenation is
the operation in which you join together two strings. You must use the concatenation
operator which is the plus symbol ( + ). In older versions of VB,
programmers tended to use the ampersand symbol
(&)
as a concatenation operator but I prefer that you use the + operator. Look
closely at the following example:
strNameA = "John"
strNameB = "John "
strLastName = "Doe"
strExample1 = strNameA + strLastName
strExample2 = strNameB + strLastName
strExample1 is currently equal to "JohnDoe" and strExample2 is "John Doe" because of the included blank space in strNameB.
Here are more examples involving string concatenation:
"computer" + "programming" displays
as "computerprogramming"
(no space is will automatically be placed between the words)
"Wyomissing " + "Area" displays
as "Wyomissing Area"
(notice the space after the 'g' in "Wyomissing")
"54" + "32" displays
as "5432"
(both operands are strings and NOT numeric values)
"54" + 32 displays
as 86
(when at least one of the two operands is a number, the + symbol adds
rather than concatenates)
54 + 32 displays
as 86
(both operands are numeric values)
You can also use the += operator to concatenate two strings as in
strName = "John"
strLastName = "Doe"
strName += strLastName ' strName is now "JohnDoe" (with no space in between)
This last statement is equivalent to
strName = strName + strLastName
- The Length method of a string can be used to count the number of characters in a string. For example 11 will show up in the message box from the following statement
Dim strWord = "Programming"
MessageBox.Show(strWord.Length())
If strWord2 = " Programming is fun", then strWord2.Length() is 19 because of the three spaces that are included in the strWord2. Notice that there is a leading space before the 'P' and two spaces that separate the words. Spaces ARE considered to be characters and, therefore, they are counted as part of the length of a string. In former versions of Visual Basic, the Len function was also used to count the number of characters in a string as in MessageBox.Show(Len(strWord)) but I would rather you use the Length method on assignments, quizzes, and tests.
- You can use the ToString method
to turn a variable that represents a numeric value into a string. For example,
strNum =
intNumber.ToString()
would
turn the Integer variable intNumber that
is equal to 5 into a string which is represented by "5" . In former versions of VB, the Str function
was used to do the same thing as in
strNum = Str(intNumber)
I prefer that you use the ToString method
rather than the Str method
when turning a numeric variable into a string.
- A programmer can
use the Val function
to turn a string into a numeric value like the statement
intZip = Val("19610")
or
Dim strZip As String = "19610"
intZip = Val(strZip)
The CInt method
can also be used to change a string into an integer as in
intZip = CInt("19610")
- Strings can be compared using the string comparison
operators (=, <, and >) which happen to be the same as the arithmetic
comparison operators that are used to compare mathematical and Boolean
expressions in Visual Basic. Visual Basic compares
strings alphabetically with the string comparison operators. In order to
compare strings, VB simply examines the Unicode values of the corresponding
characters of each string starting with the leftmost characters. Whichever
first letter of the two strings has the lower Unicode value causes that
string to be considered less than the other string. In comparing "Apple" to "Banana",
VB first compares the Unicode value of the 'A' in "Apple" to
the 'B' in "Banana. The Unicode value of 'A' is 65 which is less than
the Unicode value of 'B' which is 66. Therefore, "Apple" is considered
to be less than "Banana." If
the two strings have the same first character, then Basic compares the
second characters with each other.
Examples:
("A" < "B") simplifies
to the Boolean value True since the Unicode value of A is 65 and the
Unicode value of B is 66.
("D" < "d") simplifies
to the Boolean value True since the Unicode value of uppercase D
is 68 and the Unicode value of d is 100.
("Apple" < "Banana") simplifies
to the Boolean value True since the Unicode value of A is 65 and
the Unicode value of B is 66.
("ABC" = ("A" & "BC")) simplifies to True since the "ABC" is equal to "ABC" after
the string concatenation.
("Apple" < "Aphrodite") simplifies
to False since the Unicode value of the second p in Apple is 112
and the Unicode value of h is 104.
("Zeus" < "aphrodite") simplifies
to True since the Unicode value of uppercase Z is 90 and the Unicode
value of lowercase a is 97.
Another Example:
strMyName = "Minich"
strYourName = "Anderson"
If (strMyName < strYourName) Then
MessageBox.Show("Ha Ha, I greater than you (alphabetically at least)")
End If
- Besides using the string comparison operators (<, >, =), you can also use the Compare method
to compare two strings to see if one string is less than, equal to, or
greater than another string. The Compare method returns a positive number if its first parameter is alphabetically greater than the second parameter. It returns a negative number if its first parameter is less than the second parameter . It returns a zero if the two parameters are equal.
Dim strYourName As String = "Zeus"
Dim strMyName As String = "Aphrodite"
If (String.Compare(strMyName, strYourName) < 0) Then
MessageBox.Show("My name is less than your name") ' this message will display
End If
Notice that the Compare method
is a static method from the String class
like the Sqrt and Pow methods
from the Math class.
Old versions of VB used the StrComp to
compare two strings.
- The ToUpper method
is used to change lowercase letters into uppercase letters. The ToLower function
is used to change uppercase letters into lowercase letters. These functions
can be used to make a program case-insensitive. This would allow the user
to type text input without regard to the "uppercaseness" or "lowercaseness" of
what he/she is typing. Older versions of VB used the UCase and LCase functions
to change text to upper or lowercase.
Examples:
strName = "bill"
(strName.ToUpper()
= "BILL") is
True since every letter of the string is changed to uppercase
strFruit = "apple"
(strFruit.ToLower() = "apple") is
True since "apple" is already lowercase
strAnimal = "AARDVARK"
(strAnimal.ToLower() > "Programming") is
True since lowercase a is greater than uppercase p on the Unicode chart
- In general, you cannot assume that the user is going to
enter data into your program in a consistent (or even logical) manner. Therefore,
one person may enter his name as "John Doe" whereas another may
enter it as "bill doe" (forgetting to capitalize proper nouns).
This seems to occur more than ever since computer users are so sloppy typing
email messages in lowercase letters. A skillful programmer can avoid any
complications from bad user input by using the ToUpper and ToLower methods.
- Similarly, users may enter trailing or leading spaces by accident when inputting data. For example, someone may enter his name as " John Doe" (notice the leading space before the 'J') and not "John Doe". Therefore, you should use the Trim function to avoid any complications. The Trim function takes a string as a parameter and returns the string with all of its leading and trailing spaces removed if any exist. Note that if you were comparing two strings where one had a leading space then that one would always appear less than the other even if the first non-white space character was alphabetically less than its counterpart. That is, " Zeus" < "Arthur" (notice the leading blank space before the Z) since the Unicode value of the leading space in " Zeus" is 32, which is less than the Unicode value of 'A', which is 65.
Examples:
Trim(" Fred") = "Fred"
Trim(" Fred ") = "Fred"
Trim("Fred") = "Fred"
- The Substring method returns
a substring that begins with a particular character of the original string
and ends with a specified spot. A substring is a part of a larger
string. The Substring method works in this
way
Dim strName As String = "George Washington"
MessageBox.Show(strName.Substring(8, 5)) ' ashin
MessageBox.Show(strName.Substring(0, 6)) ' George
MessageBox.Show(strName.Substring(7)) ' Washington
where the first parameter is the starting point of the extracted substring
(counting the first character as zero) and the second parameter is the
number of characters to extract from the starting point. If no second parameter
is used then the rest of the string is extracted and no blank spaces are
used to pad the new substring. A blank space counts as a character. In
older versions of VB, it was necessary to use the Mid function
instead of the Substring method.
- The IndexOf method helps you find a substring within another string. In other words it finds one string within another string.
Dim strName As String = "George Washington"
MessageBox.Show(strName.IndexOf("g"))
would display the value 4 in the message box since the first occurrence of a lowercase g is in position 4 of strName. The IndexOf method does not find the second or later occurrence of a substring. A -1 value is returned by the IndexOf method if it does not find an occurrence of the string parameter in the larger string. Here are some more examples with strName = "George Washington"
strName.IndexOf("shin") simplifies to 9 since the position of the "s" in "shin" is position 9. The blank space in strName counts as a position of course.
strName.IndexOf("wash") simplifies to -1 since "wash" with a lowercase "w" is not found anywhere in strName
strLetter = "r"
strName.IndexOf(strLetter) simplifies to 3 since the lowercase "r" is found in position 3 of strName.
strVowels = "aeiou"
strName = "George Washington"
strVowels.IndexOf(strName.Substring(1, 1)) simplifies to 1 since the "e" in strName is found in position 1 of strVowels
Objective #8: Use the Math class
methods.
- The Abs method can be used to compute the absolute value of a number as in
intNum = Math.Abs(intX * intX + intY * intY)
- The Pow method can be used to compute base to an exponent as in
intNum = Math.Pow(3, 4)
which simplifies to 81 which is 3 to the fourth power. You should use the Pow method rather than the ^ operator.
- The Sqrt method can be used to compute a square root as in
dblNum = Math.Sqrt(13)
- The Round met hod which
uses Banker's
Rounding (.5 only rounds up if the number before it is odd) -
more info on Banker's Rounding
intNum = Math.Round(13.5)
rounds to 14 but
intNum = Math.Round(12.5)
rounds to 12.
- The Max and Min methods return the greatest or smallest value respectively.
intNum = Math.Max(4, -6)
causes 4 to be stored in intNum.
While
intNum = Math.Min(4, -6)
causes -6 to be stored in intNum.
- The Floor method causes numbers to be changed to the next smallest integer
intNum = Math.Floor(8.9)
causes 8 to be stored in intNum while
intNum = Math.Floor(-8.9)
causes -9 to be stored in intNum.
- The Ceiling method causes numbers to be changed to the next greatest integer
intNum = Math.Ceiling(8.1)
causes 9 to be stored in intNum while
intNum = Math.Ceiling(-8.9)
causes -8 to be stored in intNum.
- The Log10, Sin, Cos, and Tan method compute base 10 logs, sines, cosines, and tangents respectively.
intNum = Math.Log10(100) causes 2 to be stored in intNum since 10 to the second power equals 100.
dblNum = Math.Sin(3.14) causes 0 (or a number close to that) to be stored in dblNum since the sine of PI is 0.
dblNum = Math.Cos(3.14) causes -1 to be stored in dblNum since the cosine of PI is -1.
dblNum = Math.Tan(3.14/4) causes 1 to be stored in dblNum since the tangent of PI/4 is 1.
- Pretty accurate values for PI and e (Euler's constant) can be used since they are defined in the Math class as constants. The statement
MessageBox.Show(Math.PI) will display PI pretty accurately and
MessageBox.Show(Math.E) will display e pretty accurately.
Objective #9: Use the "macho" rounding formula
to implement normal rounding rather than Banker's Rounding like the Math.Round method.
- Consider the following assignment statement
intRounded = Math.Floor(dblUnrounded + 0.5)
The value of intRounded will be value of dblUnrounded rounded to the nearest
whole number with normal rounding
- Consider the following statement
dblRounded = Math.Floor(dblUnrounded * 100 + 0.5)
/ 100
The value of dblRounded will be value of dblUnrounded rounded
to the nearest
hundredth's place with normal rounding
- Only Mr. Minich calls this method of rounding "macho rounding".
You will not see this algorithm referred to as macho rounding anywhere else.
Objective #11: Use While loops.
- A While loop should be used instead of a For Next loop
when you do not know the exact number of iterations that the loop must
make. That is, if there is a situation in which some process must occur
over and over again within a loop but you do not know when exactly it will
end then you should use a While loop.
For example, if you ask the user to input his test scores but your program
does not necessarily know how many tests he has taken you could use a While loop and simply tell the user to enter
the number -99 to end his list of input values. Of course, we know that
-99 will not be confused with his actual exam scores since it is impossible
to earn a -99 on an exam. In this case, -99 is called the sentinel value that
warns the loop that the inputs have ended just like Paul Revere was a sentinel
that warned the Americans that the British were coming.
- A While loop is called an indefinite loop (or indeterminate loop) because you never know exactly how many times it will iterate. Remember that a For loop is a definite loop (or determinate loop) because a programmer can count how many times it will iterate based on its initial value, limit value, and step value.
- In a While loop, a control expression is typed after the keyword While. Visual Basic evaluates the control expression to either True or False. If the control expression is True then VB does iterate the loop. If it is False, VB skips the loop or stops iterating it. I prefer that you use parentheses around the control expression of a While loop for readability and style however VB does not require the use of parentheses.
- Here is an example of an accumulator statement in
a While loop:
intCounter = -1
intTotalPoints = 0
intExam = 0
While (intExam <> -99)
intTotalPoints = intTotalPoints + intExam
intCounter = intCounter + 1
intExam = InputBox("Enter your next exam score (-99 to quit):")
End While
intExamAverage = intExamTotalPoints / intCounter
Note that in the example above the user is prompted
by the InputBox to enter -99 to quit. Notice the use of an accumulator statement (intTotalPoints = intTotalPoints + intExam)
as well as the use of a counter statement (intCounter = intCounter + 1). The loop allows the user to enter all of his or her exam scores. After the loop finishes iterating, the exam average is computed and stored in intExamAverage. Can you find the bug that would cause a potential run-time error in the example above? Can you rewrite the code to fix this logical error?
- The While loop
in the example above is called a top-checking loop because the control
expression which evaluates to true or false is placed at the
top of the loop. It is also possible to use Do
While loops
as a bottom-checking loop with the control expression after the keyword Loop at
the bottom of the loop. A bottom-checking loop guarantees at least one iteration
while
a top-checking does not since the control expression could evaluate to false
right away. Here is an example of a bottom-checking Do While loop:
Do
intTotalPoints = intTotalPoints + intExam
intCounter = intCounter + 1
intExam = InputBox("Enter your next exam score (-99 to
quit):")
Loop While (intExam <> -99)
- You can use an Exit While statement
to exit or "break out of" a While loop. You can also use an Exit For statement to break out of a For loop. However, it is not wise to use these Exit statements unless there is no other practical way to make the loop end naturally under the control of its control expression.
Example:
While (intSentinel <> -99)
intExam = InputBox("Enter your next exam score (-99 to quit): ")
If (intExam = -99)
Exit While
End If
intCounter = intCounter + 1
intTotalPoints = intTotalPoints + intExam
End While
in this loop, the loop immediately stops iterating if the user enters an exam score of -99 before the intCounter counter variable is incremented by one.
- Be careful not to create infinite loops that iterate forever. If a While loop's control expression never becomes False, the loop will never end possibly causing the user to be forced to turn off the computer itself! If a For loop is constructed like this:
For i = 1 To 10 Step -1
it may never finish iterating.
- A flag variable is
often used to store the value 1 (meaning True) or 0 (meaning False). The
programmer uses the flag variable as a way of controlling some process
in an algorithm. Flag variables are often used in loops to send a signal
to the control expression. For example, in the code segment below intGameIsOver is
used as a flag variable. It sends a signal to the control expression of
the loop if the user has scored enough points to end the game and exit
the loop. intGameIsOver is
initially set to the value 0 which indicates False (the game is NOT over).
You should name flag variables appropriately. The variable should be named
in a way that it's name indicates a True condition. (For example, in the
segment below, you should not use a flag variable with the name, intGameIsNotOver,
since it would probably make the logic of the algorithm harder for most
fellow programmers to follow.)
intGameIsOver = 0
While (intGameIsOver = 0)
' a bunch of statements would be located here
intUserPointsScored = intUserPointsScored + intLastRoundScore
If (UserPointsScored > 1000) Then
intGameIsOver = 1
End If
End While
Often programmers use variables with the Boolean data
type as flag variables. A Boolean variable
can be set to either True or False.
Here is an example:
Dim
blnGameIsOver As Boolean = False
While (blnGameIsOver = False)
' a bunch of statements
would be located here
intUserPointsScored
= intUserPointsScored + intLastRoundScore
If (intUserPointsScored > 1000)
Then
blnGameIsOver
= True
End If
End While
By using a Boolean variable
you can simplify the first line of the loop like
this
While
(Not blnGameIsOver)
- You should always surround your loops with blank lines in your code. This makes your program easier to read and debug. That is, above all While and For loops you should include a blank line and below all End While and Next statements, you should include a blank line. In fact, your instructor may deduct points for the failure to do so even though Visual Basic does not require these blank lines. Blank lines used to make code easier to read are called white space. Tabs and blank spaces that are also used for the same purpose of making white space.
Objective #12: Trace and apply the sequential search
algorithm.
- Although there are more efficient ways to search for data,
a sequential search is
a good choice to use when the amount of data to be searched is small. A sequential
search is also called a linear search.
- You simply check each element of an array position by
position until you find the one that you are looking for.
- In any search, the item upon which the search is based
is called the key
- An advantage to the sequential search is that the algorithm
is relatively easy to code.
- The sequential search algorithm's worst case is when the
element that you are searching for is the last element in the array or not
found in the array. The best case occurs when the element that you are searching
for is the very
first
item in the array.
- A boolean variable can be used to exit early from
a loop when the key is found. Also, a boolean
value can be returned from a sequential search method to indicate whether
or not the target key was found or not. Or, the position within an array
where the target is found could be returned.
Dim mintScores() As Integer = {32, 45,
28, 99, 70}
Private Sub btnFind_Click(...)
Dim J As Integer = 0
Dim blnFound As Boolean = False
While (Not(blnFound))
If (mintScores(J) = 33) Then
blnFound = True
End If
End While
If (blnFound) Then
MessageBox.Show("33 was found")
Else
MessageBox.Show("33
was not found")
End If
End Sub
- The following code is a linear search that finds
the maximum value in an array.
Dim mintScores() As Integer = {32, 45,
28, 99, 70}
Private Sub btnFind_Click(...)
Dim J As Integer = 0
Dim intMax As Integer = 0
For J = 0 To mintScores.Length()
If (mintScores(J) > intMax) Then
intMax = mintScores(J)
End If
Next
MessageBox.Show(intMax)
End Sub
Objective #13: Trace and apply the binary search algorithm.
- If the data in an array is already sorted in order (alphabetically
for example) then a binary search is much more efficient and usually
quicker than a sequential search.
- In the case of a binary search, you first examine the "middle" element
in the array. If that element is "lower" (alphabetically, for example)
than the element which you are looking for, then you discard the lower half
of
the
data and continue to search the upper half. The process repeats itself when
you then look at the middle element of the remaining "upper half" of
the data.
- The worst case of a binary search is that you do not find
the key but even the worst case doesn't take too long. If the array has 100
elements, then it would take at most 7 loop iterations to find any element
in the array since 2 ^ 7 is the first power of two that is greater than 100.
- Here is a version of the binary search algorithm
Dim mintScores() As Integer = {5, 13, 29, 31, 44, 53, 66, 75, 87, 99}
Private Sub btnBinarySearch_Click(...)
Dim intLow
As Integer = 0
Dim intHigh As Integer = mintScores.Length() - 1
Dim intKey As Integer = Val(txtKey.Text)
Dim intMid As Integer = intHigh / 2
Dim blnFound As Boolean = False
System.Array.Sort(mintScores)
While (Not (blnFound) And intLow <= intHigh)
If (mintScores(intMid) = intKey) Then
blnFound = True
Else
If (mintScores(intMid) > intKey) Then
intHigh = intMid - 1
ElseIf (intKey > mintScores(intMid)) Then
intLow = intMid + 1
End If
intMid = Math.Round((intLow + intHigh) / 2)
End If
End While
If (blnFound = True) Then
lblResult.Text = "Found in position " + intMid.ToString()
Else
lblResult.Text = "Not Found"
End If
End Sub
Objective #14: Be able to use the KeyDown, KeyPress, MouseDown, MouseUp, MouseMove, MouseLeave,
& MouseEnter methods.
- Some interesting methods can be used with a form including MouseDown, MouseUp, MouseMove, KeyPress,
and KeyPress.
- A form's KeyDown method
allows your program to respond to presses of the arrow keys on the keyboard.
Private Sub Form1_KeyDown(...)
If (e.KeyCode = Keys.Right)
Then
picPlayer.Left = picPlayer.Left + 1
ElseIf (e.KeyCode = Keys.Left) Then
picPlayer.Left = picPlayer.Left - 1
ElseIf (e.KeyCode = Keys.Up) Then
picPlayer.Top = picPlayer.Top - 1
ElseIf (e.KeyCode = Keys.Down) Then
picPlayer.Top = picPlayer.Top + 1
End If
End Sub
or, to use letters on the keyboard,
Private Sub Form1_KeyDown(...)
If (e.KeyCode = Keys.d)
Then
picPlayer.Left = picPlayer.Left + 1
ElseIf (e.KeyCode = Keys.a) Then
picPlayer.Left = picPlayer.Left - 1
ElseIf (e.KeyCode = Keys.w) Then
picPlayer.Top = picPlayer.Top - 1
ElseIf (e.KeyCode = Keys.s) Then
picPlayer.Top = picPlayer.Top + 1
End If
End Sub
- A form's KeyPress method also allows
your program to respond to presses of various letter keys on the keyboard.
Private Sub Form1_KeyPress(...)
If (e.KeyChar = "d") Then
picPlayer.Left = picPlayer.Left + 1
ElseIf (e.KeyChar = "a") Then
picPlayer.Left = picPlayer.Left - 1
ElseIf (e.KeyChar = "w") Then
picPlayer.Top = picPlayer.Top - 1
ElseIf (e.KeyChar = "s") Then
picPlayer.Top = picPlayer.Top + 1
End If
End Sub
If you have placed one or more buttons on your form, you may need to set
the form's KeyPreview property to True in
order for the KeyPress method to work correctly.
- A MouseDown event
occurs when the user presses the mouse button somewhere on the form. The
following method displays the coordinates of where the mouse was clicked
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
Handles MyBase.MouseDown
If (e.Button = MouseButtons.Left) Then
MessageBox.Show("The mouse was clicked at (" + e.X.ToString + ", " +
e.Y.ToString + ")")
End If
End Sub
- A MouseUp event
occurs when the user releases the mouse button. Note that the MouseUp event
may occur in the very next instant after its corresponding MouseDown event
if the user clicked the mouse quickly. Or, if the user decides to hold down
the mouse button for a long time or he/she drags the mouse across the screen,
the MouseUp event will occur much later than its corresponding MouseDown event.
- A MouseMove event
occurs when the mouse's position changes. The following method displays the
coordinates of the mouse in two labels
Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
Handles MyBase.MouseMove
lblX.Text = e.X
lblY.Text = e.Y
End Sub
- The MouseLeave event occurs when the mouse leaves the
form. A MouseEnter event occurs when the mouse enters the forms. See the
following examples
Private Sub Form1_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs)
Handles MyBase.MouseLeave
lblElvis.Text = "Elvis has left the building"
lblX.Text = ""
lblY.Text = ""
End Sub
Private Sub Form1_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs)
Handles MyBase.MouseEnter
lblElvis.Text = "Elvis is in the building"
End Sub
Objective #15: Use Select
Case statements for multiple
selection.
- You will not be tested in this Visual
Basic class on Select Case statements however this objective
is included in the notes since you should at least be familiar with Select
Case statements since they are used by many programmers.
It is not necessary though to use Select Case statements
since If
ElseIf statements can be used to produce the same logic.
- 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
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.Text = "A"
Case 8
lblOutput.Text = "B"
Case 7
lblOutput.Text = "C"
Case 6
lblOutput.Text = "D"
Case Is <= 5
lblOutput.Text = "F"
Case Else
lblOutput.Text = "intGrade must have a bad value"
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.
- 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.