Chapter 3 Variables Constants and Calculations Programming In
Chapter 3 Variables (變數), Constants (常數) and Calculations (計算) Programming In Visual Basic. NET Prepared by Johnny Tsui, CIM@IVE
Your work - Reminder • How can you assign (給予) values to the following two text boxes? Textbox 1 Textbox 2 YES NO • How can you swap (互換) the values in these two text boxes? Textbox 1 Textbox 2 NO YES 2
Suggested Solution • How can you assign values to the following two text boxes? Textbox 1 Textbox 2 YES NO • Textbox 1. text = “YES” • Textbox 2. text = “NO” 3
Suggested Solution • How can you swap the values in these two text boxes? Textbox 1 2 YES Textbox 2 NO 1 str. Temp 3 YES • Dim str. Temp = Textbox 1. text • Textbox 1. text = Textbox 2. text • Textbox 2. text = str. Temp 4
Variables & Constants • A temporary (暫時) location for storage (儲存) and calculation (計算) • Variable – data that can be changed (可改變) – Ex: study hours (溫習小時) 45 hr • Constant – data that cannot be changed (不能改變) – Ex: service charge (服務費) 10% 5
Declaration • Variables and Constants must be declared before being used 6
Naming Conventions (命名法則) • May consist of letters (文字), digits ( 數字) and underscores (底線) • Begin with a letter • Cannot contain any spaces (空位) or periods (點) • Cannot be reserved words (專用字) • Not case sensitive (不分大小寫) • Should be meaningful (有意思) 7
Your work – Valid? 1. 2. 3. 4. 5. 6. 7. 8. omitted int#Sold int Number Sold int. Number. Sold sng$Amount sub str. Sub text 9. con. Maximum 10. Minimum. Rate 11. dec. Max. Check 12. str. Company. Name 13. room###123 14. Price$112 8
Declaration Statements • DIM used to declare Variables • CONST used to declare Constants • Declaration – DIM Variable. Name As Data. Type = Value – CONST Constant. Name As Data. Type = Value 9
Data Types (資料類別) • • • Boolean (True, False) Char (“A”, “B” ) Date (“ 11/9/2004”) String (“Hello”) Decimal (123. 45) Integer (1, 23, 45) 10
Data Types – Prefixes (字頭) • • • Boolean – bln Char – chr Date – dat String – str Decimal – dec Integer – int 11
Your work – Declaration? Dim str. Name Dim dec. Pay. Rate Dim dat. Hire. Date Dim bln. Insured Dim chr. Letter Const dec. RATE As String = As Decimal = As Date = As Boolean = As Char = As Decimal = 12
Variables – Scope • Global – Available to all modules and procedures of Project – Initialized at start of Project • Local – Available only to the procedure it is declared in – Initialized every time the Procedure runs 13
Calculations • Do NOT use Strings in calculations • Ex: int. X = “ABC” + 3 • Values from Text property of Text Boxes – Are Strings, even if they contain numeric data – Must be converted to a Numeric Data Type 14
Conversion Functions Function CInt CDec CStr Convert To Integer Decimal String 15
Conversion Examples int. Quantity dec. Price int. Whole. Number dec. Dollars str. Value = = = CInt(txt. Quantity. Text) CDec(txt. Price. Text) CInt(dec. Fractional. Value) CDec(int. Dollars) CStr(dec. Value) Function Name Argument (參數) 16
Your work - Conversion String CInt CDec 123. 45 $100 1, 000. 00 -5 0. 01 1. 5 A 123 17
Mathematical Operators Operator + – * / Mod ^ Operation Addition Subtraction Multiplication (乘) Division (除) Integer Division Modulus (餘數) Exponentiation (次方) 18
Order of Operations • from left to right in the following orders 1. 2. 3. 4. 5. 6. Parentheses - () Exponentiation - ^ Multiplication & Division - */ Integer Division - Modulus - Mod Addition & Subtraction - +19
Mathematical Examples 3+4*2 = 11 Multiply then add (3+4)*2 = 14 Parentheses control: add then multiply 8/4*2 = 4 Same level, left to right: divide then multiply 20
Calculation Examples • 10 • 10 +2= – 2= *2= /2= 4= mod 3 = ^2= 21
Your work – Calculation? • 1. 2. 3. 4. 5. 6. 7. 8. Assume (假設) that int. X=2, int. Y=4, int. Z=3, what is the value of int. A = int. X + int. Y ^ 2 int. A = 8 / int. Y / int. X int. A = int. X * (int. X + 1) int. A = int. X * int. X + 1 int. A = int. Y ^ int. X + int. Z * 2 int. A = int. Y ^ (int. X + int. Z) * 2 int. A =(int. Y ^ int. X) + int. Z) * 2 int. A =((int. Y ^ int. X) + int. Z) * 2 22
Option Explicit (明確) • ON by default • If turned off – Variables can be used without first being declared • To turn off – Option Explicit Off 23
Option Strict (嚴格) • OFF by default • If turned on – VB becomes strongly typed language – Will not allow implicit conversions • To turn on – Option Strict On 24
Your work – Explicit? • What errors will you get if Option Explicit Off has been defined? – int. A = 3 – Dim int. B As Integer – Int. B = int. A +5 • What errors will you get if Option Explicit On has been defined? – int. A = 3 – Dim int. B As Integer – Int. B = int. A +5 25
Your work – Strict? • What errors will you get if Option Strict Off has been defined? – Dim int. A as Integer, int. B As Decimal – int. A = 2. 5 – Int. B = int. A +5 • What errors will you get if Option Strict On has been defined? – Dim int. A as Integer, int. B As Decimal – int. A = 2. 5 – Int. B = int. A +5 26
Handling Exceptions (Errors) • Exceptions occur – User enters nonnumeric data in Text Box and code attempts to run a Numeric Conversion Function – User enters data that results in division by zero 27
Try/Catch Blocks • Handle exceptions in a Try/Catch Block – If an error occurs, control is transferred to the Catch Block – Include a Finally statement to indicate code that should execute last whether or not an exception occurred 28
Try Block - General Form Try statements that may cause error Catch [Variable. Name as Exception. Type] statements for action when an exception occurs Finally statements that always execute before exit of Try block End Try 29
Try Block - Example 1 Catches All Exceptions Try int. Quantity=CInt(txt. Quantity. Text) lbl. Quantity. Text=CStr(int. Quantity) Catch lbl. Message. Text="Error in input data. " End Try 30
Try Block - Example 2 Catches Specific Exception Try int. Quantity=CInt(txt. Quantity. Text) lbl. Quantity. Text=CStr(int. Quantity) Catch My. Err as Invalid. Cast. Exception lbl. Message. Text="Error in input data. " End Try Conversion exception, usually caused by nonnumeric or blank data 31
Try Block - Example 3 Catches Multiple Specific Exceptions Try statements that may cause errors Catch My. Err as Invalid. Cast. Exception (轉型錯誤) error messages and statements for nonnumeric data Catch My. Err as Arithmetic. Exception (計算錯誤) error messages and statements for calculation problems Catch My. Err as Exception (其他錯誤) error messages and statements for any other exception End Try 32
Your work – Exception? • How can you handle exceptions for the following coding? : : : Dim str. A as String Dim int. B as Integer : : : str. A = “$100. 0” int. B = CInt(str. A) lbl. Message. text = int. B : : : 33
Message. Box • Use to display messages in a special type of window • Arguments of Show method 1. 2. 3. 4. Message to display (內容) Title Bar Caption (標題) Button(s) (按鈕) Icon (圖案) 34
Message. Box Syntax Message. Box. Show (Text. Message, Titlebar. Text, _ Message. Box. Buttons, Messsage. Box. Icon) • Example: Message. Box. Show(“Good Morning”, “Greeting”, _ OK, Exclamation) 35
Message. Box. Buttons Constants • OKCancel • Retry. Cancel • Yes. No. Cancel • Abort. Retry. Ignore 36
Message. Box. Icon Constants • • • Asterisk Error Exclamation Hand Information • • None Question Stop Warning 37
Your work - Message. Box • Please write the following messages on the screen: Message Title Button Icon Nice to meet you! Greeting OK Exclamation You are wrong! Attention OK Warning Please press ENTER! Information OKCancel Information 38
- Slides: 38