380 likes | 513 Views
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?. Textbox2. Textbox1. YES. NO.
E N D
Chapter 3Variables (變數), 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? Textbox2 Textbox1 YES NO • How can you swap (互換) the values in these two text boxes? Textbox2 Textbox1 NO YES
Suggested Solution • How can you assign values to the following two text boxes? Textbox2 Textbox1 YES NO • Textbox1.text = “YES” • Textbox2.text = “NO”
Suggested Solution • How can you swap the values in these two text boxes? Textbox2 Textbox1 2 YES NO 1 3 YES strTemp • Dim strTemp = Textbox1.text • Textbox1.text = Textbox2.text • Textbox2.text = strTemp
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%
Declaration • Variables and Constants must be declared before being used
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 (有意思)
Your work – Valid? • omitted 9. conMaximum • int#Sold 10. MinimumRate • int Number Sold 11. decMaxCheck • int.Number.Sold 12. strCompanyName • sng$Amount 13. room###123 • sub 14. Price$112 • strSub • text
Declaration Statements • DIM used to declare Variables • CONST used to declare Constants • Declaration • DIM VariableName As DataType = Value • CONST ConstantName As DataType = Value
Boolean (True, False) Char (“A”, “B” ) Date (“11/9/2004”) String (“Hello”) Decimal (123.45) Integer (1, 23, 45) Data Types (資料類別)
Boolean – bln Char – chr Date – dat String – str Decimal – dec Integer – int Data Types – Prefixes (字頭)
Your work – Declaration? Dim strName As String = Dim decPayRate As Decimal = Dim datHireDate As Date = Dim blnInsured As Boolean = Dim chrLetter As Char = Const decRATE As Decimal =
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
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
Conversion Functions • Function Convert To • CInt Integer • CDec Decimal • CStr String
Conversion Examples intQuantity = CInt(txtQuantity.Text) decPrice = CDec(txtPrice.Text) intWholeNumber = CInt(decFractionalValue) decDollars = CDec(intDollars) strValue = CStr(decValue) Function Name Argument (參數)
Mathematical Operators • Operator Operation • + Addition • – Subtraction • * Multiplication (乘) • / Division (除) • \ Integer Division • Mod Modulus (餘數) • ^ Exponentiation (次方)
Order of Operations • from left to right in the following orders 1. Parentheses - () 2. Exponentiation - ^ 3. Multiplication & Division - */ 4. Integer Division - \ 5. Modulus - Mod 6. Addition & Subtraction - +-
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
Calculation Examples • 10 + 2 = • 10 – 2 = • 10 * 2 = • 10 / 2 = • 10 \ 4 = • 10 mod 3 = • 10 ^ 2 =
Your work – Calculation? • 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
Option Explicit (明確) • ON by default • If turned off • Variables can be used without first being declared • To turn off • Option Explicit Off
Option Strict (嚴格) • OFF by default • If turned on • VB becomes strongly typed language • Will not allow implicit conversions • To turn on • Option Strict On
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
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
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
Try/Catch Blocks • Handle exceptions in aTry/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
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
Try Block - Example 1Catches All Exceptions Try intQuantity=CInt(txtQuantity.Text) lblQuantity.Text=CStr(intQuantity) Catch lblMessage.Text="Error in input data." End Try
Try Block - Example 2Catches 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
Try Block - Example 3Catches 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
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 ::: :::
MessageBox • Use to display messages in a special type of window • Arguments of Show method • Message to display (內容) • Title Bar Caption (標題) • Button(s) (按鈕) • Icon (圖案)
MessageBox Syntax • Example: MessageBox.Show(“Good Morning”, “Greeting”, _ OK, Exclamation) MessageBox.Show (TextMessage, TitlebarText, _ MessageBoxButtons, MesssageBoxIcon)
MessageBoxButtons Constants • OK • OKCancel • RetryCancel • YesNo • YesNoCancel • AbortRetryIgnore
Asterisk Error Exclamation Hand Information None Question Stop Warning MessageBoxIcon Constants
Your work - MessageBox • Please write the following messages on the screen: