Visual Basic Guided Tour

Embed Size (px)

Citation preview

  • 8/2/2019 Visual Basic Guided Tour

    1/9

    Visual Basic Guided Tour

    Words and Text: Using String Variables to Organize Words

    What Is a String?

    A string is any series of text characters, such as letters, numbers, special characters, and spaces. Stringscan be human-readable phrases or sentences, such as "The quick brown fox jumps over the lazy dog," or an

    apparently unintelligible combination, such as "@#fTWRE 3 35Gert".

    String variables are created just as other variables: by first declaring the variable and assigning it a value,as shown here.

    Visual Basic

    Copy CodeDim aString AsString = "This is a string"

    When assigning actual text (also called a string literal) to a String variable, the text must be enclosed inquotation marks (""). You can also use the = character to assign one String variable to another String

    variable, as shown in this example.

    Visual Basic

    Copy CodeDim aString AsString = "This is a string"

    Dim bString AsString = ""bString = aString

    The previous code sets the value ofbString to the same value as aString (This is a string).

    You can use the ampersand (&)character to sequentially combine two or more strings into a new string, as

    shown here. This is also known as concatenation.

    Visual Basic

    Copy CodeDim aString AsString = "using string"Dim bString AsString = "variables"Dim cString AsString = ""cString = aString & bString

    The previous example declares three String variables and respectively assigns "using string" and "variables"to the first two, and then assigns the combined values of the first two to the third variable. What do youthink the value ofcString is? You might be surprised to learn that the value is using stringvariables

    because there is no space at the end ofaString or at the start ofbString. The two strings are just joined

    together. If you want to add spaces or anything else between two strings, you must do so with a stringliteral, such as " ", as shown here.

    Visual Basic

    Copy CodeDim aString AsString = "using string"Dim bString AsString = "variables"Dim cString AsString = ""cString = aString & " " & bString

    The text that is contained in cString now reads as using string variables.

  • 8/2/2019 Visual Basic Guided Tour

    2/9

    Try It!

    To join strings

    1. On the File menu, click NewProject.2. In the New Project dialog box:

    a.

    In the Templates pane, click Windows Application.b. In the Name box, type Concatenation.c. Click OK.A new Windows Forms project opens.

    3. Double-click the form to open the Code Editor.4. In the Form1.Load event procedure, declare four string variables and assign the string values, as

    shown here:

    Visual Basic

    Copy Code

    Dim aString AsString = "Concatenating"Dim bString AsString = "Without"Dim cString AsString = "With"Dim dString AsString = "Spaces"

    5. Add the following code to concatenate the strings and display the results:Visual Basic

    Copy Code' Displays "ConcatenatingWithoutSpaces".MsgBox(aString & bString & dString)

    ' Displays "Concatenating With Spaces".MsgBox(aString & " " & cString & " " & dString)

    6. Press F5 to run your program.The text displayed in the message box is the result of joining the string variables that were assigned ina previous step. In the first box, the strings are joined together without spaces. In the second, spacesare explicitly inserted between each string.

  • 8/2/2019 Visual Basic Guided Tour

    3/9

    Arrays: Variables That Represent More Than One Value

    As explained in previous lessons, variables are used to store different types of data for use by your program.There is another type of variable called an arraythat provides a convenient way to store several values ofthe same type.

    For example, suppose you were writing a program for a baseball team and you wanted to store the namesof all the players on the field. You could create nine separate string variables, one for each player, or youcould declare an array variable that looks something like the code that is shown here.

    Visual Basic

    Copy CodeDim players() AsString

    You declare an array variable by putting parentheses after the variable name. If you know how many valuesyou have to store, you can also specify the size of the array in the declaration as follows.

    Visual Basic

    Copy CodeDim players(8) AsString

    The size of the array is 9 because a baseball team has 9 players. An array consists of a number of values, or

    elements, which are referenced by unique index values, starting with 0. The index value of the final elementis always one less than the size of the array. In this case, the array contains the elements 0 through 8, for atotal of nine elements. When you want to refer to one of the players on the team, you just subtract 1. Forexample, to reference the first player, you reference element 0, to reference the ninth player, you referenceelement 8.

    Assigning Values to Arrays

    As with other types of values, you have to assign values to arrays. To do so, you refer to the elementnumber as part of the assignment, as shown here.

    Visual Basic

    Copy Codeplayers(0) = "John"players(3) = "Bart"

    In the previous code, the value John is assigned to the first element of the array (element 0) and the value

    Bart is assigned to the fourth element (element 3). The elements of the array don't have to be assigned in

    order, and any unassigned element will have a default valuein this case, an empty string.

    As with other types of values, you can declare and assign values to an array on a single line as follows.

    Visual Basic

    Copy CodeDim players() AsInteger = {1, 2, 3, 4, 5, 6, 7, 8, 9}

    In this case, braces indicate a list of values. The values are assigned to elements in the order listed. Noticethat size of the array isn't specifiedit is determined by the number of items that you list.

    Retrieving Values from Arrays

  • 8/2/2019 Visual Basic Guided Tour

    4/9

    Just as you use numbers to specify an item's position in an array, you use the element number to specifythe value that you want to retrieve.

    Visual Basic

    Copy CodeDim AtBat AsString

    AtBat = players(3)

    The above code retrieves the fourth element of the array and assigns it to the string variable AtBat.

    Try It!

    To store values in an array

    1. On the File menu, click New Project.2. In the New Project dialog box, in the Templates pane, click Windows Forms Application.3. In the Name box, type MyFirstArray and then click OK.

    A new Windows Forms project opens.

    4. From the Toolbox, drag a Textbox control onto the form.5. From the Toolbox, drag a Button control onto the form.6. Double-click the Button to open the Code Editor.7. In the Button1_Click event procedure, add the following code:

    Visual Basic

    Copy CodeDim players() AsString = {"Dan", "Fred", "Bart", "Carlos", _"Ty", "Juan", "Jay", "Sam", "Pedro"}

    Dim i AsInteger = CInt(Textbox1.Text)

    MsgBox(players(i) & " is on first base.")Notice that the previous code uses the CInt function to convert the String value (TextBox1.Text) to

    an Integer (i).

    8. Press F5 to run the program.9. Type a number between 0 and 8 in the text box and click the button. The name corresponding to that

    element is displayed in a message box.

  • 8/2/2019 Visual Basic Guided Tour

    5/9

    Arithmetic: Creating Expressions with Variables and

    Operators

    An expression is a segment of code that performs arithmetic and then returns a value. For example, asimple addition expression is shown here:

    5 + 4

    The expression 5 + 4 returns the value 9 when evaluated and consists of two parts: the operands(5 and 4),

    which are the values that the operation is performed on, and the operator(+), which specifies the operation

    to be performed.

    Using Values Returned by Expressions

    For an expression to be useful, you must do something with the value that is returned. The most commonthing to do is to assign it to a variable, as shown here:

    Visual Basic

    Copy Code

    Dim anInteger AsInteger = 5 + 4

    This example declares a new Integer variable called anInteger and assigns the value returned by 5 + 4

    to it.

    Arithmetic Operators

    A common use for expressions is to perform arithmetic on variables: addition, subtraction, multiplication, ordivision. The following table describes the operators frequently used for arithmetic.

    Operator Description Example

    + (addition) Returns the sum of two operands 5 + 4

    - (subtraction) Returns the difference of two operands 5 - 4

    * (multiplication) Returns the product of two operands 5 * 4

    / (division) Returns the quotient of two operands 5 / 4

    The kind of variable that you use when you perform arithmetic can affect the result. Dividing two numbersoften results in a return value that is not a whole number. For example, when you divide 3 by 2, the result is1.5. If you assigned the return value of that expression to an Integer variable, it would be rounded to thenearest whole number, 2. When performing division, you should use a Double variable to store the returnvalue.

    Try It!

    To add numbers

    1. On the File menu, click New Project.2. In the New Project dialog box, in the Templates pane, click Windows Application.3. In the Name box, type Arithmetic and then click OK.

    A new Windows Forms project opens.

    4. From the Toolbox, drag two Textbox controls onto the form.5. From the Toolbox, drag a Button control onto the form.6. Double-click the Button to open the Code Editor.7. In the Button1_Click event procedure, type the following code.

  • 8/2/2019 Visual Basic Guided Tour

    6/9

    Visual Basic

    Copy CodeDim A AsDouble = Textbox1.Text

    Dim B AsDouble = Textbox2.Text

    MsgBox(A + B)MsgBox(A - B)MsgBox(A * B)MsgBox(A / B)

    The first two lines declare the variables A and B. A and B will hold the numeric values used in this

    program and assign the values of the two TextBox controls (their text) to the variables A and B.

    The final four lines create expressions with the two variables and each of the basic arithmeticoperators, and display the results of those expressions in a message box.

    8. Press F5 to run the application.9. Type a number in each text box and click Button1.

    Note:

    If you type any other character into the text boxes, an error will occur.

    10. Expressions are created by using the two numbers that you enter and each of the four basic arithmeticoperators (addition, subtraction, multiplication, and division). The result of each expression isdisplayed in a message box

  • 8/2/2019 Visual Basic Guided Tour

    7/9

    Using Expressions to Compare Values

    The last lesson showed how to use arithmetic operators to create numeric expressions and return numericvalues. Another kind of operator, the comparison operators, can be used to compare numeric values andreturn Boolean (True or False) values.

    The following table summarizes the comparison operators:

    Operator Description Examples

    = (equals) Returns True if the number on the left-hand side is equal to thenumber on the right-hand side.

    5 = 4 (false)

    4 = 5 (false)

    4 = 4 (true)

    (not equal to) Returns True if the number on the left is not equal to thenumber on the right.

    5 4(true)

    4 5(true)

    4 4(false)

    > (greater than) Returns True if the number on the left is greater than thenumber on the right.

    5 > 4 (true)

    4 > 5 (false)

    4 > 4 (false)

    < (less than) Returns True if the number on the left is less than the numberon the right.

    5 < 4 (false)

    4 < 5 (true)

    4 < 4 (false)

    >= (greater than orequal to)

    Returns True if the number on the left is greater than or equalto the number on the right.

    5 >= 4(true)

    4 >= 5(false)

    4 >= 4

    (true)

  • 8/2/2019 Visual Basic Guided Tour

    8/9

    Copy CodeDim A AsDouble = CDbl(Textbox1.Text)Dim B AsDouble = CDbl(Textbox2.Text)MsgBox(A > B)

    MsgBox(A < B)MsgBox(A = B)

    The first two lines declare the variables A and B, which will hold the numeric values used in this

    program; they use the CDbl statement to convert the text from Textbox1 and Textbox2 into numeric

    values. Finally, the last three lines create expressions to compare the two variables using three basiccomparison operators, and display the results of those expressions in three message boxes.

    8. Press F5 to run the application.9. Type a number in each of the text boxes and click Button1.

    The first message box will display True ifA (the number that you entered in the first text box) is

    greater than B (the number that you entered in the second text box); otherwise it will display False.

    The second message box will display True ifA is less than B, and the third message box will display

    True if both numbers are the same.

    Try typing different numbers into the text boxes to see how the results change.

  • 8/2/2019 Visual Basic Guided Tour

    9/9