more code visual basic 2008 - morell regional high school ... · 09-10-2012 · more code –...

15
More Code Visual Basic 2008 Variables Storing and using values from within a computer program requires the use of storage containers called variables. A variable is a named memory location which stores the values or data used in a program. Each variable holds a specific data type. The type of variable, and thus the type of data, is determined by the programmer when the code is written. The two characteristics of variables are: Every variable has a name. Every variable can hold only one kind of data. Data Types Visual Basic works with all kinds of data. Before you learn how to manipulate data, you will learn how to distinguish among various data types. The various data types allow you to categorize data and perform specific functions on certain kinds of data. Visual Basic Type Prefix Storage Size Value Range Boolean bln 2 bytes True or False Date dat 8 bytes January 1, 0001 to December 31, 9999 Decimal dcm 16 bytes +/-79,228,162,514,264,337,593,543,950,335 with no decimal point; +/-7.9228162514264337593543950335 with 28 places to the right of the decimal; smallest non-zero number is +/-0.0000000000000000000000000001 Double (double- precision floating- point) dbl 8 bytes -1.79769313486231E+308 to 4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486231E+308 for positive values Integer int 4 bytes -2,147,483,648 to 2,147,483,647 Long (long integer) lng 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Short sht 2 bytes -32,768 to 32,767 Single (single- precision floating- point) sng 4 bytes -3.402823E+38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E+38 for positive values String (variable- length) str Depends on platform 0 to approximately 2 billion Unicode characters

Upload: trankhanh

Post on 06-Apr-2018

218 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: More Code Visual Basic 2008 - Morell Regional High School ... · 09-10-2012 · More Code – Visual Basic 2008 ... Names cannot contain punctuation or blank spaces. ... Label3 Name

More Code – Visual Basic 2008

Variables

Storing and using values from within a computer program requires the use of storage containers called variables. A variable is a named memory location which stores the values or data used in a program. Each variable holds a specific data type. The type of variable, and thus the type of data, is determined by the programmer when the code is written. The two characteristics of variables are: Every variable has a name. Every variable can hold only one kind of data.

Data Types

Visual Basic works with all kinds of data. Before you learn how to manipulate data, you will learn how to distinguish among various data types. The various data types allow you to categorize data and perform specific functions on certain kinds of data.

Visual Basic Type Prefix Storage Size Value Range

Boolean bln 2 bytes True or False

Date dat 8 bytes January 1, 0001 to December 31, 9999

Decimal dcm 16 bytes +/-79,228,162,514,264,337,593,543,950,335 with no

decimal point; +/-7.9228162514264337593543950335 with

28 places to the right of the decimal; smallest non-zero

number is +/-0.0000000000000000000000000001

Double (double-

precision floating-

point)

dbl 8 bytes -1.79769313486231E+308 to 4.94065645841247E-324 for

negative values; 4.94065645841247E-324 to

1.79769313486231E+308 for positive values

Integer int 4 bytes -2,147,483,648 to 2,147,483,647

Long (long integer) lng 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Short sht 2 bytes -32,768 to 32,767

Single (single-

precision floating-

point)

sng 4 bytes -3.402823E+38 to -1.401298E-45 for negative values;

1.401298E-45 to 3.402823E+38 for positive values

String (variable-

length)

str Depends on

platform

0 to approximately 2 billion Unicode characters

Page 2: More Code Visual Basic 2008 - Morell Regional High School ... · 09-10-2012 · More Code – Visual Basic 2008 ... Names cannot contain punctuation or blank spaces. ... Label3 Name

Defining Variables

To define a variable means to create and name the variable. Programs can have as many variables as you need to have. Before you use a variable, you should request that Visual Basic create the variable by defining the variable first. When you define a variable, you must decide the following characteristics:

Its name – what descriptive name will you choose.

Its data type — what kind of data it should hold

Its scope — what code should be able to refer to it without qualifying its name

Its access level — what code should have permission to read and write to it

Its lifetime — how long it should continue to exist

Rules for choosing names for variables:

Names of variables must begin with a letter.

Names cannot be longer than 255 characters, although 32 is the recommended maximum.

Names cannot contain punctuation or blank spaces.

Names are not case sensitive, thus Name, name and NAME are all the same in Visual Basic.

