Visual Basic - Chapter 3

Transcription

Visual Basic - Chapter 3Mohammad Shokoohi* Adopted from An Introduction to Programming Using Visual Basic 2010, Schneider1

Chapter 3 – Variables, Input,and Output3.1 Numbers3.2 Strings3.3 Input and Output2

3.1 Numbers Arithmetic OperationsVariablesIncrementing the Value of a VariableBuilt-In Functions: Math.Sqrt Int Math.Round3

Numbers (continued) The Integer Data TypeMultiple DeclarationsTwo Integer-Valued OperatorsParenthesesThree Types of ErrorsThe Error List Window4

Arithmetic Operations Numbers are called numeric literals Five arithmetic operations in Visual Basic addition- subtraction* multiplication/ division exponentiation5

Numeric Expressions2 33 * (4 5)2 36

Displaying NumbersLet n be a number or a numeric expression.The statementlstBox.Items.Add(n)displays the value of n in the list box.7

Example 1: Form8

Example 1: Code and OutputPrivate Sub btnCompute Click (.)Handles Items.Add(2 * 3)lstResults.Items.Add((2 3) – 1)End SubOutputin listbox5679

Numeric VariableA numeric variable is a name to which anumber can be 10

Variables Declaration:Dim speed As Doublevariable namedata type Assignment:speed 5011

Initialization Numeric variables are automaticallyinitialized to 0:Dim varName As Double To specify a nonzero initial valueDim varName As Double 5012

Numeric ExpressionsNumeric variables can be used in numericexpressions.Dim balance As Double 1000lstBox.Items.Add(1.05 * balance)Output: 105013

Assignment StatementDim numVar1 As Double 5Dim numVar2 As Double 4numVar1 3 * numVar2lstBox.Items.Add(numVar1)Output: 1214

Incrementing To add 1 to the numeric variable varvar var 1 Or as a shortcutvar 1 Or as a generalizationvar numeric expression15

Built-in FunctionsFunctions return a valueMath.Sqrt(9) returns 3Int(9.7) returns 9Math.Round(2.7) returns 316

Integer Data Type Variables of type Double can be assignedboth whole numbers and numbers withdecimals. The statementDim varName As Integerdeclares a numeric variable that can only beassigned whole number values betweenabout -2 billion and 2 billion.17

Multiple DeclarationsDim a, b As DoubleTwo other types of multiple-declarationstatements areDim a As Double, b As IntegerDim c As Double 2, b As Integer 518

Two Integer-Valued Operators Integer division (denoted by \) is similar toordinary long division except that theremainder is discarded. The Mod operator returns only the integerremainder.23 \ 7 323 Mod 7 28\2 48 Mod 2 019

Parentheses Parentheses should be used liberally innumeric expressions. In the absence of parentheses, theoperations are carried out in the followingorder: , * and /, \, Mod, and -.20

Three Types of Errors Syntax error Runtime error Logic error21

Some Types of Syntax Errors MisspellingslstBox.Itms.Add(3) OmissionslstBox.Items.Add(2 ) Incorrect punctuationDim m; n As Integer22

A Type of Runtime ErrorOverflow errorDim numVar As Integer 1000000numVar numVar * numVar23

A Logical ErrorDim average As DoubleDim m As Double 5Dim n As Double 10average m n / 2Value of average will be 10. Should be 7.5.24

Error List WindowDim m; n As )25

3.2 Strings Variables and StringsOption Explicit and Option StrictUsing Text Boxes for Input and OutputAuto CorrectionString Properties and Methods:LengthTrimIndexOfToUpperToLowerSubstring26

Strings (continued) ConcatenationThe Empty StringInitial Value of a StringWidening and NarrowingInternal DocumentationLine ContinuationScope of a Variable27

String LiteralA string literal is a sequence ofcharacters surrounded by quotation marks.Examples:"hello""123-45-6789""#ab cde?"28

String VariableA string variable is a name to which astring value can be assigned.Examples:countryssnwordfirstName29

String Variable (continued) Declaration:Dim firstName As Stringvariable namedata type Assignment:firstName "Fred"30

