0% found this document useful (0 votes)
8 views

JK VB - NET - 4 - Input Output Variables DataTypes

Uploaded by

curtisandrea242
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

JK VB - NET - 4 - Input Output Variables DataTypes

Uploaded by

curtisandrea242
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 45

Input, Output, Variables, DataTypes, and

Calculations
Introduction
 This presentation will covers the use of text
boxes to gather input from users
 It also discusses the use of
 Variables

 Named constants

 Common Arithmetic Operators

Slide 3- 2
Class Exercise
write these question down
1. Write a program that capture your name through
a textbox and display the name entered on the
textbox through a label after clicking on a button.

2. Adjust the program above to attach the word


Hello to any name captured through the textbox
(eg Hello Mary)
3. Write a program that make use of textboxes to
capture two numbers and sums them and finally
displays the results through a label.
Slide 3- 3
Gathering Text Input

In This Section, We Use the


Textbox Control to Gather Input
That the User Has Typed on the
Keyboard
The TextBox Control
 A text box is a rectangular area on a form that
accepts input from a keyboard
 Tutorial 3-1 provides an example in the use of a
text box

txtUserName
lblGreeting
btnClose
btnShowGreeting

Slide 3- 5
The Text Property of a TextBox
 A user can change the text property of a text box
simply by typing in the text box
 A programmer can change the text property of a
text box with an assignment statement
 Uses the form Object.Property similar to

working with the text property of a label


 The following code assigns the text to the right

of the equal sign to the text property of a


TextBox box txtInput left of the equal sign
 txtInput.Text = “Type your name”

Slide 3- 6
The Text Property of a TextBox
 We can also use the text property of a text box to
retrieve something the user has typed
 The following code assigns the text in txtInput

to the text property of the label lblSet


 lblSet.Text = txtInput.Text

 Once again we use the form Object.Property

 This is the standard format to refer to any

property of any object

Slide 3- 7
Clearing a TextBox
 Can be done with an assignment statement:
 txtInput.Text = ""

 Two adjacent quote marks yields a null string

 So this replaces whatever text was in txtInput

with "nothing" -- a string with no characters


 Can also be done with a method:
 txtInput.Clear()

 Clear is a Method, not a Property

 Methods are actions – as in clearing the text

 Uses the form Object.Method

Slide 3- 8
String Concatenation
 We often need to combine two or more strings
into a longer one
 This operation is called Concatenation
 Concatenation is signaled by the '&' operator in
the same way addition is signaled by a '+'

Slide 3- 9
String Concatenation
 Assume the user has entered their name into the
TextBox txtName
 Label lblGreeting can say, “Hello” to any name
found in the TextBox
 lblGreeting.Text = "Hello " & txtName.Text
 Appends user name in txtName.Text to “Hello ” and
stores result in text property of lblGreeting

Slide 3- 10
String Concatenation
 Tutorial 3-2 provides another example of how to
concatenate strings from text boxes

txtDayOfWeek

txtMonth

txtDayOfMonth

txtYear

lblDateString

btnExit
btnClear
btnShowDate

Slide 3- 11
Aligning Controls in Design Mode
 When dragging a control to a form, it can be
aligned with a control already on the form
 Guide lines automatically appear
 Blue guide lines appear for vertical alignment

 Lavender guide lines for horizontal alignment

 Horizontal alignment example

Slide 3- 12
'&' Has Special Meaning in a Button
 Note that the '&' in "&Save"
does not display in the
button control on the form
 It simply establishes the Alt
Key access
 In order to actually display
an '&' on a button, it must
be entered as "&&“
 Button text Save & Exit is

entered as Save && Exit


Slide 3- 13
Variables and Data Types

Variables Hold Information That May Be


Manipulated, Used to Manipulate Other
Information, or Remembered for Later Use
Why Have Variables?
 A variable is a storage location in the computer’s
memory, used for holding information while the
program is running
 The information that is stored in a variable may
change, hence the name “variable”
 A variable is a named memory location that can
change dynamically during program execution

Slide 3- 15
What Can You Do With Variables?
 Copy and store values entered by the user, so
they may be manipulated
 Perform arithmetic on values
 Test values to determine that they meet some
criterion
 Temporarily hold and manipulate the value of a
control property
 Remember information for later use in the
program

Slide 3- 16
How to Think About Variables
 You the programmer make up a name for the
variable
 Visual Basic associates that name with a location
in the computer's RAM
 The value currently associated with the variable
is stored in that memory location

Slide 3- 17
Declaring Variables
 A variable declaration is a statement that creates
a variable in memory
 The syntax is
Dim VariableName As DataType
 Dim (short for Dimension) is a keyword
 VariableName is the programmer designated name
 As is a keyword
 DataType is one of many possible keywords for the
type of value the variable will contain
 Example: Dim intLength as Integer
Slide 3- 18
Declaring Multiple Variables
 Several variables may be declared in one
statement if they all hold the same type of value

Dim intLength, intWidth, intHeight as Integer

 Or this can be done in 3 separate statements


Dim intLength as Integer
Dim intWidth as Integer
Dim intHeight as Integer

Slide 3- 19
Setting the Value of a Variable
 An assignment statement is used to set the value
of a variable, as in:
 Assign the value 112 to the variable length

length = 112
 Assign the string literal “Good Morning “
followed by the contents of the text box
txtName to the variable greeting
greeting = "Good Morning " & txtName.Text
 An assignment changes only the left operand
 The right operand remains unchanged
Slide 3- 20
Visual Basic Data Types

 Integer types  Other data types


 Byte  Boolean
 Short  Char
 Integer  String
 Long  Date
 Floating-Point types
 Single
 Double
 Decimal

Slide 3- 21
Integer Data Types
 For values that will always be a whole number
 Usually name a variable starting with a 3 or 4
letter prefix indicating the variable’s type

Data Naming Description


Type Prefix
Byte byt Unsigned integer from 0 to 255
Short shrt Signed integer from -32,768 to 32,767
Integer int Signed integer from -2,147,483,648 to 2,147,483,647
Long lng Signed integer from -9,223,372,036,854,775,808
to 9,223,372,036,854,775,807

Slide 3- 22
Floating-Point Data Types
 For values that may have fractional parts
 Single used most frequently
 Double sometimes used in scientific calculations
 Decimal often used in financial calculations
Data Naming Description
Type Prefix
Single sng As large as 1038 plus or minus, 7 decimal positions
Double dbl As large as 10308 plus or minus,15 decimal positions
Decimal dec As large as 1029 plus or minus, 29 decimal positions

Slide 3- 23
Other Common Data Types
 Boolean – variable naming prefix is bln
 Holds 2 possible values, True or False

 Char – variable naming prefix is chr


 Holds a single character

 Allows for characters from other languages

 String – variable naming prefix is str


 Holds a sequence of up to 2 billion characters

 Date – variable naming prefix is dat


 Can hold date and/or time information

Slide 3- 24
Working with the String Data Type
 A string literal is enclosed in quotation marks
 The following code assigns the name Jose Gonzales to
the variable strName
Dim strName as string
strName = "Jose Gonzales"
 An empty string literal can be coded as:
 Two consecutive quotation marks

strName = ""
 Or by the special identifier String.Empty
strName = String.Empty

Slide 3- 25
Assigning Text to a Variable
 Tutorial 3-6 provides an example of how the
contents of text boxes are assigned to a string
variable
' Declare a string variable to hold the full name.
Dim strFullName As String

' Combine the first and last names


' and copy the result to lblFullName
strFullName = txtFirstName.Text & " " & txtLastName.Text
lblFullName.Text = strFullName

Slide 3- 26
Variable Naming Rules
 The first character of a variable name must be a
letter or an underscore
 Subsequent characters may be a letter,
underscore, or digit
 Thus variable names cannot contain spaces or

periods (or many other kinds of characters)


 Visual Basic keywords cannot be used as
variable names

Slide 3- 27
Variable Naming Conventions
 Naming conventions are a guideline to help
improve readability but not required syntax
 A variable name should describe its use
 Each data type has a recommended prefix, in
lower case, that begins the variable name
 The 1st letter of each subsequent word in the
variable name should be capitalized
 intHoursWorked - an integer variable

 strLastName - a string (or text) variable

Slide 3- 28
Declaring Variables with IntelliSense
 As you enter your program, VB often aids you by
offering a list of choices that could be used at that
point
 After typing "As" in a variable declaration, VB will
offer an alphabetical list of all possible data types
 Type the first few letters of the data type name

 Intellisense box will highlight the matching type

 Press the Tab key to select highlighted choice

 Or just complete typing the entire data type name

Slide 3- 29
Default Values and Initialization
 When a variable is first created in memory, it is
assigned a default value
 numeric types are given a value of zero

 Boolean types are given a value of False

 strings are given a value of Nothing

 dates default to 12:00:00 AM January 1,1

 Good practice to initialize string variables


 Dim strName as String = String.Empty
 String with value Nothing causes error if used

Slide 3- 30
Initialization of Variables
 Can provide a starting or initialization value for
any type of variable in a Dim statement
 Usually want to set an initial value unless
assigning a value prior to using the variable
 Just append = value to the Dim statement where
value is the literal to be assigned to the variable
Dim intMonthsPerYear As Integer = 12

Slide 3- 31
Performing Calculations

Visual Basic Has Powerful Arithmetic Operators That


Perform Calculations With Numeric Variables and
Literals
Common Arithmetic Operators
 Visual Basic provides operators for the common