Names cannot be keywords (commands)

It is good practice for troubleshooting to use the prefixes for variable names.

Page 3: More Code Visual Basic 2008 - Morell Regional High School ... · 09-10-2012 · More Code – Visual Basic 2008 ... Names cannot contain punctuation or blank spaces. ... Label3 Name

Variable Scope Where you declare a variable is important because it determines which statements can access the variable. Variables that are declared within a procedure are considered to be local. These variables are only available within the procedure that they are declared.

When a variable is needed by more than one procedure in the Form class, the declaration should be at the module-level, above any procedures. These declarations are considered to be global.

Syntax: Variable Declaration Dim variableName As data type

Syntax: Variable Declaration Private variableName As data type

Page 4: More Code Visual Basic 2008 - Morell Regional High School ... · 09-10-2012 · More Code – Visual Basic 2008 ... Names cannot contain punctuation or blank spaces. ... Label3 Name

DIM statements can be used to declare several variables at once, using commas to separate the Variable names, if they have the same data type. This should only be done if the variables represent related items. Variable Lifetime The lifetime of a variable refers to how long they exist in memory. The lifetime of a local variable is the duration of the procedure in which it was declared. The lifetime of a global variable is the duration of the program. By using a Static declaration, the lifetime of a local variable can be extended to the life of the program.

Syntax: Variable Declaration Dim variableName1, variableName2, variableName3 As datatype

Syntax: Variable Declaration Static variableName As data type = initialValue

Page 5: More Code Visual Basic 2008 - Morell Regional High School ... · 09-10-2012 · More Code – Visual Basic 2008 ... Names cannot contain punctuation or blank spaces. ... Label3 Name

Initial values Once declared, all variables are assigned an initial value. All numeric data types are initialized to 0 (zero). String variables are initialized to an empty string (" "). Boolean variables are initialized as False. It is important to realize that a variable can store only one value at any one time.

Option Explicit/Option Infer Variables are internal labels that the user of the program does not see. Visual Basic does not require that variables be declared before you use them. This could cause problems if you misspell variables when assigning values to them. You may get results that you do not want. To avoid this, use the Option Explicit On statement in the General declarations section of the Code editor (above Public Class statement). Option Explicit will display an error message at runtime when a variable is used before it is declared. Similarly, the Option Infer Off statement ensures that every variable is declared with a data type.

Page 6: More Code Visual Basic 2008 - Morell Regional High School ... · 09-10-2012 · More Code – Visual Basic 2008 ... Names cannot contain punctuation or blank spaces. ... Label3 Name

Assigning values to variables

The value of a variable is changed through an assignment statement. The variable assignment statement has the variable on the left side of an equals sign and a literal, expression, or variable that it is to receive on the left side. (A literal is any actual value. String literals must be in double quotation marks). Visual Basic will convert data from one type to another when a variable is being assigned as long as the data is valid for the receiving data type. For instance, numeric data can be converted from decimal to integer with no problems, however, placing text data into a numeric data type variable will produce an error. Constants A constant is a data value that does not change. They are used in order for values to be represented with meaningful names and so that programs can easily be changed. Constant names are typically all uppercase. The value of the constant is only assigned in the declaration of the constant. Declaration is typically in the Form class, outside of any procedures (before variables).

Syntax: Assignment Statement variableName = literal/expression/variable

Syntax: Constant Declaration Const constant_name As datatype = value

Page 7: More Code Visual Basic 2008 - Morell Regional High School ... · 09-10-2012 · More Code – Visual Basic 2008 ... Names cannot contain punctuation or blank spaces. ... Label3 Name

Keywords

VB has many keywords, which have a specific meaning. These words should not be used when declaring variables or constants.

And Dim False Long Return

Boolean Do Finally Me Select

Byte Double For Mod Short

Call Each Friend Module Single

Case Else Function New Static

Catch ElseIf Get Not Stop

Const End Handles Nothing String

Date Enum If Object Structure

Decimal Erase In Or Sub

Declare Error Integer Private Then

Default Event Is Protected To

Delegate Exit Like Public True

Programming Errors

Syntax errors, logical errors and run-time errors are the three types of errors that can

occur in a program.

Syntax errors occur when the “language” of Visual Basic is violated. In Visual Studio

