Chapter 8


[Page 699 (continued)]

Exercises 8.1

1.

Hello

3.

Bon Jour

5.

You must enter a number.

7.

Error occurred.

9.

File AGES.TXT contains an invalid age.

11.

The file WELCOME.TXT is created and has the following lines:

Hello Bon Jour


13.

The filespec YOB.TXT needs to be delimited with quotation marks.

15.

There should be no quotations around the variable name as the parameter to the CreateText method.

17.

The variable age is declared within the Try-Catch-Finally block and therefore is not available below the line End Try.

19.

Private Sub btnCreate_Click(...) Handles btnCreate.Click   'Create a sequential file, and populate it.   Dim sw As IO.StreamWriter = IO.File.CreateText("COWBOY.TXT")   sw.WriteLine("Colt Peacemaker")   sw.WriteLine(12.2)   sw.WriteLine("Holster")   sw.WriteLine(2)   sw.WriteLine("Levi Strauss Jeans")   sw.WriteLine(1.35)   sw.WriteLine("Saddle")   sw.WriteLine(40)   sw.WriteLine("Stetson")   sw.WriteLine(10)   sw.Close()        'Always close the writer when finished.   MsgBox("The file has been created.", 0, "DONE") End Sub


21.

Private Sub btnAdd_Click(...) Handles btnAdd.Click   'Append to a sequential file.   Dim sw As IO.StreamWriter = IO.File.AppendText("COWBOY.TXT")   sw.WriteLine("Winchester rifle")   sw.WriteLine(20.5)   sw.Close()   MsgBox("The item has been added to the file.", 0, "DONE") End Sub



[Page 700]
23.

Private Sub btnAdd_Click(...) Handles btnAdd.Click   'Add new item to list from COWBOY.TXT,   'and save in alphabetical order into COWBOY2.TXT.   Dim flag As Boolean   Dim item, price As String   'Open COWBOY for input and COWBOY2 for output.   Dim sr As IO.StreamReader = IO.File.OpenText("COWBOY.TXT")   Dim sw As IO.StreamWriter = IO.File.CreateText("COWBOY2.TXT")   flag = False   item = ""   'Loop until we reach the new item to add or run out of room.   Do While (item < txtItem.Text) And (sr.Peek <> -1)     'Read the current item from the file.     item = sr.ReadLine     price = sr.ReadLine     'If we have reached the new item, add the new item.     If item > txtItem.Text Then       'Add the new item and the new item's price.       sw.WriteLine(txtItem.Text)       sw.WriteLine(txtPrice.Text)       'Set flag true so we don't add it again at the end.       flag = True     End If     'Add the current item and price.     sw.WriteLine(item)     sw.WriteLine(price)   Loop   'If there are any more items to read, write them to the output.   Do While (sr.Peek <> -1)     item = sr.ReadLine     price = sr.ReadLine     sw.WriteLine(item)     sw.WriteLine(price)   Loop   'If the new item hasn't been written yet, write it.   If Not flag Then     sw.WriteLine(txtItem.Text)     sw.WriteLine(txtPrice.Text)   End If   sr.Close()    'Always close the reader when finished.   sw.Close()    'Always close the writer when finished.   'Display a message, and clear the input text boxes.   MsgBox("Item added to COWBOY2.TXT", 0, "Note") End Sub


25.

Private Sub btnLookup_Click(...) Handles btnLookup.Click   'Lookup person in data file to get age.   Dim found As Boolean = False   Dim name As String, yob As Integer   Dim sr As IO.StreamReader = IO.File.OpenText("YOB.TXT")   'Loop through file until end or name found.   Do While (sr.Peek <> -1) And (Not found)     name = sr.ReadLine     yob = CInt(sr.ReadLine) 
[Page 701]
If name.ToUpper >= txtName.Text.ToUpper Then If name.ToUpper > txtName.Text.ToUpper Then Exit Do Else 'If name matches, display the age txtOutput.Text = CStr(2006 - yob) found = True End If End If Loop sr.Close() 'If name not found, then display message. If Not found Then txtOutput.Text = "Not found." End If End Sub


27.

Private Sub btnLookup_Click(...) Handles btnLookup.Click   'Lookup book title in sequential file.   Dim fileName As String   Dim title As String, quantity As Integer   'Determine file to open, and then open it for input.   If mtxtType.Text.ToUpper = "P" Then     fileName = "PAPERBACK.TXT"   Else     fileName = "HARDBACK.TXT"   End If   Dim sr As IO.StreamReader = IO.File.OpenText(fileName)   'Loop until title is found or end of file.   title = ""   Do While (title.ToUpper <> txtTitle.Text.ToUpper) And _           (sr.Peek <> -1)     title = sr.ReadLine     quantity = CInt(sr.ReadLine())   Loop   sr.Close()   'Display result.   If title.ToUpper = txtTitle.Text.ToUpper Then     txtQuantity.Text = CStr(quantity)   Else     txtQuantity.Text = "n/a"     MsgBox("Book not found in file.", 0, "NOTE")   End If End Sub


