If you can't read please download the document
Upload
hope
View
81
Download
4
Embed Size (px)
DESCRIPTION
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. - PowerPoint PPT Presentation
Citation preview
Chapter 3Variables (), Constants () and Calculations ()Programming InVisual Basic.NET
Prepared by Johnny Tsui, CIM@IVE
Your work - ReminderHow can you assign () values to the following two text boxes?YESNOTextbox1Textbox2How can you swap () the values in these two text boxes?NOYESTextbox1Textbox2
Suggested SolutionHow can you assign values to the following two text boxes?YESNOTextbox1Textbox2Textbox1.text = YESTextbox2.text = NO
Suggested SolutionDim strTemp = Textbox1.textTextbox1.text = Textbox2.textTextbox2.text = strTempHow can you swap the values in these two text boxes?YESNOTextbox1Textbox2YESstrTemp132
Variables & ConstantsA temporary () location for storage () and calculation ()Variabledata that can be changed ()Ex: study hours () 45 hrConstantdata that cannot be changed ()Ex: service charge () 10%
DeclarationVariables and Constants must be declared before being used
Naming Conventions ()May consist of letters (), digits () and underscores ()Begin with a letterCannot contain any spaces () or periods ()Cannot be reserved words ()Not case sensitive ()Should be meaningful ()
Your work Valid?omitted 9. conMaximumint#Sold 10. MinimumRateint Number Sold 11. decMaxCheckint.Number.Sold 12. strCompanyNamesng$Amount 13. room###123sub 14. Price$112strSubtext
Declaration StatementsDIM used to declare VariablesCONST used to declare ConstantsDeclarationDIM VariableName As DataType = ValueCONST ConstantName As DataType = Value
Data Types ()Boolean (True, False)Char (A, B ) Date (11/9/2004)String (Hello)Decimal (123.45)Integer (1, 23, 45)
Data Types Prefixes ()Boolean blnChar chrDate datString strDecimal decInteger int
Your work Declaration?Dim strNameAs String =Dim decPayRate As Decimal = Dim datHireDate As Date = Dim blnInsured As Boolean = Dim chrLetterAs Char =Const decRATE As Decimal =
Variables ScopeGlobal Available to all modules and procedures of ProjectInitialized at start of ProjectLocalAvailable only to the procedure it is declared inInitialized every time the Procedure runs
CalculationsDo NOT use Strings in calculationsEx: intX = ABC + 3Values from Text property of Text BoxesAre Strings, even if they contain numeric dataMust be converted to a Numeric Data Type
Conversion FunctionsFunctionConvert ToCIntIntegerCDecDecimalCStrString
Conversion ExamplesFunction NameArgument ()intQuantity=CInt(txtQuantity.Text)decPrice=CDec(txtPrice.Text)intWholeNumber=CInt(decFractionalValue)decDollars=CDec(intDollars)strValue=CStr(decValue)
Your work - Conversion
Mathematical OperatorsOperatorOperation+Addition Subtraction*Multiplication ()/Division ()\Integer DivisionModModulus ()^Exponentiation ()
Order of Operationsfrom left to right in the following orders1. Parentheses - ()2. Exponentiation - ^3. Multiplication & Division - */4. Integer Division - \5. Modulus - Mod6. Addition & Subtraction - +-
Mathematical Examples3+4*2 = 11Multiply then add(3+4)*2 = 14Parentheses control: add then multiply8/4*2 = 4Same level, left to right: divide then multiply
Calculation Examples10 + 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 intAintA = intX + intY ^ 2intA = 8 / intY / intXintA = intX * (intX + 1)intA = intX * intX + 1intA = intY ^ intX + intZ * 2intA = intY ^ (intX + intZ) * 2intA =(intY ^ intX) + intZ) * 2intA =((intY ^ intX) + intZ) * 2
Option Explicit ()ON by defaultIf turned offVariables can be used without first being declaredTo turn offOption Explicit Off
Option Strict ()OFF by defaultIf turned onVB becomes strongly typed languageWill not allow implicit conversionsTo turn onOption Strict On
Your work Explicit?What errors will you get if Option Explicit Off has been defined?intA = 3Dim intB As IntegerIntB = intA +5What errors will you get if Option Explicit On has been defined?intA = 3Dim intB As IntegerIntB = intA +5
Your work Strict?What errors will you get if Option Strict Off has been defined?Dim intA as Integer, intB As DecimalintA = 2.5IntB = intA +5What errors will you get if Option Strict On has been defined?Dim intA as Integer, intB As DecimalintA = 2.5IntB = intA +5
Handling Exceptions (Errors)Exceptions occur User enters nonnumeric data in Text Box and code attempts to run a Numeric Conversion FunctionUser enters data that results in division by zero
Try/Catch BlocksHandle exceptions in a Try/Catch BlockIf an error occurs, control is transferred to the Catch BlockInclude a Finally statement to indicate code that should execute last whether or not an exception occurred
Try Block - General FormTrystatements that may cause errorCatch [VariableName as ExceptionType]statements for action when an exception occursFinallystatements that always execute before exit of Try blockEnd Try
Try Block - Example 1Catches All ExceptionsTryintQuantity=CInt(txtQuantity.Text)lblQuantity.Text=CStr(intQuantity)CatchlblMessage.Text="Error in input data."End Try
Try Block - Example 2Catches Specific ExceptionTryintQuantity=CInt(txtQuantity.Text)lblQuantity.Text=CStr(intQuantity)Catch MyErr as InvalidCastExceptionlblMessage.Text="Error in input data."End TryConversion exception, usually caused by nonnumeric or blank data
Try Block - Example 3Catches Multiple Specific ExceptionsTrystatements that may cause errorsCatch MyErr as InvalidCastException ()error messages and statements for nonnumeric data Catch MyErr as ArithmeticException ()error messages and statements for calculation problemsCatch MyErr as Exception ()error messages and statements for any other exceptionEnd Try
Your work Exception?How can you handle exceptions for the following coding?:::Dim strA as StringDim intB as Integer:::strA = $100.0intB = CInt(strA)lblMessage.text = intB::::::
MessageBoxUse to display messages in a special type of windowArguments of Show methodMessage to display ()Title Bar Caption ()Button(s) ()Icon ()
MessageBox SyntaxExample:MessageBox.Show(Good Morning, Greeting, _OK, Exclamation)MessageBox.Show (TextMessage, TitlebarText, _ MessageBoxButtons, MesssageBoxIcon)
MessageBoxButtons ConstantsOKOKCancelRetryCancelYesNoYesNoCancelAbortRetryIgnore
MessageBoxIcon ConstantsAsteriskErrorExclamationHandInformationNoneQuestionStopWarning
Your work - MessageBoxPlease write the following messages on the screen:
MessageTitleButtonIconNice to meet you!GreetingOKExclamationYou are wrong!AttentionOKWarningPlease press ENTER!InformationOKCancelInformation