2008, a blue wavy underline will indicate a syntax error. Hovering the mouse over the line will

display help text.

Logic errors occur when the desired output is not achieved. Logical errors are more

difficult to detect than syntax errors. Logic errors are often found when testing the programs

functionality.

Run-time errors often caused by a statement that cannot be executed will halt the

program. You must stop the debugging process and correct the error if this occurs.

Page 8: More Code Visual Basic 2008 - Morell Regional High School ... · 09-10-2012 · More Code – Visual Basic 2008 ... Names cannot contain punctuation or blank spaces. ... Label3 Name

Mathematical Operations Expressions are mathematical statements. Because we are dealing with numbers, we do not need to put the statements in quotation marks. Expressions follow order of operations (BEDMAS). Operators are as follows:

exponents- ^

division - /

multiplication - *

integer division - \ (returns the integer of the division)

modulus- MOD (Determines the remainder)

addition - +

subtraction- -

brackets - ( & ) Functions VB has many built in functions. A function is a type of procedure or method that performs a task and returns a value. A function may require data to perform its task. The data is “passed” to the function as arguments enclosed in parentheses after the function name. Strings to Numbers To convert a number string into a numerical value, use the VAL( ) function. This must be used if you are receiving data from a user and you want to perform mathematical operations on it.

Val can convert only string characters that represent numbers. Any character after numbers are ignored. If Val can’t convert the string at all, it returns a value of zero (0).

Syntax: Convert Strings to Numerical values variable_name = VAL ( “string” )

Page 9: More Code Visual Basic 2008 - Morell Regional High School ... · 09-10-2012 · More Code – Visual Basic 2008 ... Names cannot contain punctuation or blank spaces. ... Label3 Name

Formatting Numbers The Format ( ) function converts a number to a formatted string. When this function is used, the string that is returned can no longer have mathematical operations performed on it. This function is useful in displaying numeric data in values such as currency or percent. Number is a numeric variable or value Format type is a predefined Visual Basic format such as Percent, Currency, Scientific, General Number (no commas), Fixed (2 decimals), or Standard (2 decimals with commas).

Obtaining values from the User An application is interactive if and only if the user of the application can enter data and the application then responds to that data in some way. There are several ways in which you can obtain information from a user. The most common way would be to use a textbox. At run time, the TextBox Text property stores whatever characters are currently in the text box. The value in the text property can be assigned to a variable and stored for the program to use. variableName would be a variable that has been previously declared. Me indicated that the present form is being used. If more than one form is available for the program, the name of the form should be placed here. txtTextBox_Name is the name of the text box you are retrieving information from. Text is the property that you are retrieving information from. Characters are always read as string data types, thus numbers entered into a text box will be required to be converted to numbers.

Syntax: Formatting Numbers variable_name = Format(number, “format type”)

Syntax: Obtaining values variableName = Me.txtTextBox_Name.Text

Page 10: More Code Visual Basic 2008 - Morell Regional High School ... · 09-10-2012 · More Code – Visual Basic 2008 ... Names cannot contain punctuation or blank spaces. ... Label3 Name

Concatenating information

The & symbol is used to combine information in an assignment statement. It can be

used to combine variables, strings, or a combination. More than one & can be used to

concatenate more than two items.

Syntax: Concatenating variableName = SecondVariable & “ a literal string.”

Page 11: More Code Visual Basic 2008 - Morell Regional High School ... · 09-10-2012 · More Code – Visual Basic 2008 ... Names cannot contain punctuation or blank spaces. ... Label3 Name

Lab #3 We will create a program that will allow the user to enter the length of a side of a square and the units and return the Area of the associated Square. Open VB Studio 2008 and

Create a Project.

Give the project the name

Square Area Calculator

Add 4 Labels, two Textboxes

and three Buttons to the

Form.

Make the following changes to the Controls.

Label1

Name – lblLength

Text – Length of side

Label2

Name – lblUnits

Text – Units

Label3

Name – lblResults

Text – Results

Label4

Name – lblSquareUnits

Text – Square Units

TextBox1

Name – txtLength

Text – blank

TextBox2

Name – txtUnits

Text – blank

Page 12: More Code Visual Basic 2008 - Morell Regional High School ... · 09-10-2012 · More Code – Visual Basic 2008 ... Names cannot contain punctuation or blank spaces. ... Label3 Name

