VB Lecture Notes - Assignment Statements
Objective #1: Use assignment statements to calculate and store mathematical results and to change the properties of objects.
- An assignment statement is a statement that is used to store a value into a variable or object's property.
- Assignment statements evaluate the mathematical expression on the right-hand side of the assignment operator and assigns the resulting value into the variable on the left-hand side
of the equals symbol (which is known as the "assignment operator").
- For example, the statement
intNum = 5
is an assignment statement that stores the value 5 into the variable named intNum.
Instead of a simple numerical value like 5, a more complicated mathematical expression can be typed on the right side of the equals symbol as in
dblAnswer = intNum * 2 + intNum * 2 * 0.06
where the righthand side of the equals symbol must be simplified first before the final result is assigned to the variable dblAnswer.
- Never type an assignment statement with a mathematical expression on the left of the equals symbol ( e.g. )
since it causes a compile error. For example the following examples would cause a compile error
5 = intAnswer
5 + intNum = intAnswer
- An assignment statement can also store a string value (which is a word or phrase) into a String variable as in the following examples
strName = "Wyomissing"
strName = lblName.Text
- An assignment statement can also store a string variable or a literal string value into the Text property of an object such as a label:
lblName.Text = strName
lblName.Text = "Wyomissing"
- The concatenation operator ( + ) can be used in assignment statements. For example,
lblName.Text = "Wyomissing" + " Area High School"
lblName.Text = strFirstName + " " + strLastName
lblName.Text = "Mr. " + strLastName
- You can assign the empty string (aka null string) to a string variable or the Text property of an object such as a label. For example,
strName = ""
lblName.Text = ""
The empty string is represented as two double quote symbols typed next to each other with no space in between.
- You can even make an object disappear by using the Visible property in the following statement
lblMessage.Visible = False
The Visible property is used to make an object or 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.
- If a statement is cut-off along the right edge of the paper when a program is printed out, it is necessary to break up the statement so that it appears over two lines of code.
This can be done by typing the line continuation operator ( _ ) after a space anywhere next to an operator. The continued second line of code should be indented for good style. For
example, rather than
dblPrice = dblPRICE_PER_BOOK * intNumBooks + dblPRICE_PER_BOOK * intNumBook * PA_SALES_TAX_RATE
you could type out
dblPrice = dblPRICE_PER_BOOK * intNumBooks + dblPRICE_PER_BOOK * _
intNumBook * PA_SALES_TAX_RATE
Objective #2: Convert string values to numeric values.
- You must be careful distinguish between string data and numeric data (which includes Integer & Double).
For example, the string "13" is not equivalent to the number 13 just as the string "19610" (pronounced "one nine six one zero" like Wyomissing's zip code) is not equivalent to the number 19610 (pronounced "nineteen thousand six hundred and ten.")
- Double quotations are used to show that the "13" is being treated as a string value and therefore it should not be added, subtracted, etc. with a number. Wouldn't it be dumb to add 13 to your zip code!?
- With the Val function, one could change "13" into
13 as in
intNum = Val("13")
- The CInt function can also be used
to change "13" into 13 as in
intNum = CInt("13")
There are some subtle differences between the Val and CInt functions however but you are not responsible for knowing these differences in this VB course.
Objective #3: Convert numeric values to string values.
- The Str function can be used to change
the numerical value 19610 into the string "19610" as in
strZipCode = Str(19610)
- The ToString method can also be used
to change a numeric variable into a string. The statement
Dim intNum As Integer = 19610
Dim strZipCode As String = "00000"
strZipCode = intNum.ToString()
causes the string "19610" to be stored in strZipCode. Notice the required empty parentheses after the ToString method.
Objective #4: Write a method that uses declaration and assignment statements.
- So let's say that you want to write a computer program that computes your grade for a class at school.First you must be able to compute
your grade by hand with a calculator or scratch paper. How can you train a computer to compute your grade if you do not know how to perform the algorithm yourself? So you add up the points earned
on all of your homeworks and tests and divide by the sum of the points possible for those assignments. This gives you your grade percentage. Okay, so how many numbers do you end up scribbling onto
your scratch paper as partial subtotals or intermediate calculations? Probably three. You added up the points earned as one subtotal. You added up the points possible as another subtotal. And, the
quotient that you calculated by dividing those two numbers was a third important number that you wrote down.
What would be three good, descriptive variable names for those three values and
are they whole numbers or decimal numbers? The variable names intPointsEarned and intPointsPossible would be good names for the first two and there data type should be Integer since they would always
be whole numbers. Do not use short variable names like x and y or even intPE and intPP since you probably wouldn't remember what those cryptic names mean if you needed to update your program a few
years later. In fact, ask your math teacher sometime why you've been using x and y as varaible names in math class all of these years. Those problems don't seem to relate to the real world like computer
programs where every program has meaning and variable names that explain the purpose of a given program. The other variable could be named dblGradeAverage and it should be a Double rather than an
Integer since it is likely to store decimal numbers.
Next you need to declare these variables with declaration statements and initialize them to the appropriate values.
Dim intPointsEarned As Integer = 90
Dim intPointsPossible As Integer = 100
Dim dblGradeAverage As Double = 0
Then you write one or more assignment statements to perform the calculation
dblGradeAverage = intPointsEarned / intPointsPossible
Finally you decide that you want to display the answer in a message box with the statement
MessageBox.Show(dblGradeAverage)
All of this code could be typed into the Click method of a button named btnCompute as in
Private Sub btnCompute_Click( )
Dim intPointsEarned As Integer = 90 ' total pts earned
Dim intPointsPossible As Integer = 100 ' total pts possible
Dim dblGradeAverage As Double = 0 ' student's grade average
dblGradeAverage = intPointsEarned / intPointsPossible
MessageBox.Show(dblGradeAverage)
End Sub
- It is usually possible to accomplish a task with many variables or with no variables! For example, the following two code segments
produce the same results
Short Version
lblAve.Text = Str((Val(txtScore1.Text) + _
Val(txtScore2.Text) + Val(txtScore3.Text)) / 3)
Long Version
Dim intTest1 As Integer = 0 ' student's 1st test score
Dim intTest2 As Integer = 0 ' student's 2nd test score
Dim intTest3 As Integer = 0 ' student's 3rd test score
Dim dblAverage As Double = 0 ' student's average test score
intTest1 = Val(txtScore1.Text)
intTest2 = Val(txtScore2.Text)
intTest3 = Val(txtScore3.Text)
intSum = intText1 + intTest2 + intTest3
dblAverage = intSum / 3.0
lblAve.Text = Str(dblAverage)
There are a number of differences between the two code segments besides the obvious difference in length. The short version does not use any variables. Instead, it
computes the results by directly working with the textboxes and label. This does save some memory since no variables are declared but using variables makes it easier to maintain and upgrade a program.
The use of variables in the long version gives the programmer the opportunity to document and explain each of the variables and this makes the program easier for other programmers to understand.
For example, in the long version, it is not understood that it is a student's test scores that are being averaged. The long version is nicely spaced out as well making the code easier to read and
analyze.
- Assignment statements can be used to overwrite the values stored in variables as the program executes from top to bottom.
Dim intX As Integer = 1
Dim intY As Integer = 2
Dim intResult As Integer = intX + intY
lblResult.Text = Str(intResult) ' lblResult contains 3
intX = 5
lblResult.Text = Str(intResult) ' lblResult still contains 3 not 7
intResult = intX + intY
lblResult.Text = Str(intResult) ' lblResult now contains 7
Some students mistakenly believe that intResult is initially tied to the formula intX + intY. This is incorrect since only the current values stored in intX and intY are used to create the sum that's
initially stored in intResult.