Exercises 8.2

1.

facetious

3.

A,B,C,D,E,F,G

5.

Dim sw As IO.StreamWriter Private Sub frmBaseball_Load(...) Handles MyBase.Load   sw = IO.File.CreateText("AVERAGE.TXT")   'Open for output End Sub 
[Page 702]
Private Sub btnAdd_Click(...) Handles btnAdd.Click 'Add a name with 0 times and 0 hits to the file. sw.WriteLine(txtName.Text) sw.WriteLine(0) sw.WriteLine(0) 'Reset input text boxes. txtName.Clear() txtName.Focus() End Sub Private Sub btnQuit_Click(...) Handles btnQuit.Click sw.Close() End 'Terminate the program. End Sub


7.

Dim sw As IO.StreamWriter Private Sub frmBaseball_Load(...) Handles MyBase.Load   sw = IO.File.AppendText("AVERAGE.TXT") End Sub Private Sub btnAdd_Click(...) Handles btnAdd.Click   'Add a name with 0 times and 0 hits to the file.   sw.WriteLine(txtName.Text)   sw.WriteLine(0)   sw.WriteLine(0)   'Reset input text box.   txtName.Clear()   txtName.Focus() End Sub Private Sub btnQuit_Click(...) Handles btnQuit.Click   sw.Close()   End         'Terminate the program. End Sub


9.

Private Sub btnConvert_Click(...) Handles btnConvert.Click   'Convert a sequential file in LSV format to a sequential file   'in "Comma Separated Values" (CSV) format.   Dim numFields As Integer    'Number of fields per record   numFields = CInt(txtFields.Text)   Dim field(numFields - 1) As String  'String array to hold fields   Dim sr As IO.StreamReader = IO.File.OpenText(txtLSV.Text)   Dim sw As IO.StreamWriter = IO.File.CreateText(txtCSV.Text)   'Loop over all lines in the LSV file.   Do While (sr.Peek <> -1)     'Set each field to a line from the LSV file.     For i As Integer = 0 To numFields - 1       field(i) = sr.ReadLine     Next     'Join the fields with a comma, and write to the CSV file.     sw.WriteLine(Join(field, ","))   Loop   sw.Close()   sr.Close()   MsgBox("Conversion completed.", 0, "DONE") End Sub


11.

Structure State   Dim name As String      'State name   Dim abbr As String      'Abbreviation 
[Page 703]
Dim entered As String 'Date entered union Dim area As Double 'Area in square miles Dim pop As Double 'Population in 2000 End Structure Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Load data from CSV file, sort on abbreviation, write to new file, 'and display records in list box. Dim temp As State Dim state(4) As String 'Current state data, five fields total Dim states(49) As State 'Holds all states Dim fmtStr As String = "{0,-4} {1,-17} {2,-10} {3,10:N0} {4,13:N0}" 'Read the data into the states array. Dim sr As IO.StreamReader = IO.File.OpenText("csvUSSTATES.TXT") For i As Integer = 0 To 49 state = sr.ReadLine.Split(","c) 'The field order is name, abbr, entered, area, pop. states(i).name = state(0) states(i).abbr = state(1) states(i).entered = state(2) states(i).area = CDbl(state(3)) states(i).pop = CDbl(state(4)) Next sr.Close() 'Bubble sort the array based upon abbreviation name. For i As Integer = 1 To 49 For j As Integer = 1 To 50 - i If states(j - 1).abbr > states(j).abbr Then 'Swap elements. temp = states(j - 1) states(j - 1) = states(j) states(j) = temp End If Next Next 'Write the data to the output file and to the list box. Dim sw As IO.StreamWriter = IO.File.CreateText("csvSORTED.TXT") lstOutput.Items.Add(String.Format(fmtStr, "ABBR", "STATE", _ "ENTERED", "AREA", "POPULATION")) For i As Integer = 0 To 49 'Copy data into string array. state(0) = states(i).name state(1) = states(i).abbr state(2) = states(i).entered state(3) = CStr(states(i).area) state(4) = CStr(states(i).pop) 'Join string array using commas, and write to file. sw.WriteLine(Join(state, ",")) 'Write data to list box. lstOutput.Items.Add(String.Format(fmtStr, states(i).abbr, _ states(i).name, states(i).entered, _ states(i).area, states(i).pop)) Next sw.Close() End Sub



[Page 704]
13.