Button1

Name – cmdCalculate

Text – Calculate

Button2

Name – cmdClear

Text – Clear

Button 3

Name – cmdExit

Text – Exit

Form1

Name - frmSquareArea

Text – Square Area Calculator

In this program, we are going to code for three events, all clicks of the mouse on the buttons for calculate, clear and exit. When the Exit button is clicked, the program will close. We have seen this code in the last lab. When the Clear button is clicked, the values in the two textboxes and the values in the Square Units label will be cleared (Square Units caption will change to reflect the actual square units of the area of the square. When the Calculate button is clicked, the program will retrieve that values that are inputted from the user and calculate the area of the square and then place the results into the Square Units label.

Page 13: More Code Visual Basic 2008 - Morell Regional High School ... · 09-10-2012 · More Code – Visual Basic 2008 ... Names cannot contain punctuation or blank spaces. ... Label3 Name

Planning: For this program we will need the following: Formulas: Area = Length2

Variables:

Area – needs to be a number, decimals should be allowed Length of the side – needs to be a number, decimals should be allowed Units of measurement – needs to be a string The scope of these variables needs only to be used within the form class, thus, they should be declared after Public Class and before any of the subroutines using Private. The flowchart for the Calculate subroutine looks like this:

Page 14: More Code Visual Basic 2008 - Morell Regional High School ... · 09-10-2012 · More Code – Visual Basic 2008 ... Names cannot contain punctuation or blank spaces. ... Label3 Name

Pseudo-code Pseudo-code consists of short English phrases used to explain specific tasks within a program's algorithm. Pseudo-code can include keywords in a specific computer language and should be written as a list of consecutive phrases. You should not use flowcharting symbols in your pseudo-code. Much like the real program, indentation can be used to show the logic in pseudo-code as well. One programmer should be able to take another programmer's pseudo-code and generate a program based on that in any language. Because the programming process is a complicated one, you must first understand the program specifications (what the customer wants the program to do and what the interface will look like). Then you need to organize your thoughts and create the program. You must break the main tasks that must be accomplished into smaller ones in order to be able to eventually write fully developed code. Write a short phrase to describe the tasks that need to be accomplished. There may eventually be a one-to-one correlation between the lines of pseudo-code and the lines of the code that you write for the actual program. Writing pseudo-code will save you time later during the construction and testing phase of a program's development. Pseudo-code: cmdExit _Click Exit program End Sub cmdClear_Click clear contents of textboxes (set to empty strings) reset label for results to “Square Units” End Sub cmdCalculate_Click get user input from text boxes and put them into variables calculate area (Area = length2) display the area in the Square Units label End Sub

Page 15: More Code Visual Basic 2008 - Morell Regional High School ... · 09-10-2012 · More Code – Visual Basic 2008 ... Names cannot contain punctuation or blank spaces. ... Label3 Name

Code: Comments at the start of the program should indicate the name of the program, what the program does, who wrote it and when, when it was last modified and any known problems. 'Square Area Calculator

'purpose: to introduce variables to students.

'Program will request a length and unit of

'measurement from the user and return the area

'of a sqaure that has that length measurement.

'Written by Computer Teacher, One day

'Modified by you, today

Option Explicit On Ensure variables are declared with a data type Option Infer Off before they are used in the program

Public Class frmMainForm

'Variable declaration

Private sngArea As Single

Private sngLength As Single

Private strUnits As String

Private Sub cmdExit_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles cmdExit.Click

Me.Close()

End Sub

Private Sub cmdClear_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles cmdClear.Click

'Clear text boxes and the label

Me.txtLength.Text = " " Empty strings will clear a text box Me.txtUnits.Text = " " Ensure that the property is included in the Me.lblSquareUnits.Text = "Square Units" assignment statements End Sub

Private Sub cmdCalculate_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles cmdCalculate.Click

'get information from the text boxes, calculate the area

'and display the results in a label.

sngLength = Val(txtLength.Text) Use of Val ensures the variable is a number strUnits = txtUnits.Text Best practice assigns values to a variable sngArea = sngLength ^ 2 from a text box lblSquareUnits.Text = sngArea & strUnits & " squared"

End Sub

End Class

Do Not forget to save often and test code.