Beruflich Dokumente
Kultur Dokumente
Chapter 3
Variables and Calculations
Outline
Outline
3.1 Gathering Text Input 3.2 Variables and Data Types 3.3 Performing Calculations 3.4 Mixing Different Data Types 3.5 Formatting Numbers and Dates 3.6 Class-Level Variables
Outline (cont.)
3.7 Exception Handling 3.8 Group Boxes 3.9 The Load Event 3.10 Focus on Program Design and Problem Solving: Building the Room Charge Calculator Application 3.11 More about Debugging: Locating Logic Errors
Topics
Topics
Gathering text input Data
Variables, constants
Tools/Options
Auto List Members
Calculations
Intrinsic functions and mathematical calculations Assignments and arithmetic
Copyright 2014 Pearson Education, Inc.
Topics (cont.)
Type conversion functions Formatting results
Numbers, currency, percentages, dates
Group boxes
Pay period, employee data
3.1
Examples
lblGreeting.Text = "Hi there!" lblName.Text = txtUserName.Text
Copyright 2014 Pearson Education, Inc.
TextBox Control
TextBox
Rectangular area on a form Receives focus Accepts input from keyboard Displays information to user
10
SelectAll( )
Highlights contents of Textbox
Focus( )
Positions cursor in Textbox
11
12
btnShowGreeting
13
String Concatenation
Concatenation
Combines strings into a longer string Uses & operator to join strings Example
lblGreeting.Text = "Hello " & txtUserName.Text
space separates literal from text
14
String Concatenation
Example
txtDayOfWeek txtMonth txtDayOftheMonth txtYear lblDateString btnExit btnClear btnShowDate
15
16
Focus() Method
Focus
Allows a control to receive user input Always belongs to a control on active form Only an input control may receive focus May be given to a control by calling Focus() Example
txtUserName.Focus()
17
Other control
Thin dotted line surrounding control
18
Tab Order
Navigation within Form
Tab key advances focus to next control Shift Tab key moves focus to previous control Sequence determined by TabIndex property of controls
19
20
Tab Order
Select Form
View/Tab Order
21
22
23
24
25
26
27
28
29
3.2
30
Variables
Variable
Refers to a storage location Holds information while program runs May be manipulated May be used to manipulate other information Remembers value for later use
31
32
Variables (cont.)
Each variable has a
Storage (or memory) location Name Data type Value
33
Naming Rules
Identifier in VB
Must begin with letter or underscore May contain letters, digits, and underscores Must NOT contain spaces or periods Must NOT be keywords (reserved words)
34
Naming Conventions
Identifier in VB
Should describe value stored Should use camel casing Is not case-sensitive Examples
firstName numberOfStudents
35
Other
Boolean, Char, String, Date, Object
36
VB Data Types
Data Type Boolean Byte Char Date Decimal Double Integer Long Description True/False Small whole number (0-255) Character Date and/or time Precise floating point number Large floating point number Whole number Large whole number
37
38
Floating-Point types
Single Double Decimal
Copyright 2014 Pearson Education, Inc.
39
Variable Declarations
To declare a variable
Dimension variable with name and data type Assign an initial value (optional) Good practice to initialize string variables
40
Examples
Dim Dim Dim Dim Dim salary As Decimal classSize As Integer = name As String = "John errorMessage As String firstName, lastName As
20 Doe" = String.Empty String
41
42
Decimal
45
Examples
Dim enrolled As Boolean = False enrolled = True txtName.Visible = True txtSalary.Visible = False
Copyright 2014 Pearson Education, Inc.
46
47
48
49
50
51
52
53
Named Constants
Constant
Mnemonic represents data value that does not change Improves readability of code Eases maintenance of code
54
55
56
57
58
Tools/Options
59
Tools/Options/Text Editor/Basic
60
Scope of a Variable
Scope
Part of program where variable is visible and may be accessed by programming statements May be
Global - known within a project Class - known within a class (file) Local - known within method in which declared
61
Global Variable
Global - known within a project
Scope throughout all forms, classes, and methods of project Variable declared outside any class or method
62
Class-Level Variable
Class - known within a class (file)
Scope throughout all methods of class Variable declared inside class but outside any method
63
Local Variable
Local - known within method in which declared
Scope begins where variable is declared Extends to end of method Variable is not visible outside the method
Note: A variable cannot be declared twice in same method
Copyright 2014 Pearson Education, Inc.
64
Local Variables
Local variable
Declared within a method Scope
Begins where variable is declared Extends to end of method where declared
65
3.3
Performing Calculations
66
68
69
70
Exceptions
DivideByZeroException runtime error
Caused by use of \ or MOD operator to perform integer division by zero
71
' 5% raise
72
Equivalent to
x x x x x = = = = = x x x x x + * / \ 2 5 10 y y
Effect
Add to Subtract from Multiply by Divide by Integer Divide name &= last name = name & last Concatenate
73
74
75
76
77
78
Exercise Processing
Add button processing
Controls
Text boxes
Date, start date, end date, name, hours, rate, raise%
79
3.4
80
Type Conversions
Type conversions
A value of one data type may be assigned to a variable of a different type Types
Implicit - attempts to convert to receiving variables data type Explicit - specifies how to convert to receiving variables data type
81
82
Option Strict
Option Strict
VB configuration setting On allows only widening conversions
An integer can be assigned to a decimal A decimal cannot be assigned to an integer A single can be assigned to a double A double cannot be assigned to a single
83
84
85
86
Invalid Conversions
Conversion functions can fail
Dim dblSalary As Double = CDbl("xyz")
87
88
Literals
Type Boolean Keywords Byte Char Date Decimal Double Integer Long Short Single String Description True and False Decimal digits between 0 and 255 Character surrounded by double quotes followed by lowercase C Date and/or time representation enclosed in # Digits with decimal point followed by D or @ Digits with decimal point followed by optional R Decimal digits followed by optional letter I Decimal digits followed by the letter L Decimal digits followed by the letter S Digits with decimal point followed by letter F or ! Characters surrounded by double quotes Example True 200 "A"c #1/1/14#
+32.0D
3.5R -3054I 40000L 12345S 26.4F "ABC123"
89
Exercise Processing 2
Add conversions to button processing
Controls
Text boxes
Date, start date, end date, name, hours, rate, raise%
90
Parse( ) Methods
Parse( ) method
Each data type has a Parse( ) method to convert a string to the data type No error detection Examples
Dim age As Integer age = Integer.Parse(txtAge.Text) Dim salary As Decimal salary = Decimal.Parse(txtSalary.Text)
Copyright 2014 Pearson Education, Inc.
91
Exercise Processing 3
Add Parse( ) method to button processing
Controls
Text boxes
Date, start date, end date, name, hours, rate, raise%
92
TryParse( ) Methods
TryParse( ) method
Each data type has a TryParse( ) method to convert a string to the data type Returns
True if conversion successful False if conversion unsuccessful
Examples
Integer.TryParse(txtAge.Text, age) Decimal.TryParse(txtSalary.Text, salary)
Copyright 2014 Pearson Education, Inc.
93
Exercise Processing 4
Add TryParse( ) method to button processing
Controls
Text boxes
Date, start date, end date, name, hours, rate, raise%
94
3.5
95
ToString( ) Method
Every VB data type has a ToString() method
Converts contents of a variable to a string Example
Dim number As Integer = 123 lblNumber.Text = number.ToString()
Converts integer 123 to string "123", then assigns string to Text property of lblNumber control
96
97
N or n
F or f E or e
Number format includes commas and displays 2 digits to the right of the decimal
Fixed point format 2 digits to the right of the decimal but no commas Exponential format displays values in scientific notation with a single digit to the left of the decimal point. The exponent is marked by the letter e, and the exponent has a leading + or - sign. Currency format includes dollar sign, commas, and 2 digits to the right of the decimal Percent format multiplies number by 100 and displays with a trailing space and percent sign
98
C or c P or p
99
100
1234567.8
($1,234,567.80)
101
D2
01
102
Exercise Formatting
Add formatting to button processing
Controls
Text boxes
Date, start date, end date, name, hours, rate, raise%
103
104
105
3.6
Class-Level Variables
106
Class-Level Variables
Class-level variable
Declared inside class but outside any method
Scope is throughout all methods of class
107
Class-Level Constants
Class-level constant
Named constant declared with Const keyword at class level Cannot be changed during runtime Eliminates many potential hazards associated with use of class-level variables More acceptable than class-level variables
108
Class-Level Declarations
Public Class Form1 ' Begin after class declaration ' Declare class-level constant Private Const cVALUE As Integer = 0 ' Declare class-level variable Private aValue As Integer ' End before method declarations
Private Sub Procedure() End Sub End Class
109
3.7
Exception Handling
110
Runtime Errors
Runtime error
Occurs for many reasons Results when
VB throws an exception and it is unhandled
Examples
DivideByZeroException InvalidCastException
111
Exception Handling
Exception handling
Allows a program to
Fail gracefully Recover if possible
112
Handling Exceptions
VB provides an exception handler
Syntax
Try try-block Catch [exception-type] catch-block End Try
where
try-block statements might throw an exception catch-block statements execute when exception is thrown
Copyright 2014 Pearson Education, Inc.
113
salary = Decimal.Parse(txtSalary.Text) MessageBox.Show("Your salary is " & salary.ToString("c")) Catch MessageBox.Show("Try again and enter a " & "number", "Entry Error") txtSalary.SelectAll() txtSalary.Focus() End Try
Copyright 2014 Pearson Education, Inc.
114
115
116
3.8
Group Boxes
117
Group Box
GroupBox groups controls
Physical
Controls surrounded by rectangular border and have a title (optional) Visual to user that controls in box are related
Logical
Controls within box have tab ordering within group Moving a GroupBox moves its controls with it Removing a GroupBox removes its controls
118
GroupBox
119
120
121
122
123
124
3.9
125
Form Events
Form events
Form_Load
Runs when form is initially loaded into memory
Form_Activated
Runs each time control is transferred to form
Form_Disposed
Runs when form is removed from memory
126
127
128
Controls
Text boxes
Date, start date, end date, name, hours, rate, raise%
129
3.10
Focus on Program Design and Problem Solving: Building the Room Charge Calculator Application
130
131
132
133
134
135
Completed Form
136
Changing Color
Color
Properties
ForeColor - text color
Custom, Web, System tabs
137
138
139
3.11
140
141
142
Program Problem
Scenario
Program runs but does not work correctly (logic errors) Running the program with various inputs has not isolated where the logic errors lie What can be done?
143
Debugging
VS .NET provides tools to debug your application
Set Breakpoints in source code View Immediate Window
Display data values or messages Change data values
144
Debugging (cont.)
Step through code
Step Into - single step through method Step Over - execute method without stepping through each line Step Out Of - return from method Run to Cursor - execute statements until statement on which cursor is located
145
Debugging (cont.)
Debugging toolbar
146
147
Debugging
Breakpoint
148
Exercise Debugging
Add breakpoints to code and debug/inspect
Controls
Text boxes
Date, start date, end date, name, hours, rate, raise%
149
150
Topics Covered
Topics covered
Gathering text input Data
Variables, constants
Tools/Options
Auto List Members
Calculations
Intrinsic functions and mathematical calculations Assignments and arithmetic
Copyright 2014 Pearson Education, Inc.
151
152