Private Sub btnCreate_Click(...) Handles btnCreate.Click   'Write matching records from two input files into a third file.   Dim name, subscriber As String   'Open files for reading.   Dim srBlock As IO.StreamReader = IO.File.OpenText("BLOCK.TXT")   Dim srTimes As IO.StreamReader = IO.File.OpenText("TIMES.TXT")   Dim sw As IO.StreamWriter = IO.File.CreateText("NAMES.TXT")   'Loop over all records in the BLOCK reader.   subscriber = ""   Do While srBlock.Peek <> -1     'Read in the name from BLOCK.     name = srBlock.ReadLine     'Loop until the subscriber has been reached.     Do While (subscriber < name) And (srTimes.Peek <> -1)       'Read the next subscriber.       subscriber = srTimes.ReadLine     Loop     'If we have a match, then write it to output file.     If subscriber = name Then       sw.WriteLine(name)     End If   Loop   srBlock.Close()   srTimes.Close()   sw.Close()   MsgBox("The file has been created.", 0, "DONE") End Sub


15.

Private Sub btnCount_Click(...) Handles btnCount.Click   'Count the maximum number of repeated integers.   Dim max, lastNum, numRepeats, number As Integer   'Open data file.   Dim sr As IO.StreamReader = IO.File.OpenText("NUMBERS.TXT")   max = 0   lastNum = 0   numRepeats = 0   'Loop over all input.   Do While sr.Peek <> -1     number = CInt(sr.ReadLine)     'If number has changed, then compare its count.     If number <> lastNum Then       'If its count is more than the max, update the max.       If numRepeats > max Then         max = numRepeats       End If       'Store this number as the last number.       lastNum = number       numRepeats = 1     Else       numRepeats += 1   'Increment the count     End If   Loop   sr.Close()   txtOutput.Text = CStr(max)    'Display the result End Sub



[Page 705]
17.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Display a report on count of raffle tickets by grade.   Dim grade, gradeTotal, total As Integer   Dim currentGrade, tickets As Integer   Dim name As String   Dim fmtStr As String = "{0,5} {1,7:N0}"   'Open data file for input.   Dim sr As IO.StreamReader = IO.File.OpenText("RAFFLE.TXT")   'Reset cumulative totals.   grade = 0   gradeTotal = 0   total = 0   'Loop over all records in the file.   lstOutput.Items.Add(String.Format(fmtStr, "GRADE", "TICKETS"))   Do While sr.Peek <> -1     'Read in student's data.     currentGrade = CInt(sr.ReadLine)     name = sr.ReadLine     tickets = CInt(sr.ReadLine)     'If grade changes, then display current grade's totals.     If grade <> currentGrade Then       'If not first pass, display totals.       If grade <> 0 Then         lstOutput.Items.Add(String.Format(fmtStr, grade, gradeTotal))         'Update cumulative total.         total += gradeTotal       End If       'Reset grade.       grade = currentGrade       gradeTotal = 0     End If     'Add student's tickets to grade's total.     gradeTotal += tickets   Loop   sr.Close()   'Display last grade's totals.   lstOutput.Items.Add(String.Format(fmtStr, grade, gradeTotal))   total += gradeTotal   'Display grand total.   lstOutput.Items.Add(String.Format(fmtStr, "TOTAL", total)) End Sub


19.

Private Sub btnUpdate_Click(...) Handles btnUpdate.Click   'Update phone number master file with file of those who have moved.   Dim masterName, masterNumber As String  'Master info   Dim movedName, movedNumber As String    'Moved info   'Open input files for reading.   Dim srMaster As IO.StreamReader = IO.File.OpenText("MASTER.TXT")   Dim srMoved As IO.StreamReader = IO.File.OpenText("MOVED.TXT")   'Open temporary file to hold output.   Dim sw As IO.StreamWriter = IO.File.CreateText("TEMP.TXT")   'Loop over all records in the move input file.   Do While srMoved.Peek <> -1     'Read in name that has moved.     movedName = srMoved.ReadLine     movedNumber = srMoved.ReadLine 
[Page 706]
'Loop until find a matching record in master file. Do 'Read a name from the master file. masterName = srMaster.ReadLine masterNumber = srMaster.ReadLine If movedName = masterName Then 'If found a match, then write the new number. sw.WriteLine(masterName) sw.WriteLine(movedNumber) Else 'Otherwise, write the master number. sw.WriteLine(masterName) sw.WriteLine(masterNumber) End If Loop Until masterName = movedName Loop 'Write the rest of the master file. Do While srMaster.Peek <> -1 masterName = srMaster.ReadLine masterNumber = srMaster.ReadLine sw.WriteLine(masterName) sw.WriteLine(masterNumber) Loop srMaster.Close() srMoved.Close() sw.Close() 'Delete the old master, and rename the temporary file. IO.File.Delete("MASTER.TXT") IO.File.Move("TEMP.TXT", "MASTER.TXT") MsgBox("The file has been updated.", 0, "DONE") End Sub





An Introduction to Programming Using Visual Basic 2005
Introduction to Programming Using Visual Basic 2005, An (6th Edition)
ISBN: 0130306541
EAN: 2147483647
Year: 2006
Pages: 164

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net