Presentation is loading. Please wait.

Presentation is loading. Please wait.

Variable Review & IO User 12/26/2018.

Similar presentations


Presentation on theme: "Variable Review & IO User 12/26/2018."— Presentation transcript:

1 Variable Review & IO User 12/26/2018

2 Introduction Review variable typing and dimension statement format
Data type conversion File IO 12/26/2018

3 Variable Initialization
Numeric variables are automatically initialized to 0: Dim varName As Double To specify a nonzero initial value Dim varName As Double = 50 declares a variable named varName to be of type Double. Actually, the Dim statement causes the computer to set aside a location in memory with the name varName. Since varName is a numeric variable, the Dim statement also places the number zero in that memory location. (We say that zero is the initial value or default value of the variable.) 12/26/2018

4 Multiple Declarations
multiple-declaration statements : Dim a, b As Double Dim a As Double, b As Integer Dim c As Double = 2, b As Integer = 5 12/26/2018

5 Data Conversion Type-casting functions
Converts data from one type to another such as CDbl(n), Cint(n), CStr(n) Previously we used intrinsic functions to convert numeric to string and string to numeric Val(n), Str(n) 12/26/2018

6 Data Conversion numVar = CDbl(txtBox.Text) txtBox.Text = CStr(numVar)
Converts a String to a Double Converts a number to a string CType(numVar,string) ‘Alternative conversion methods Convert.ToString(numVar) numVar.ToString Str(numVar) 12/26/2018

7 CType() CType(expression, typename)
expression – any variable or string literal expression typename – any VB datatype, object, class or structure allowed with in the VB framework Data Conversion numVar = CDbl(txtBox.Text) txtBox.Text = CStr(numVar) 12/26/2018

8 ANSI Character Set If n is between 32 and 255, str
Chr(n):returns the string consisting of the character with ANSI value n Chr(65) A Asc(str):returns the ANSI value of the first character of str Asc(“Apple”) 32 & Chr(176) & “Fahrenheit ° Fahrenheit 12/26/2018

9 Strings String literal
a sequence of characters treated as a single item, surrounded by “” String variable a name used to refer to a string Dim varName As String 12/26/2018

10 String Properties and Methods
A string is an object, like controls, has both properties and methods. Length ToUpper Trim ToLower IndexOf Substring 12/26/2018

11 String Properties str.Length: the number of characters in str
Where str is any string literal or attribute the number of characters in str “Tacoma".Length is 5 12/26/2018

12 String methods str.ToUpper format str.ToLower
with all letters of str capitalized format “Tacoma".ToUpper is TACOMA. str.ToLower with all letters of str in lowercase format “TCC1926".ToLower is tcc1926 12/26/2018

13 Concatenation Combining two strings into a new string.Concatenation is represented by “&” Dim str1 As String = “My GPA is A " Dim Str2 As String = “in Winter 2002" txtOutput.Text = str1 & str2 displays My GPA is A in Winter 2002 12/26/2018

14 Concatenation Combining strings with numbers into a string
Dim str1 As String = “My grade is “ Dim grade As Double = 89 Dim str2 As String = “in Winter 2002" txtOutput.Text = str1 & grade & str2 displays My GPA is 89 in Winter 2002 12/26/2018

15 String Methods str.Substring(m,n) str.Substring(m)
substring consisting of n characters beginning with the character in position m in str “Washington”.Substring(0,4) is “Wash” str.Substring(m) substring beginning with the character in position m in str until the end of str “Washington”.Substring(2) is “shington” 12/26/2018

16 The Empty String zero-length string ""
lstBox.Items.Add("") skips a line txtBox.Text = "“ or txtBox.Clear() clear the text box 12/26/2018

17 Initial Value of a String
A string should be assigned a value before being used By default the initial value is Nothing Strings can be given a different initial value as follows: Dim today As String = "Monday“ 12/26/2018

18 Option Strict The Option Strict statement must appear before any other code Restricts implicit data type conversions to only widening conversions Provides compile-time notification of data lost conversions Generates an error for any undeclared variable 12/26/2018

19 Option Strict The default is Off Option Strict { On | Off } On:
Optional. Enables Option Strict checking Off : Optional. Disables Option Strict checking 12/26/2018

20 Option Strict Example Option Strict On Dim MyVar As Integer
Dim Obj As Object MyVar = 1000 MyVar = ‘ Data lost MyInt = 10 ' Undeclared variable 12/26/2018

21 Using Text Boxes for Input and Output
The contents of a text box is a string The Property “Text” can only be assigned to a string variable type Assigning input strVar = txtBox.Text When using the textbox for output Assigning Output set(ReadOnly = true) txtBox.Text = strVar 12/26/2018

22 Data Files and IO Streams
12/26/2018

23 Creating a Sequential File
Choose a filename – may contain up to 215 characters Select the path for the folder to contain this file Execute a statement like the following: Dim sw As IO.StreamWriter = IO.File.CreateText(filespec) 12/26/2018