String Variable (continued)You can declare a string variable andassign it a value at the same time.Dim firstName As String "Fred"31

Add MethodLet str be a string literal or variable. Then,lstBox.Items.Add(str)displays the value of str in the list box.32

String VariableYou can assign the value of one stringvariable to another.Dim strVar1 As String "Hello"Dim strVar2 As String "Goodbye"strVar2 strVar1lstOutput.Items.Add(strVar2)Output: Hello33

Variables and StringsPrivate Sub btnDisplay Click(.) HandlesbtnDisplay.ClickDim president As Stringpresident "George ut.Items.Add(president)End SubOutput:presidentGeorge Washington34

Option Strict Visual Basic allows numeric variables to beassigned strings and vice versa, a poorprogramming practice. To prevent such assignments, set OptionStrict to On in the Options dialog box.35

Option Strict (continued) Select Options from the Tools menuIn left pane, expand Projects and SolutionSelect VB DefaultsSet Option Strict to On36

Option Strict (continued)37

Using Text Boxes for Inputand Output The contents of a text box is always a string. Input example:strVar txtBox.Text Output example:txtBox.Text strVar38

Data ConversionBecause the contents of a text box is always astring, sometimes you must convert the inputor output.dblVar CDbl(txtBox.Text)converts a String to a DoubletxtBox.Text CStr(numVar)converts a number to a string39

Auto Correction40

With Option Strict OnDim dblVar As Double, intVar As IntegerDim strVar As StringNot Valid:Replace with:intVar dblVardblVar strVarstrVar intVarintVar CInt(dblVar)dblVar CDbl(strVar)strVar CStr(intVar)41

ConcatenationCombining two strings to make a new stringquote1 "We'll always "quote2 "have Paris."quote quote1 & quote2txtOutput.Text quote & " - Humphrey Bogart"Output:We'll always have Paris. - Humphrey Bogart42

Appending To append str to the string variable varvar var & str Or as a shortcutvar & str43

Appending ExampleDim var As String "Good"var & "bye"txtBox.Text varOutput: Goodbye44

Comment on Example 4ConsidertxtOutput.Text numOfKeys & " keys"The ampersand automatically convertsnumOfKeys into a string before concatenating.We do not have to convert numOfKeys with CStr.45

String Properties and Methods"Visual".Length is 6."Visual".ToUpper is VISUAL."123 Hike".Length is 8."123 Hike".ToLower is 123 hike."a" & " bcd ".Trim & "efg" is abcdefg.46

Positions in a StringPositions of characters in a string arenumbered 0, 1, 2, .Consider the string “Visual Basic”.Position 0: VPosition 1: iPosition 7: BSubstring “al” begins at position 447

Substring MethodLet str be a string.is the substring of lengthn, beginning at position m in str.str.Substring(m, n)“Visual Basic”.Substring(2, 3) is “sua”“Visual Basic”.Substring(0, 1) is “V”48

IndexOf MethodLet str1 and str2 be strings.str1.IndexOf(str2)is the position of the first occurrence of str2 in str1.(Note: Has value -1 if str2 is not a substring of str1.)"Visual Basic".IndexOf("is") is 1."Visual Basic".IndexOf("si") is 9."Visual Basic".IndexOf("ab") is -1.49

The Empty String The string "", which has no characters, iscalled the empty string or the zero-lengthstring. The statement lstBox.Items.Add("") skips aline in the list box. The contents of a text box can be clearedwith either the statementtxtBox.Clear()or the statementtxtBox.Text ""50

Initial Value of a StringVariable By default the initial value is the keywordNothing Strings can be given a different initial valueas follows:Dim name As String "Fred"51

Widening Widening: assigning an Integer value toa Double variable Widening always works. (Every Integervalue is a Double value.) No conversion function needed.52

Narrowing Narrowing: assigning a Double value to anInteger variable Narrowing might not work. (Not everyDouble value is an Integer value.) Narrowing requires the Cint function.53

CommentsPrivate Sub btnCompute Click (.)Handles btnCompute.Click'Calculate the balance in an accountDim rate As Double 'Annual rate of interestDim curBalance As Double 'Current balance54