arithmetic operations:
+ Addition
- Subtraction
* Multiplication
/ Division
^ Exponentiation
Mod Modulus

Slide 3- 33
Common Arithmetic Operators
 Addition
decTotal = decPrice + decTax
 Subtraction
decNetPrice = decPrice – decDiscount
 Multiplication
dblArea = dblLength * dblWidth
 Division
sngAverage = sngTotal / intItems
 Exponentiation
dblCube = dblSide ^ 3
Slide 3- 34
Special Integer Division Operator
 The backslash (\) is used as an integer division
operator
 Divides one integer by another
 The result is always an integer, created by
discarding any remainder from the division
 If calculating the number of hours in a given
number of minutes
intHours = intMinutes \ 60
 With intMinutes equal to 190, this calculation
will result in the value 3 assigned to intHours

Slide 3- 35
Modulus (MOD) Operator
 This operator can be used in place of the
backslash operator to give the remainder of a
division operation
intRemainder = 17 MOD 3 ‘result is 2
dblRemainder = 17.5 MOD 3 ‘result is 2.5
 Use of the \ or MOD
operator to perform integer
division by zero causes a
DivideByZeroException
runtime error
Slide 3- 36
Retrieving the Current Date/Time
 A series of keywords yields the current date,
current time, or both

Description Keyword Example


Date & Time Now datCurrent=Now
Time only TimeOfDay
datCurrTime=TimeOfDay
Date only Today datCurrDate=Today

 Variables datCurrent, datCurrTime, and


datCurrDate must be declared as Date data types
Slide 3- 37
Scope and Local Variables
 Scope refers to the part of the program where:
 A variable is visible and

 May be accessed by program code

 Variables declared within a procedure are called


local variables and observe these characteristics
 Scope begins where variable is declared

 Extends to end of procedure where declared

 Variable is not visible outside the procedure

 A variable cannot be declared twice in the same


procedure

Slide 3- 38
Class-Level and Global Scope
 A variable declared inside a class but outside any
procedure is a class-level variable
 Scope is throughout all procedures of the class

 A variable declared outside any class or


procedure is a global variable
 Scope is throughout all forms, classes, and

procedures of the project


 Class-level and global scope will be discussed
further in future chapters
 Values in a variable are destroyed when it goes
out of scope
Slide 3- 39
Combined Assignment Operators
 Often need to change the value in a variable and
assign the result back to that variable
 For example: var = var – 5
 Subtracts 5 from the value stored in var

 Other examples:
 x = x + 4 Adds 4 to x
 x = x – 3 Subtracts 3 from x
 x = x * 10 Multiplies x by 10
 VB provides for this common need with combined
assignment operators

Slide 3- 40
Combined Assignment Operators
These special assignment operators provide an easy means
to perform these common operations:

Operator Usage Equivalent to Effect

+= x += 2 x = x + 2 Add to
-= x -= 5 x = x – 5 Subtract from
*= x *= 10 x = x * 10 Multiply by
/= x /= y x = x / y Divide by
\= x \= y x = x \ y Int Divide by
&= name &= last name = name & last Concatenate

Slide 3- 41
Arithmetic Operator Precedence
 Operator precedence tells us the order in which
operations are performed
 From highest to lowest precedence:
 Exponentiation (^)

 Multiplicative (* and /)

 Integer Division (\)

 Modulus (MOD)

 Additive (+ and -)

 Where precedence is the same, operations occur


from left to right

Slide 3- 42
Operator Precedence Examples
The result is very different when the divide by 2 operation
is moved from the end of the calculation to the middle.

6 * 2^3 + 4 / 2 6 / 2 * 2^3 + 4

6* 8 +4/2 6/2 * 8 +4

48 +4/2 3 *8 +4
48 + 2
24 +4
50
28
Slide 3- 43
Grouping with Parentheses
 Parentheses () can be used to force selected parts of an
expression to be evaluated before others
 Assume we’re computing the average of 3 numbers

dblAvg = int1 + int2 + int3 / 3 ‘incorrect

int3 / 3 is evaluated first

That result is added to int1 and int2
 Use parentheses to control order of operations

dblAvg = (int1 + int2 + int3) / 3 ‘correct

int1 + int2 + int3 is evaulated first

That result is divided by 3
 When in doubt, use parentheses!
Slide 3- 44
Named Constants
 Can declare a variable whose value is set at
declaration and cannot be changed later:
Const sngSALES_TAX_RATE As Single = 1.06
 Looks like a normal declaration except:
 Const used instead of Dim

 An initialization value is required

 By convention, entire name capitalized with

underscore characters to separate words


 The objective of our code is now clearer
Const sngSALES_TAX_RATE As Single = 1.06
decTotal *= sngSALES_TAX_RATE

Slide 3- 45

You might also like