24 Open Modes OpenText Format of the IO statement to read data:
Dim sr As IO.StreamReader = IO.File.OpenText(“Colleges.txt") The argument “sr” is used here to indicate a read string CreateText Format of the IO statement to write data: Dim sw As IO.StreamWriter = IO.File.CreateText(“Colleges.txt") The argument “sw” is used here to indicate a write string AppendText Format of the IO statement to Add data: Dim sw As IO.StreamWriter = IO.File.AppendText(“Colleges.txt") 12/26/2018

25 Open Modes CreateText = Opens the file and clears the file, it writes only new data to the file OpenText = Opens the file so that the records can be read AppendText = Opens the file and writes new records to the end of the file 12/26/2018

26 Adding Items to a Sequential File
Execute the statement Dim sw As IO.StreamWriter = IO.File.AppendText(filespec) where sw is a variable name used to store the data in memory and filespec identifies the file. Place data into the file with the WriteLine method. After all the data have been recorded into the file, close the file with the statement sw.Close() 12/26/2018

27 Creating a Sequential File…
Place a line of data into the file with a statement of the form: sw.WriteLine(attribute) Close the file when all data has been added: sw.Close() 12/26/2018

28 Example 1 Private Sub btnCreateFile_Click(...) _
Handles btnCreateFile.Click Dim sw As IO.StreamWriter = IO.File.CreateText(“Colleges.TXT") With sw .WriteLine(“Missouri Western") .WriteLine(“5475") .WriteLine(strCollege) .WriteLine(strFaculty) .Close() End With End Sub 12/26/2018

29 Caution If an existing file is opened for output, the computer will erase the existing file and create a new one. What open mode will clear the file? What open mode will add to the file? 12/26/2018

30 Adding Items to a Sequential File
Execute the statement Dim sw As IO.StreamWriter = IO.File.AppendText(filespec) where sw is a variable name to store the date in memory and filespec identifies the file. Write to the file with the WriteLine method. After all the data have been recorded close. sw.Close() 12/26/2018

31 IO.File.AppendText Append adds to the end of the file
If a file does not exist, it will create one 12/26/2018

32 Sequential File Modes CreateText OpenText AppendText
A file should not be opened in two different modes at the same time. 12/26/2018

33 Code to Read from the file
' Read data from a file and display in a list box Private Sub btnRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRead.Click ' Establish a communication link Dim sr As IO.StreamReader = IO.File.OpenText("Grades.txt") ' Read data line by line and display them in listbox lstDisplay.Items.Clear() lstDisplay.Items.Add(sr.ReadLine()) ' Terminate the communication link sr.Close() End Sub 12/26/2018

34 Input Dialog Box strVar = InputBox(prompt, title) 12/26/2018

35 Code for Input box ' Read data from a file ans display in a list box Private Sub btnRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRead.Click Dim fileName As String ‘set an argument for the file name Dim sr As IO.StreamReader ‘set an argument as the read string ' Get the file name from user fileName = InputBox("Enter the file name", "Enter file name") ' establish a communication link sr = IO.File.OpenText(fileName) ' Read data line by line, display them and the average lstDisplay.Items.Clear() lstDisplay.Items.Add(sr.ReadLine()) ' Terminate the communication link sr.Close() End Sub 12/26/2018

36 Format Functions FormatNumber(n,r) FormatCurrency(n,r)
FormatPercent(n,r) return a string value n - a number, an numeric expression or a string to be formatted r - the number of decimal places default value is 2 12/26/2018

37 Formatting Output with Format Functions
String Value FormatNumber( ,1) FormatNumber(1 + 2) 12,345.6 3.00 FormatCurrency( ,2) FormatCurrency(-100) $12,345.63 ($100.00) FormatPercent(0.185,2) FormatPercent(“0.07”) 18.50% 7.00% 12/26/2018

38 Code the Output ' Format data using format functions
Private Sub btnFormat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFormat.Click lstDisplay.Items.Add(strCollege) lstDisplay.Items.Add(FormatNumber(lngFaculty)) lstDisplay.Items.Add(FormatNumber(lngStudents)) lstDisplay.Items.Add(FormatPercent(sngRatio,2)) End Sub 12/26/2018

39 Formatting Output with Zones
Line up items in columns Use a fixed-width font such as Courier New Divide the characters into zones with a format string. 12/26/2018

40 Formatting output with zones
Zone width Dim fmtStr As String = "{0, 15}{1, 10}{2, 8}“ lstOutput.Items.Add(String.Format(fmtStr, _ data0, data1, data2)) Zone number 12/26/2018

41 Numbers with FMT-zones
A colon and formatting symbol after width to specially format numeric data Zone Format Term Data Number displayed {1,12:N3} {1,12:N0} 34.6 34 {1,12:C1} $1234.6 {1,-12:P} 0.569 56.90% 12/26/2018

42 Formatting with Zones Zone width
left adjusted if preceded with minus sign, right adjusted otherwise Spaces between the successive pairs of brackets will be displayed in the corresponding zones in the output. 12/26/2018

43 Code Example 12/26/2018

44 Dim sr As IO.StreamReader Dim fmtStr As String = "{0,-15}{1,15}{2,15}"
' Read data from a file ans display in a list box Private Sub btnRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRead.Click Dim fileName As String Dim sr As IO.StreamReader Dim fmtStr As String = "{0,-15}{1,15}{2,15}" ' Get the file name from user fileName = InputBox("Enter file name", “File name") ' Establish a communication link sr = IO.File.OpenText(fileName) ' Read data line by line, display them and the average lstDisplay.Items.Clear() lstDisplay.Items.Add(String.Format(fmtStr, “City", “Population", “Jobs")) lstDisplay.Items.Add(String.Format(fmtStr, sr.ReadLine(), sr.ReadLine(), sr.ReadLine())) ' Terminate the communication link sr.Close() End Sub 12/26/2018

45 Using a Message Dialog Box for Output
MsgBox(prompt,title) MsgBox(prompt, , title) is executed, where prompt and title are strings, a message dialog box appears with prompt displayed and the title bar caption title and stays on the screen until the user presses Enter, clicks on the box in the upper-right corner, or clicks OK. For instance, the state-ment MsgBox("Nice try, but no cigar.", , "Consolation") 12/26/2018

46 Code 'Message sent before clearing the items in a list box
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click MsgBox(" All items will be deleted", , "Delete items") lstDisplay.Items.Clear() End Sub 12/26/2018


Download ppt "Variable Review & IO User 12/26/2018."

Similar presentations


Ads by Google