1 / 62

CSCI 3131.01 Chapter 3 Variables and Calculations Instructor: Bindra Shrestha

CSCI 3131.01 Chapter 3 Variables and Calculations Instructor: Bindra Shrestha University of Houston – Clear Lake. Acknowledgement Dr. Xinhua Chen And Starting Out with Visual Basic 2010 by Tony Gaddis and Kip Irvine. Topics Gathering Text Input Variables and Data Types

zagiri
Download Presentation

CSCI 3131.01 Chapter 3 Variables and Calculations Instructor: Bindra Shrestha

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSCI 3131.01 Chapter 3 Variables and Calculations Instructor: Bindra Shrestha University of Houston – Clear Lake

  2. Acknowledgement Dr. Xinhua Chen And Starting Out with Visual Basic 2010 by Tony Gaddis and Kip Irvine

  3. Topics • Gathering Text Input • Variables and Data Types • Performing Calculations • Mixing Different Data Types • Formatting Numbers and Dates • Exception Handling • The Load Event Procedure • Debugging – Locating Logic Errors

  4. Use TextBox Control to Get User Input txtUserName lblGreeting btnClose btnShowGreeting Use the Text property of the TextBox to retrieve user input. Syntax: nameOfTextBox.Text Use the Clear method to clear TextBox nameOfTextBox.Clear()

  5. The Use of TextBox • Use the Text property of the TextBox to retrieve user input. • Syntax: nameOfTextBox.Text • Use the Clear method to clear TextBox • Syntax: nameOfTextBox.Clear() • Display the contents of a TextBox with a Label • Syntax: nameOfLabel.Text = nameOfTextBox.Text • Display a string with a TextBox • Syntax: nameOfTextBox.Text = StringValue

  6. String Concatenation Use the concatenation operator (&) to concatenate strings. Examples: lblGreeting.Text = "Hello " & txtUserName.Text lblGreeting.Text = lblGreeting.Text & ". " & _ "How are you? "

  7. The Focus Method The controls that are capable of receiving some sort of input, such as TextBox and Button, may have focus. Syntax of Focus: nameOfControl.Focus() Example: txtFirstName.Focus

  8. Tab Order The focus moves from one control to another when the user presses the Tab key. The order in which controls receive focus depends on the value of the TabIndex property and TabStop property. Only if the TabStop property is True can the control receive focus. The TabIndex can be set using the property window and the View->Tab Order menu item.

  9. Assigning Keyboard Access Keys to Buttons Windows applications almost always provide quick access to buttons using Alt-<key> combination. For example, the Exit button blow can be access using Alt-x To enable keyboard access to the Exit button, set the Text property of the button as E&xit

  10. How to Display “&” on a Button or a Label? Use double ampersand (&&) to display one “&” on a Button or a Label. Example: Set the Text property of a button as Beans && Cream makes the button display as Beans & Cream

  11. Accept Buttons and Cancel Buttons An accept button is clicked when the user presses the Enter key. A cancel button is clicked when the user presses the Esc key. In the form’s property window, you may set the accept button and the cancel button.

  12. Variables and Data Types • Variables are computer memory locations the application can access while running. • An variable can be used do • Copy and store values entered by the user • Perform arithmetic on numeric values • Test values to determine that they meet some criterion • Temporarily hold and manipulate the value of a control property • Remember information for later use in a program • Every variable has a name, data type, scope, and lifetime.

  13. Variable Names • Visual Basic program uses identifiers to name variables, subprograms, classes and modules. • Rules of creating Visual Basic identifiers: • The first character must be a letter or an underscore; • Other characters, if any, must be the combination of a letter, an underscore, or a digit. • Maximum length of an identifier is 16383; however, the recommended maximum length is 32. • A Visual Basic reserved word cannot be used as an identifier.

  14. Naming Conventions • Hungarian notation • Use the first three or more characters to represent the type and the remaining characters to represent the purpose of the identifier • Example: • intMax • New notation that does not include the data type prefix, but include the purpose of the identifier only. If the identifier is formed using multiple words, make the first word lower case and make the first letter of other word(s) capitalized. This is called camel case. • Example: • firstName

  15. Valid Identifier _sum strProduct getSize Item_222 MAX_HOURS Invalid Identifier 13Users get Size box-22 IsEmpty? Integer

  16. Declaring a Variable Syntax [Dim | Private | Static] variablename As datatype [ =initialvalue] Examples Dim dblCarPayment As Double Dim decItemPrice As Decimal Dim blnIsDataOk As Boolean = True Dim strStudentName As String Dim intAge As Integer Dim strName As String = String.Empty

  17. Integer Data Types • For values that will always be a whole number • Usually name a variable starting with a 3 or 4 letter prefix indicating the variable’s type

  18. Floating-Point Data Types • For values that may have fractional parts • Single used most frequently • Double sometimes used in scientific calculations • Decimal often used in financial calculations

  19. Other Common Data Types • Boolean – variable naming prefix is bln • Holds 2 possible values, True or False • Char – variable naming prefix is chr • Holds a single character • Allows for characters from other languages • String – variable naming prefix is str • Holds a sequence of up to 2 billion characters • Date – variable naming prefix is dat • Can hold date and/or time information

  20. Integer Literals A sequence of digit from 0 to 9 with optional sign makes an integer literal. Comma should not be included. Use of type identifier, I, L and S: I: Integer literal (This is the default for integer literals) L: Long integer literal S: Short integer literal Examples: 1000L 1234S

  21. Floating-Point Literals Floating-point literals can be written in either fixed-point or scientific notation. Examples: Fixed-point: 342.32 Scientific notation: 4.73454E+4 This is Visual Basic’s notation for 4.73454  10-4. The letters F, R, D are used to indicate Single, Double and Decimal literals. If no letter is appended to a floating-point literal, it is treated as Double.

  22. Char Data Type Variables of Char holds one Unicode character, which is a two-byte character. Use quotation marks and c to denote a Char literal. Dim chrLetter As Char chrLetter = " A " c String Data Type A variable of type String can refer to zero to about 2 billion characters. Use quotation marks to create a string literal. Dim strName As String strName = " Jose Gonzalez "

  23. Date Data Type A variable of type Date can hold date and time information. A date literal is defined using a pair of # signs. Examples: Dim dtmBirth As Date dtmBirth = #5/1/2008# Dim dtmStartTime As Date dtmStartTime = #9/25/2008 7:00 PM#

  24. The Object Data Type If a variable is declared without data type, the Object data type is assumed by the Visual Basic compiler. The prefix for a variable of Object is obj, such objSender. The Object type is the most flexible type, because a variable of Object type can store different type of data at the runtime of the program. For example, the same variable of Object type may store number 20 first then refer to string "John" next. The flexibility of the Object type comes with inefficiency and more memory consumption.

  25. Table of Literal Type Characters

  26. Assigning Data to an Existing Variable Syntax variablename = value Examples Dim intQtyOrdered As Integer intQtyOrdered = 500 Dim strFirstName As String strFirstName = "Mary" Dim strZipCode As String strZipCode = zipTextBox.Text Dim decTaxRate As Decimal decTaxRate = .05D

  27. Performing Calculations Two types of operators in Visual Basic: unary and binary. A unary operator requires only one operand, such as -5 -intCount +4 A binary operator requires two operands, such as 5 + 10 intA + intB

  28. Writing Arithmetic Expressions Most commonly used arithmetic operators with their precedence. Parentheses are commonly used to override the order of precedence. Parentheses have the highest precedence.

  29. Operator Precedence Examples The result is very different when the divide by 2 operation is moved from the end of the calculation to the middle. 6 * 2^3 + 4 / 2 6 * 8 + 4 / 2 48 + 4 / 2 48 + 2 50 6 / 2 * 2^3 + 4 6 / 2 * 8 + 4 3 * 8 + 4 24 + 4 28

  30. Integer Division The operator “\” performs integer division. The decimal part of the quotient is discarded. Example: intHours = intMinutes \ 60 If intMinutes holds 100, intHours will hold 1 after the calculation.

  31. Modulus The modulus operator (MOD) performs integer division and returns only the reminder. Example: intRemainder = 17 MOD 3 intRemainder will hold 2 after the calculation.

  32. Exponentiation To calculate a variable x taken to the power of y, use this expression: x ^ y Example: dblResult = 5.0 ^ 2.0 (mathematically, 52)

  33. Getting the Current Date and Time There are a few built-in functions available to get system date and time. DescriptionKeywordExample Date & Time Now datCurrent=Now Time only TimeOfDay datCurrTime=TimeOfDay Date only Today datCurrDate=Today • Variables datCurrent, datCurrTime, and datCurrDate must be declared as Date data types

  34. Variable Scope A variable’s scope refers to the part of a program where the variable is accessible by programming statements. 1. Local Scope: A variable declared in a procedure has the local scope. This variable can only be accessed in the procedure where it is declared. 2. Class Scope: A variable declared inside a class but outside of any procedures has the class scope. This class-level variable can be accessed in any procedures of the class.

  35. Variable Scope (Cont’d) 3. Global Scope: A variable declared outside of any class or procedure has the global scope. This variable can be accessed in any procedures.

  36. Combined Assignment Operators • Often need to change the value in a variable and assign the result back to that variable • For example: var = var – 5 • Subtracts 5 from the value stored in var • Other examples: • x = x + 4 Adds 4 to x • x = x – 3 Subtracts 3 from x • x = x * 10 Multiplies x by 10 • VB provides for this common need with combined assignment operators

  37. Combined Assignment Operators These special assignment operators provide an easy means to perform these common operations: Operator Usage Equivalent to Effect += x += 2 x = x + 2 Add to -= x -= 5 x = x – 5 Subtract from *= x *= 10 x = x * 10 Multiply by /= x /= y x = x / y Divide by \= x \= y x = x \ y Int Divide by &= name &= last name = name & lastConcatenate

  38. Mixing Different Data Types • Implicit Type Conversion • Ideally, the variables of the same type should be used in a statement, e.g, • intSum = intA + intB 'All are integers • However, sometimes we may find it more convenient to use variables of different types in a statement, e.g., • dblSum = dblA + intB 'Only intB is integer • Visual Basic attempts to convert intB to Double before the summation. This is called implicit conversion.

  39. Mixing Different Data Types (Cont’d) • Widening Conversions • With widening conversions, a type that takes less memory is converted into a type that takes more memory. No loss of precision occurs with widening conversions. Examples: • Dim dblVar As Double = 1234 • Narrowing Conversions • With narrowing conversions, a type that takes more memory is converted into a type that takes less memory. Loss of precision could occur with narrowing conversions. Examples: • Dim dblOne As Double = 1.2342376 • Dim sngTwo As Single = dblOne 'sngTwo = 1.234238

  40. Converting Strings to Numbers Visual Basic will try to convert string values to numbers in some cases. Examples: Dim sngTemperature As Single sngTemperature = "12.13" 'Convert String into Single Dim intCount As Integer intCount = txtCount.Text 'Convert String into Integer

  41. Option Strict Implicit conversion is controlled by the setting of Option Strict. If Option Strict On/Off is specified in the beginning of a file, the setting affects the file. If the option is specified in the Project property screen, the setting affects the project. Option Strict On: Disable implicit narrowing conversion Option Strict Off: Enable implicit narrowing conversion When Option Strict On is in effect, the allowed implicit conversions are from left to right:

  42. Type Conversion Errors With Option Strict On, the statement below generates a compilation error: Dim intCount As Integer = "123" With Option Strict Off, the statement below generates a runtime error: Dim intCount As Integer = "abc123"

  43. Named Constants A named constant is a symbol for a literal. The value of the named constant cannot be changed while the application is running. Syntax Constconstantname [As datatype] = expression Examples: Const decPI As Decimal = 3.141593D Const intMAXHOURS As Integer = 40 Private Const strCOTITLE As String = "ABC Company"

  44. Explicit Type Conversion When Option Explicit On is in effect, we must use some functions to convert some conversions explicitly. A function is a named, self-contained body of code, which provide the output by manipulating the input. Input(s) Function Output

  45. Explicit Type Conversions • The following narrowing conversions require an explicit type conversion • Double to Single • Single to Integer • Long to Integer • Boolean, Date, Object, String, and numeric types represent different sorts of values and require conversion functions as well

  46. Full List of Conversion Functions • There are conversion functions for each data type • CBool ( expr ) • CByte ( expr ) • CChar ( expr ) • CDate ( expr ) • CDbl ( expr ) • CDec ( expr ) • CInt ( expr ) • CLng ( expr ) • CObj ( expr ) • CShort ( expr ) • CSng ( expr ) • CStr ( expr )

  47. Explicit Type Conversion Examples • Rounding can be done with the CInt function • intCount = CInt(12.4) 'intCount value is 12 • intCount = CInt(12.5) 'intCount value is 13 • CStr converts an integer value to a string Dim strText as String = CStr(26) • CDec converts a string to a decimal value Dim decPay as Decimal = CDec(“$1,500”) • CDate converts a string to a date Dim datHired as Date = CDate(“05/10/2005”)

  48. Invalid Conversions • Conversion functions can fail • Dim dblSalary as Double = CDbl("xyz") • Dim datHired as Date = CDate("05/35/2005") • String “xyz” can’t be converted to a number • There’s no day 35 in the month of May • These failed conversionscause a runtime error called an invalid cast exception

  49. The Val Function • The Val function is a more forgiving means of performing string to numeric conversions • Uses the form Val(string) asshown here • If the initial characters form a numeric value, the Val function will return that • Otherwise, it will return a value of zero

  50. The Val Function Val Function Value Returned • Val("34.90") 34.9 • Val("86abc") 86 • Val("$24.95") 0 • Val("3,789") 3 • Val("") 0 • Val("x29") 0 • Val("47%") 47 • Val("Geraldine") 0

More Related