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? Textbox1 Textbox2 YES NO • How can you swap (互換) the values in these two text boxes? Textbox1 Textbox2 NO YES 2 Suggested Solution • How can you assign values to the following two text boxes? Textbox1 Textbox2 YES NO • Textbox1.text = “YES” • Textbox2.text = “NO” 3 Suggested Solution • How can you swap the values in these two text boxes? Textbox1 2 YES Textbox2 NO 1 strTemp 3 YES • Dim strTemp = Textbox1.text • Textbox1.text = Textbox2.text • Textbox2.text = strTemp 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 strSub text 9. conMaximum 10. MinimumRate 11. decMaxCheck 12. strCompanyName 13. room###123 14. Price$112 8 Declaration Statements • DIM used to declare Variables • CONST used to declare Constants • Declaration – DIM VariableName As DataType = Value – CONST ConstantName As DataType = 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 strName Dim decPayRate Dim datHireDate Dim blnInsured Dim chrLetter Const decRATE 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: intX = “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 intQuantity decPrice intWholeNumber decDollars strValue = = = = = CInt(txtQuantity.Text) CDec(txtPrice.Text) CInt(decFractionalValue) CDec(intDollars) CStr(decValue) Function Name Argument (參數) 16 Your work - Conversion String CInt CDec 123.45 $100 1,000.00 -5 0.01 1.5 A123 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 • 10 • 10 • 10 • 10 • 10 +2= –2= *2= /2= \4= mod 3 = ^2= 21 Your work – Calculation? • 1. 2. 3. 4. 5. 6. 7. 8. Assume (假設) that intX=2, intY=4, intZ=3, what is the value of intA intA = intX + intY ^ 2 intA = 8 / intY / intX intA = intX * (intX + 1) intA = intX * intX + 1 intA = intY ^ intX + intZ * 2 intA = intY ^ (intX + intZ) * 2 intA =(intY ^ intX) + intZ) * 2 intA =((intY ^ intX) + intZ) * 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? – intA = 3 – Dim intB As Integer – IntB = intA +5 • What errors will you get if Option Explicit On has been defined? – intA = 3 – Dim intB As Integer – IntB = intA +5 25 Your work – Strict? • What errors will you get if Option Strict Off has been defined? – Dim intA as Integer, intB As Decimal – intA = 2.5 – IntB = intA +5 • What errors will you get if Option Strict On has been defined? – Dim intA as Integer, intB As Decimal – intA = 2.5 – IntB = intA +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 [VariableName as ExceptionType] 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 intQuantity=CInt(txtQuantity.Text) lblQuantity.Text=CStr(intQuantity) Catch lblMessage.Text="Error in input data." End Try 30 Try Block - Example 2 Catches Specific Exception Try intQuantity=CInt(txtQuantity.Text) lblQuantity.Text=CStr(intQuantity) Catch MyErr as InvalidCastException lblMessage.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 MyErr as InvalidCastException (轉型錯誤) error messages and statements for nonnumeric data Catch MyErr as ArithmeticException (計算錯誤) error messages and statements for calculation problems Catch MyErr 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 strA as String Dim intB as Integer ::: strA = “$100.0” intB = CInt(strA) lblMessage.text = intB ::: ::: 33 MessageBox • 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 MessageBox Syntax MessageBox.Show (TextMessage, TitlebarText, _ MessageBoxButtons, MesssageBoxIcon) • Example: MessageBox.Show(“Good Morning”, “Greeting”, _ OK, Exclamation) 35 MessageBoxButtons Constants • OK • OKCancel • RetryCancel • YesNo • YesNoCancel • AbortRetryIgnore 36 MessageBoxIcon Constants • • • • • Asterisk Error Exclamation Hand Information • • • • None Question Stop Warning 37 Your work - MessageBox • 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