Sequential Access Files

Sequential Access Files
Dr.NaveenBansal Profile Pic
Dr.NaveenBansal,India,Teacher
Published Date:25-10-2017
Your Website URL(Optional)
Comment
CHAPTER22 I’m Saving for the Future (Sequential Access Files) After studying Chapter 22, you should be able to: Open and close a sequential access file Write data to a sequential access file Send the focus to a text box Read data from a sequential access file Determine whether a sequential access file exists Test for the end of a sequential access file400 CHAPTER 22 I’m Saving for the Future (Sequential Access Files) Sequential Access Files In addition to getting data from the keyboard and sending data to the computer screen, an application also can get data from and send data to a file on a disk. Getting data from a file is referred to as “reading from the file,” and sending data to a file is referred to as “writing to the file.” Files to which data is written are called output files, because the files store the output produced by an application. Files that are read by the computer are called inputfiles, because an application uses the data in these files as input. Most input and output files are composed of lines of text that are both read and written sequentially. In other words, they are read and written in consecutive order, one line at a time, beginning with the first line in the file and ending with the last line in the file. Such files are referred to as sequential access files, because ofthemannerinwhichthelinesoftextareaccessed. Theyalsoare calledtextfiles,becausethey are composed of lines of text. Examples of text stored in sequential access files include an employee list, a memo, and a sales report. You will use a sequential access file in the Game Show Contestants application, which you code in the remaining sections of this chapter. Figure 22-1 shows the application’s user interface. The interface provides a text box for entering a contestant’s name. The Write to File button will write the name to a sequential access file. The Read from File button will read each name from the sequential access file and display each in the Contestants box. (The txtContestants control’s Multiline and ReadOnly properties are set to True, and its ScrollBars property is set to Vertical.) You will code the Write to File button first. txtName txtContestants Figure 22-1 Interface for the Game Show Contestants application Write Those Lines of Text An item of data—such as the string “Yolanda”—is viewed differently by a human being and a computer. To a human being, the string represents a person’s name; to a computer, it is merely a sequence of characters. Programmers refer to a sequence of characters as a stream of characters. In Visual Basic, you use a StreamWriter object to write a stream of characters to a sequential access file. Before you create the StreamWriter object, you first declare a variable to store the object in the computer’s internal memory. Figure 22-2 shows the syntax and an example of declaring a StreamWriter variable. The IO in the syntax stands for Input/Output.401 Write Those Lines of Text Declaring a StreamWriter variable Syntax Dim Private streamWriterVariableName As IO.StreamWriter Example Dim outFile As IO.StreamWriter declares a StreamWriter variable named outFile Figure 22-2 Syntax and an example of declaring a StreamWriter variable To begin coding the Write to File button’s Click event procedure: 1. Start Visual Studio 2010 or Visual Basic 2010 Express and permanently display the Solution Explorer window. Open the Contestant Solution (Contestant Solution.sln) file contained in the ClearlyVB2010\Chap22\Contestant Solution folder. If the designer window is not open, double-click frmMain.vb in the Solution Explorer window. 2. Open the Code Editor window. Locate the code template for the btnWrite control’s Click event procedure. Click the blank line below the ' declare a StreamWriter variable comment and then enter the following declaration statement: Dim outFile As IO.StreamWriter Afterdeclaring aStreamWritervariable,you canusethesyntaxshown inFigure22-3 tocreate a StreamWriter object. As the figure indicates, creating a StreamWriter object involves opening a sequential access file using one of two methods: CreateText or AppendText. You use the CreateTextmethod to open a sequential access file for output. When you open a file for output, the computercreates anew,empty fileto whichdatacanbewritten. If thefilealreadyexists,the computer erases the contents of the file before writing any data to it. You use the AppendText method to open a sequential access file for append. When a file is opened for append, new data is written after anyexisting datain thefile. If the filedoes not exist,the computer creates the file for you. In addition to opening the file, both methods automatically create a StreamWriter object to represent the file in the application. You assign the StreamWriter object to a StreamWriter variable, which you use to refer to the file in code. Also included in Figure 22-3 are examples of using the CreateText and AppendText methods. When processing the statement in Example 1, the computer searches for the pay.txt file in the Chap22 folder on the F drive. If the file exists, its contents are erased and the file is opened for output; otherwise, a new, empty file is created and opened for output. The statement creates a StreamWriter object and assigns it to the outFile variable. You should specify the folder path in the fileName argument only when you are sure that the folder path will not change. (Keep in mind that a USB drive may have a different letter designation on another computer.) Unlike the fileNameargumentinExample1,thefileNameargumentinExample2doesnotcontainafolder path. Therefore, the computer will search for the file in the default folder, which is the current project’s bin\Debug folder. In this case, if the computer locates the report.txt file in the default folder,itopensthefileforappend.Ifitdoesnotfindthefile,itcreatesanew,emptyfileandthen opens the file for append. Like the statement in Example 1, the statement in Example 2 creates a StreamWriter object and assigns it to the outFile variable.402 CHAPTER 22 I’m Saving for the Future (Sequential Access Files) Creating a StreamWriter object Syntax IO.File.method(fileName) method Description CreateText opens a sequential access file for output AppendText opens a sequential access file for append Example 1 outFile = IO.File.CreateText("F:\Chap22\pay.txt") opens the pay.txt file for output; creates a StreamWriter object and assigns it to the outFile variable Example 2 outFile = IO.File.AppendText("report.txt") opens the report.txt file for append; creates a StreamWriter object and assigns it to the outFile variable Figure 22-3 Syntax and examples of creating a StreamWriter object by opening a file When the user clicks the Write to File button in the Game Show Contestants interface, the name entered in the Name box should be added to the end of the existing names in the file. Therefore, you will need to open the sequential access file for append. A descriptive name for a file that stores the names of contestants is contestants.txt. Although it is not a requirement, the “txt”(shortfor “text”)filenameextensioniscommonlyusedwhennamingsequentialaccessfiles; this is because the files contain text. To continue coding the btnWrite control’s Click event procedure: 1. Click the blank line below the ' open the file for append comment and then enter the following assignment statement: outFile = IO.File.AppendText(''contestants.txt'') After opening a file for either output or append, you can begin writing data to it. You write data to a sequential access file using either the Write method or the WriteLine method; however, in most cases you will use the WriteLine method. The difference between both methods is that the WriteLine method writes a newline character after the data. Figure 22-4 shows the syntax and an example of both methods. As the figure indicates, when using the Write method, the next characterwrittentothefilewillappearimmediatelyaftertheletterointhestring “Hello”.When using the WriteLine method, however, the next character written to the file will appear on the line immediately below the string. You do not need to include the file’s name in either method’s syntax, because the data will be written to the file associated with the StreamWriter variable.403 Write Those Lines of Text Writing data to a sequential access file Syntax streamWriterVariableName.Write(data) streamWriterVariableName.WriteLine(data) Example 1 outFile.Write("Hello") Result the next character will appear Hello immediately after the letter o Example 2 outFile.WriteLine("Hello") Result Hello the next character will appear on the next line Figure 22-4 Syntax and examples of writing data to a sequential access file In the Game Show Contestants application, each contestant’s name should appear on a separate line in the file, so you will use the WriteLine method to write each name to the file. To continue coding the btnWrite control’s Click event procedure: 1. Click the blank line below the ' write the name on a separate line in the file comment and then enter the following statement: outFile.WriteLine(txtName.Text) You should use the Close method to close an output sequential access file as soon as you are finished using it. This ensures that the data is saved and it makes the file available for use elsewhere in the application. The syntax to close an output sequential access file is streamWriterVariableName.Close(). Here again, notice that you use the StreamWriter variable to refer to the file in code. To continue coding the btnWrite control’s Click event procedure: 1. Click theblankline below the 'closethefile comment and then enter the following statement: outFile.Close() Tomakeitmoreconvenientfortheusertoenterthenextname,youwillclearthecurrentname from the Name box and then send the focus to the box. You can use a text box’s Focusmethod to send the focus to the text box. The method’s syntax is textbox.Focus(). To complete the btnWrite control’s Click event procedure: 1. Click the blank line below the ' clear the Name box and then set the focus comment. Enter the following two statements: txtName.Text = String.Empty txtName.Focus()404 CHAPTER 22 I’m Saving for the Future (Sequential Access Files) Figure 22-5 shows the code entered in the Write to File button’s Click event procedure. Private Sub btnWrite_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnWrite.Click ' writes a name to a sequential access file ' declare a StreamWriter variable Dim outFile As IO.StreamWriter ' open the file for append outFile = IO.File.AppendText("contestants.txt") ' write the name on a separate line in the file outFile.WriteLine(txtName.Text) ' close the file outFile.Close() ' clear the Name box and then set the focus txtName.Text = String.Empty txtName.Focus() End Sub Figure 22-5 Write to File button’s Click event procedure To test the btnWrite control’s Click event procedure: 1. Save the solution and then start the application. Type Hannah Jones in the Name box and then click the Write to File button. Use the application to write the following four names to the file: Clark Smith Khalid Shaw Joe Mendez Charise Jackson 2. Click the Exit button. 3. Now you will open the contestants.txt file to verify its contents. Click File on the menu bar and then click Open File. Open the project’s bin\Debug folder. Click contestants.txt in the list of filenames and then click the Open button. The contestants.txt window opens and shows the five names contained in the file. See Figure 22-6. Close button each name appears on a separate line in the file Figure 22-6 Names contained in the contestants.txt file 4. Close the contestants.txt window by clicking its Close button.405 Now Read Those Lines of Text Mini-Quiz 22-1 See Appendix B for the answers. 1. Write the code to declare a variable that can be used to write data to a sequential access file. Name the variable outFile. 2. The AppendText method creates a object. 3. Write a Visual Basic statement that sends the focus to the txtCity control. Now Read Those Lines of Text Next, you will code the Read from File button. In Visual Basic, you use a StreamReader object to read data from a sequential access file. Before creating the StreamReader object, you first declare a variable to store the object in the computer’s internal memory. Figure 22-7 shows the syntax and an example of declaring a StreamReader variable. As mentioned earlier, the IO in the syntax stands for Input/Output. Declaring a StreamReader variable Syntax Dim Private streamReaderVariableName As IO.StreamReader Example Dim inFile As IO.StreamReader declares a StreamReader variable named inFile Figure 22-7 Syntax and an example of declaring a StreamReader variable To begin coding the Read from File button’s Click event procedure: 1. Locate the code template for the btnRead control’s Click event procedure. 2. Click the blank line below the ' declare variables comment and then enter the following declaration statement: Dim inFile As IO.StreamReader After declaring a StreamReader variable, you can use the OpenTextmethod to open a sequential access file for input; doing this automatically creates a StreamReader object. When a file is opened for input, the computer can read the lines of text stored in the file. Figure 22-8 shows the OpenText method’s syntax along with an example of using the method. The fileName argument in the example does not include a folder path, so the computer will search for the report.txt file in the current project’s bin\Debug folder. If the computer finds the file, it opens the file for input; otherwise, a run time error occurs and causes the application to end abruptly. You assign the StreamReader object created by the OpenText method to a StreamReader variable, which you use to refer to the file in code.406 CHAPTER 22 I’m Saving for the Future (Sequential Access Files) Creating a StreamReader object Syntax IO.File.OpenText(fileName) Example inFile = IO.File.OpenText("report.txt") opens the report.txt file for input; creates a StreamReader object and assigns it to the inFile variable Figure 22-8 Syntax and an example of creating a StreamReader object by opening a file YoucanusetheExistsmethodtoavoidtheruntimeerrorthatoccurswhenthecomputercannot locate the file you want opened for input. Figure 22-9 shows the method’s syntax and includes an example of using the method. If the fileName argument does not include a folder path, the computer searches for the file in the current project’s bin\Debug folder. The Exists method returns the Boolean value True if the file exists; otherwise, it returns the Boolean value False. Determining whether a sequential access file exists Syntax IO.File.Exists(fileName) Example If IO.File.Exists("report.txt") = True Then determines whether the report.txt file exists in the current project’s bin\Debug folder; you also can write the If clause as If IO.File.Exists("report.txt") Then Figure 22-9 Syntax and an example of the Exists method To continue coding the btnRead control’s Click event procedure: 1. Click the blank line below the ' determine whether the file exists comment and then enter the following If clause: If IO.File.Exists(''contestants.txt'') = True Then 2. If the file exists, you will use the OpenText method to open the file. Enter the following comment and assignment statement. Press Enter twice after typing the assignment statement. ' open the file for input inFile = IO.File.OpenText(''contestants.txt'') 3. If the file does not exist, you will display an appropriate message. Enter the additional lines of code shown in Figure 22-10.407 Now Read Those Lines of Text enter these five lines of code Figure 22-10 Code entered in the selection structure’s false path After opening a file for input, you can use the ReadLine method to read the file’s contents, one line at a time. A line is defined as a sequence (stream) of characters followed by the newline character. The ReadLine method returns a string that contains only the sequence of characters in the current line; the string does not include the newline character at the end of the line. In most cases, you assign the string returned by the ReadLine method to a String variable. Figure 22-11 shows the ReadLine method’s syntax and includes an example of using the method. The ReadLine method does not require you to provide the file’s name, because it uses the file associated with the StreamReader variable. ReadLine method Syntax streamReaderVariableName.ReadLine Example strMessage = inFile.ReadLine reads a line of text from the sequential access file associated with the inFile variable and assigns the line, excluding the newline character, to the strMessage variable Figure 22-11 Syntax and an example of the ReadLine method In most cases, an application will need to read each line of text contained in a sequential access file, one line at a time. You can do this using a loop along with the Peek method. The Peek method “peeks” into the file to determine whether the file contains another character to read. If the file contains another character, the Peek method returns the character; otherwise, it returns the number –1 (a negative 1). The Peek method’s syntax is shown in Figure 22-12 along with an example of using the method. The Do clause in the example tells the computer to process the loop instructions until the Peek method returns the number –1, which indicates that there are nomorecharactersto read.In otherwords,theDoclausetells thecomputertoprocesstheloop instructions until it reaches the end of the file.408 CHAPTER 22 I’m Saving for the Future (Sequential Access Files) Peek method Syntax streamReaderVariableName.Peek Example Do Until inFile.Peek = –1 strLineOfText = inFile.ReadLine MessageBox.Show(strLineOfText) Loop reads each line of text from the sequential access file associated with the inFile variable, line by line; each line (excluding the newline character) is assigned to the strLineOfText variable and is then displayed in a message box Figure 22-12 Syntax and an example of the Peek method To continue coding the btnRead control’s Click event procedure: 1. First, you will declare a variable to store the string returned by the ReadLine method. Click the blank line below the Dim statement. Each line in the contestants.txt file represents a name, so you will call the variable strName. Enter the following declaration statement: Dim strName As String 2. Click the blank line below the statement that opens the contestants.txt file for input. EnterthefollowingcommentandDoclause,beingsuretotypetheminussignbeforethe number 1: ' process the loop instructions until the end of the file Do Until inFile.Peek = –1 3. Now you will tell the computer to read a line of text and assign it (excluding the newline character) to the strName variable. Enter the following comment and assignment statement: ' read a name strName = inFile.ReadLine 4. Next, you will display the name in the Contestants box. Enter the following comment and assignment statement: ' display the name txtContestants.Text = txtContestants.Text & strName & ControlChars.NewLine 5. If necessary, delete the blank line above the Loop clause. Justasyou do withan outputsequential accessfile, youshould usetheClosemethodto close an inputsequentialaccessfileassoonasyouarefinishedusingit.Doingthismakesthefileavailable for use elsewhere in the application. The syntax to close an input sequential access file is streamReaderVariableName.Close(). Notice that you use the StreamReader variable to refer to the file in code.409 Now Read Those Lines of Text To finish coding the btnRead control’s Click event procedure: 1. Click after the letter p in the Loop clause and then press Enter to insert a blank line. 2. Enter the following comment and statement: ' close the file inFile.Close() Figure 22-13 shows the code entered in the Read from File button’s Click event procedure. Private Sub btnRead_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRead.Click ' reads names from a sequential access file ' and displays them in the interface ' declare variables Dim inFile As IO.StreamReader Dim strName As String ' clear previous names from the Contestants box txtContestants.Text = String.Empty ' determine whether the file exists If IO.File.Exists("contestants.txt") = True Then ' open the file for input inFile = IO.File.OpenText("contestants.txt") ' process the loop instructions until the end of the file Do Until inFile.Peek = -1 ' read a name strName = inFile.ReadLine ' display the name txtContestants.Text = txtContestants.Text & strName & ControlChars.NewLine Loop ' close the file inFile.Close() Else MessageBox.Show("Can't find the contestants.txt file", "Game Show Contestants", MessageBoxButtons.OK, MessageBoxIcon.Information) End If End Sub Figure 22-13 Read from File button’s Click event procedure To test the btnRead control’s Click event procedure: 1. Save the solution and then start the application. Click the Read from File button. The five names contained in the contestants.txt file appear in the Contestants box, as shown in Figure 22-14.410 CHAPTER 22 I’m Saving for the Future (Sequential Access Files) Figure 22-14 Contents of the contestants.txt file listed in the Contestants box 2. On your own, add the following two names to the file: Ginger Ozark James Kartony 3. Click the Read from File button to display the seven names in the interface, and then click the Exit button. 4. Next, you will modify the If clause in the btnRead control’s Click event procedure. More To learn specifically, you will change the Exists method’s fileName argument from contestants.txt more about to Chap22\contestants.txt. Doing this will allow you to test the code entered in the sequential selection structure’s false path. Change contestants.txt in the If clause to access Chap22\contestants.txt. files, see the Sequential Access 5. Save the solution and then start the application. Click the Read from File button. Files section in the Because the contestants.txt file does not exist in the Chap22 folder, the Exists method in Ch22WantMore.pdf file. the If clause returns the Boolean value False. As a result, the instruction in the selection structure’s false path is processed. The instruction displays the “Can’t find the To learn contestants.txt file” message in a message box. Close the message box and then click the how to Exit button. handle exceptions 6. Change Chap22\contestants.txtin the If clause tocontestants.txt. Save the solution that occur and then start the application. Click the Read from File button to display the contents when using sequential of the contestants.txt file in the Contestants box. access files, view the Ch22-TryCatch video. 7. Click the Exit button. Close the Code Editor window and then close the solution. Mini-Quiz 22-2 See Appendix B for the answers. 1. Write the code to declare a variable that can be used to read data from a sequential access file. Name the variable inFile. 2. The OpenText method creates a object. 3. The string returned by the ReadLine method contains the newline character. a. True b. False411 Key Terms Summary l An application can write data to a sequential access file. It also can read data from the file. The data in a sequential access file is always accessed in consecutive order (sequentially) from the beginning of the file through the end of the file. l You use a StreamWriter object to write a sequence (stream) of characters to a sequential access file. The StreamWriter object is created when you open a file for either output or append. You use a StreamReader object to read a sequence (stream) of characters from a sequential access file. The StreamReader object is created when you open a file for input. l You can use either the Write method or the WriteLine method to write data to a sequential access file. You use the ReadLine method to read a line of text from a sequential access file. The ReadLine method returns a string that includes only the characters on the current line; it does not include the newline character at the end of the line. l You should use the Close method to close a sequential access file as soon as you are finished using the file. l You can use a text box’s Focus method to send the focus to the text box. l The Exists method returns a Boolean value that indicates whether a sequential access file exists. l If a file contains another character to read, the Peek method returns the character; otherwise, it returns the number –1. Key Terms AppendText method—used with a StreamWriter variable to open a sequential access file for append Close method—used with either a StreamWriter variable or a StreamReader variable to close a sequential access file CreateText method—used with a StreamWriter variable to open a sequential access file for output Exists method—used to determine whether a file exists Focus method—moves the focus to a specified control during run time Input files—files from which an application reads data Line—a sequence (stream) of characters followed by the newline character OpenTextmethod—used with a StreamReader variable to open a sequential access file for input Output files—files to which an application writes data Peek method—used with a StreamReader variable to determine whether a file contains another character to read ReadLine method—used with a StreamReader variable to read a line of text from a sequential access file Sequential access files—files composed of lines of text that are both read and written sequentially; also called text files Stream of characters—a sequence of characters StreamReaderobject—usedtoreadasequence(stream)ofcharactersfromasequentialaccessfile412 CHAPTER 22 I’m Saving for the Future (Sequential Access Files) StreamWriter object—usedtowriteasequence(stream) of characters to a sequential access file Text files—another name for sequential access files Write method—used with a StreamWriter variable to write data to a sequential access file; differs from the WriteLine method in that it does not write a newline character after the data WriteLine method—used with a StreamWriter variable to write data to a sequential access file; differs from the Write method in that it writes a newline character after the data Review Questions 1. Whichofthefollowingopensthecities.txtfileandallowsthecomputertowritenewdata to the end of the file’s existing data? a. outFile = IO.File.AddText("cities.txt") b. outFile = IO.File.AppendText("cities.txt") c. outFile = IO.File.InsertText("cities.txt") d. outFile = IO.File.OpenText("cities.txt") 2. If the file to be opened exists, the method erases the file’s contents. a. AppendText c. InsertText b. CreateText d. OpenText 3. Which of the following reads a line of text from a sequential access file and assigns the line (excluding the newline character) to the strLine variable? a. inFile.Read(strLine) c. strLine = inFile.ReadLine b. inFile.ReadLine(strLine) d. strLine = inFile.Read(line) 4. What does the Peek method return when the end of the file is reached? a. –1 c. the last character in the file b. 0 d. the newline character 5. Which of the following can be used to determine whether the pay.txt file exists? a. If IO.File.Exists("pay.txt") = True Then b. If IO.File("pay.txt").Exists = True Then c. If IO.Exists("pay.txt") = True Then d. If IO.Exists.File("pay.txt") = True Then 6. Which of the following closes an input sequential access file named states.txt? The file is associated with a StreamReader variable named inFile. a. StreamReader(inFile).Close() c. inFile.Close() b. StreamReader.Close(inFile) d. Close(inFile)413 Exercises 7. Which of the following writes the contents of the strFirst and strLast variables on separate lines in the names.txt file? The file is associated with a StreamWriter object named outFile. a. StreamWriter.WriteLine(strFirst) StreamWriter.Write(strLast) b. outFile.WriteLine(strFirst) outFile.WriteLine(strLast) c. outFile.Write(strFirst) outFile.Write(strLast) d. outFile("names.txt").WriteLine(strFirst) outFile("names.txt").WriteLine(strLast) Exercises 1. Open the Gross Pay Solution (Gross Pay Solution.sln) file contained in the TRY THIS ClearlyVB2010\Chap22\Gross Pay Solution folder. If necessary, open the designer window. The interface provides a text box for entering a gross pay amount. The Save button should write the gross pay amount to a sequential access file named gross.txt. Save the file in the project’s bin\Debug folder. The Display button should read the gross pay amounts from the gross.txt file and display each (formatted with a dollar sign and two decimal places) in the interface. Open the Code Editor window. Code the Click event procedures for the btnSave and btnDisplay controls. Save the solution and then start the application. Write the following 10 gross pay amounts to the file: 600, 1250, 750.67, 350.75, 2000, 450, 125.89, 560, 1400, and 555.78. Click the Display button to display the gross pay amounts in the interface. Close the Code Editor window and then close the solution. (See Appendix B for the answer.) 2. Open the Name Solution (Name Solution.sln) file contained in the ClearlyVB2010\ TRY THIS Chap22\Name Solution folder. If necessary, open the designer window. Open the names.txt file contained in the project’s bin\Debug folder. The sequential access file contains five names. Close the names.txt window. The Display button’s Click event procedure should read the five names contained in the names.txt file, storing each in a five-element one-dimensional array. The procedure should sort the array in ascending order and then display the contents of the array in the lblFriends control. Code the procedure. Save the solution and then start and test the application. Close the Code Editor window and then close the solution. If you need to recreate the names.txt file, open the file in a window in the IDE. Delete the contents of the file and then type the following five names, pressing Enter after typing each name: Jennifer, Zelda, Abby, Bruce, and Karen. (See Appendix B for the answer.) 3. Open the Salary Solution (Salary Solution.sln) file contained in the ClearlyVB2010\ MODIFY THIS Chap22\Salary Solution folder. If necessary, open the designer window. Open the Code Editor window and study the existing code. The btnDisplay control’s Click event procedure stores six salary amounts in a one-dimensional Integer array named intSalaries. Each salary amount corresponds to asalary code from 1 through 6. Code 1’s salary is stored in the intSalaries(0) element in the array, code 2’s salary is stored in the intSalaries(1) element, and so on. After storing the salary amounts in the array, the procedure prompts the user to enter a salary code. It then displays the amount associated with the code. Currently, the Dim statement assigns the six salary amountstothearray.Modifytheproceduresothatitreadsthesalaryamountsfromthe salary.txt file and stores each in the array. The salary.txt file is contained in the project’s bin\Debug folder. Save the solution and then start and test the application. Close the Code Editor window and then close the solution.414 CHAPTER 22 I’m Saving for the Future (Sequential Access Files) INTRODUCTORY 4. Open the CD Solution (CD Solution.sln) file contained in the ClearlyVB2010\Chap22\ CD Solution-Introductory folder. The interface provides a text box for entering the name of a CD. The Save CD button’s Click event procedure should write the CD name to a sequential access file named cds.txt. Save the file in the project’s bin\Debug folder. The Display CDs button’s Click event procedure should read the CD names from thecds.txtfileanddisplayeachintheinterface.OpentheCodeEditorwindowandcode both procedures. Save the solution and then start and test the application. Close the Code Editor window and then close the solution. INTRODUCTORY 5. Open the Test Scores Solution (Test Scores Solution.sln) file contained in the ClearlyVB2010\Chap22\Test Scores Solution folder. Open the Code Editor window. ThebtnSave control’s Clickevent procedureshouldallowtheuserto enteranunknown number of test scores, saving each score in a sequential access file. The btnCount control’s Click event procedure should display (in a message box) the number of scores stored in the file. Code both procedures. Save the solution and then start and test the application. Close the Code Editor window and then close the solution. INTERMEDIATE 6. Open the CD Solution (CD Solution.sln) file contained in the ClearlyVB2010\Chap22\ CD Solution-Intermediate folder. The interface allows the user to enter the name of a CD and the name of the artist associated with the CD. The Save Information button’s Click event procedure should write the CD and artist names to a sequential access file named cdInfo.txt. Save the file in the project’s bin\Debug folder. The CD and artist names should be written on separate lines in the file. In other words, the first CD name should be written on the first line in the file, and the first artist name should be written on the second line in the file. The Display Information button’s Click event procedure should read the names from the cdInfo.txt file and display each in the interface. Display the CD names in the txtCds control. Display the artist names in the txtArtists control. Open the Code Editor window and code both procedures. Save the solution and then start and test the application. Close the Code Editor window and then close the solution. INTERMEDIATE 7. In this exercise, you code an application that reads five numbers from a sequential access file and stores the numbers in a one-dimensional array. The application then increases each number by 1 and writes the numbers to the file. The application also displays the current contents of the sequential access file. Open the Numbers Solution (Numbers Solution.sln) file contained in the ClearlyVB2010\Chap22\Numbers Solution folder. Open the Code Editor window. Code the btnDisplay control’s Click event procedure so it reads the five numbers stored in the numbers.txt file and displays the numbers in the lblNumbers control. The numbers.txt file is contained in the project’s bin\Debug folder. Currently, the file contains the numbers 1 through 5. Code the btnUpdate control’s Click event procedure so it reads the five numbers from the numbers.txt file and stores the numbers in an array. It then should increase each numberinthearrayby1andwritethearraycontentstoanemptynumbers.txtfile.Save the solution and then start the application. Click the Display button. The numbers 1 through 5 appear in the interface. Click the Update button and then click the Display button. The numbers 2 through 6 appear in the interface. Close the Code Editor window and then close the solution. If you need to recreate the numbers.txt file, open the file in a window in the IDE. Delete the contents of the file and then type the numbers 1 through 5, pressing Enter after typing each number. ADVANCED 8. During July and August of each year, the Political Awareness Organization (PAO) sends a questionnaire to the voters in its district. The questionnaire asks each voter for his or her political party (Democratic, Republican, or Independent) and age. From the returned questionnaires, the organization’s secretary tabulates the number of Democrats, Republicans, and Independents in the district. The secretary wants an application that she can use to save each respondent’s information (political party and age) to a sequential access file. The application also should calculate and display the415 Exercises number of voters in each political party. Create a new Visual Basic Windows application. Use the following names for the solution and project, respectively: PAO Solution and PAO Project. Save the application in the ClearlyVB2010\Chap22 folder. Change the name of the form file on your disk to frmMain.vb. If necessary, change the form’s name to frmMain. Create the interface shown in Figure 22-15. The Party text box should accept only the Backspace key and the letters D, d, R, r, I, or i. The Age text box should accept only numbers and the Backspace key. Code the Click event procedures for the Write to File and Display Totals buttons. Save the solution and then start and test the application. Close the Code Editor window and then close the solution. Figure 22-15 Interface for Exercise 8 9. Open the FigureThisOut Solution (FigureThisOut Solution.sln) file contained in the FIGURE THIS OUT ClearlyVB2010\Chap22\FigureThisOut Solution folder. Open the Code Editor window and study the existing code. Why does the true path in the btnWrite control’s Click event procedure use the CreateText method to open the sequential access file, while its false path uses the AppendText method? Start and test the application. Close the Code Editor window and then close the solution. 10. Open the SwatTheBugs Solution (SwatTheBugs Solution.sln) file contained in the SWAT THE BUGS ClearlyVB2010\Chap22\SwatTheBugs Solution folder. Open the Code Editor window and study the existing code. Start the application. Test the application using Sue and 1000, and then using Pete and 5000. After a short time, the application ends with an error. Read the error message. Click Debug on the menu bar and then click Stop Debugging. Open the bonus.txt file. Notice that the file is empty. Close the bonus.txt window. Locate and correct the errors in the code. Save the solution and then start and test the application again. Close the Code Editor window and then close the solution.This page intentionally left blank CHAPTER23 The String Section (String Manipulation) After studying Chapter 23, you should be able to: Determine the number of characters in a string Remove spaces from the beginning and end of a string Replace characters in a string Insert characters in a string Search a string Access characters in a string Remove characters located anywhere in a string Compare strings using pattern-matching418 CHAPTER 23 The String Section (String Manipulation) Working with Strings Many times, an application will need to manipulate (process) string data in some way. For example, it may need to look at the first character in an inventory part number to determine the part’s location in the warehouse. Or, it may need to search an address to determine the street name. In this chapter, you will learn several ways of manipulating strings in Visual Basic. You will begin by learning how to determine the number of characters in a string. How Many Characters Are There? If an application expects the user to enter a seven-digit phone number or a five-digit ZIP code, you should verify that the user entered the required number of characters. The number of characters contained in a string is stored in the string’s Length property. Not surprisingly, the value stored in the property is an integer. Figure 23-1 shows the syntax of the Length property and includes examples of using the property. In the syntax, string can be a String variable, a String named constant, or the Text property of a control. Length property Syntax Purpose string.Length stores an integer that represents the number of characters contained in the string Example 1 strFullName = "Lee Thompson" intNumChars = strFullName.Length assigns the number 12 to the intNumChars variable Example 2 intNumChars = txtZip.Text.Length assigns the number of characters in the txtZip control’s Text property to the intNumChars variable Example 3 Do strZip = InputBox("5-digit ZIP code", "ZIP") Loop Until strZip.Length = 5 continues prompting the user for a ZIP code until the user enters exactly five characters Figure 23-1 Syntax and examples of the Length property Get Rid of Those Spaces When entering data in either a text box or an input box, it’s not unusual for a user to inadvertently press the Spacebar either before or after typing the data. You can use the Trim method to remove (trim) these extraneous space characters. Figure 23-2 shows the method’s syntax and includes an example of using the method. In the syntax, string can be a String variable, a String named constant, or the Text property of a control. When processing the Trim method, the computer first makes a temporary copy of the string in memory. It then performs the necessary trimming on the copy only. In other words, the Trim method does not remove any characters from the original string. The Trim method returns a string that excludes any leading or trailing spaces. (You learned about the Trim method in Chapter 11.)

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.