Internal Documentation1. Other people can easily understand theprogram.2. You can understand the program when youread it later.3. Long programs are easier to read becausethe purposes of individual pieces can bedetermined at a glance.55

Line ContinuationA long line of code can be continued onanother line by using an underscore ( )preceded by a spacemsg "I'm going to make " &"him an offer he can't refuse."56

Implicit Line ContinuationThe line continuation character can beomitted after a comma, ampersand, orarithmetic operator.msg "I'm going to make " &"him an offer he can't refuse."average sumOfNumbers /numberOfNumbers57

Scope (continued) The scope of a variable is the portion of theprogram that can refer to it. Variables declared inside an eventprocedure are said to have local scope andare only available to the event procedure inwhich they are declared.58

Scope Variables declared outside an eventprocedure are said to have class-levelscope and are available to every eventprocedure. Usually declared afterPublic Class formName(In Declarations section of Code Editor.)59

Automatic ColorizationComments – greenString literals – maroonKeywords – blueClass Name – turqoiseNote: Examples of keywords are Handles,Sub, and End. Examples of class names areForm1, Math, and MessageBox.60

3.3 Input and Output Formatting Output with Format FunctionsUsing a Masked Text Box for InputDates as Input and OutputGetting Input from an Input Dialog BoxUsing a Message Dialog Box for OutputNamed ConstantsSending Output to the Printer61

Formatting Output with FormatFunctionsFunctionString ValueFormatNumber(12345.628, 1)12,345.6FormatCurrency(12345.628, 2) 12,345.63FormatPercent(0.183, 0)18%62

Masked Text Box ControlSimilar to an ordinary text box, but hasa Mask property that restricts what canbe typed into the masked text box.Tasks button63

Masked Text Box ControlClick on the Tasks button to reveal theSet Mask property.Click Set Mask to invoke the InputMask dialog box.64

Input Mask Dialog Box65

MaskA Mask setting is a sequence of characters,with 0, L, and & having special meanings. 0 Placeholder for a digit. L Placeholder for a letter. & Placeholder for a character66

Sample Masks State abbreviation: LL Phone number: 000-0000 Social Security Number: 000-00-0000 License plate: &&&&&&67

Dates as Input and Output Date literal: #7/4/1776# Declarations:Dim indDay As DateDim d As Date CDate(txtBox.Text)Dim indDay As Date #7/4/1776#68

Getting Input from an InputDialog BoxstringVar InputBox(prompt, title)fullName InputBox("Enter your full name.","Name")titleprompt69

Using a Message Dialog Boxfor OutputMessageBox.Show(prompt, title)MessageBox.Show("Nice try, but no cigar.","Consolation")titleprompt70

Named Constants Declared withConst CONSTANT NAME As DataType value Value cannot be changed.Examples:Const MIN VOTING AGE As Integer 18Const INTEREST RATE As Double 0.035Const TITLE As String "Visual Basic"71

Sending Output to the PrinterDouble-click on the PrintDocument controlin the Toolbox. (The control will appear inthe form’s component tray.)72

Output to Printer (continued) Double-click on PrintDocument1 to obtainits default event procedure PrintPage. All printing statements appear inside thisprocedure. They begin with the statementDim gr As Graphics e.Graphics Most subsequent statements have the formgr.DrawString(str, font, Brushes.color, x, y)73

Output to Printer (continued)gr.DrawString(str, font, Brushes.color, x, y) str is string to be printed font specifies name, size, and style of fontused (can be set to Me.Font for form’s font) color specifies the color of the printed text x and y specify location of the beginning ofthe printed text74

Output to Printer (continued)x and y are distances measured in points(1 point 1/100 inch)beginning ofprinted text75

Output to Printer (continued) Execute the statementPrintDocument1.Print()to invoke actual printing A PrintPreviewDialog control can be addedto the form. Then you can preview theprinted page with the statementPrintPreviewDialog1.ShowDialog()76

Visual Basic - Chapter 3 Mohammad Shokoohi * Adopted from An Introduction to Programming Using Visual Basic 2010, Schneider. 2 Chapter 3 – Variables, Input, and Output 3.1 Numbers 3.2 Strings 3.3 Input and