Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 26

TEXT FILES

EXERCISES 8.1

Exercises 1 through 10 refer to the file Justices.txt that contains data


about the Supreme Court justices, past and present. Each record contains
SLX fieldsfirst name, last name, appointing president, home state, year
appointed, and year they left the court. (For current justices, the last field
is set to 0.) The first two lines of the file are as follows:

Samuel,Alito,George W. Bush,NJ,2006,0
Henry,Baldwin,Andrew Jackson,PA,1830,1844
In Exercises 1 through 6, determine the first two lines of the new file
created by the code.
1. Dim query = From line In IO.File.ReadAllLines("Justices.txt")
Let data = line.Split(","c)
Let firstName = data(0)
Let lastName = data(1)
Let fullName = firstName & " " & lastName
Let state = data (3)
Select fullName &","& state
IO.File.WriteAllLines("NewFile.txt", query)
Samuel Alito,NJ
Henry Baldwin,PA

2. Dim query = From line In IO.File.ReadAllLines("Justices.txt")


Let data = line.Split(","c)
Let firstName = data(0)
Let lastName = data(1)
Let fullName = (firstName & " " & lastName).ToUpper
Let yrAppointed = CInt(data(4))
Select fullName & " was appointed in " & yrAppointed & "."
IO.File.WriteAllLines("NewFile.txt", query)

SAMUEL ALITO was appointed 2006


HENRY BLADWIN was appointed 1830

3. Dim query = From line In IO.File.ReadAllLines("Justices.txt")


Let lastName = line.Split(","c)(1)
Let pres = line.Split(","c)(2)
Let presLastName = pres.Split( ,"c) .Last
Let phrase = lastName & " was appointed by " & presLastName
Select phrase

IO.File.WriteAllLines("NewFile.txt", query)
Alito was appointed by Bush
Baldwin was appointed by Jackson

4. 'Note: Today.Year is the current year


Dim query = From line In IO.File.ReadAllLines("Justices.txt")
Let lastName = line.Split(","c)(1)
Let yrAppointed = CInt(line.Split(","c)(4))
Let years = Today.Year - yrAppointed
Let phrase = lastName & " appointed " & years & " years ago"
Select phrase
IO.File.WriteAllLines("NewFile.txt", query)
Alito appointed 11 years ago
Baldwin appointed 187 years ago
5. Dim query = From line In IO.File.ReadAllLines("Justices.txt")
Let data = line.Split(","c)
Let firstName = data(0)
Let lastName = data(l)
Let yrAppointed = CInt(data(4))
Let newLine = lastName & "," & firstName & ","& yrAppointed
Select newLine
IO.File.WriteAllLines("NewFile.txt", query)
Alito,Samuel, 2006
Baldwin,Henry,1830
6. Dim query = From line In IO.File.ReadAllLines("Justices.txt")
Let data = line.Split(","c)
Let lastName = data(1)
Let pres = data(2)
Let state = data (3)
Let presLastName = pres.Split(" "c).Last
Let newLine = presLastName & "," & lastName & "," & state
Select newLine
IO.File.WriteAllLines("NewFile.txt", query)
Bush, Alito,NJ
Jackson, Henry, PA
In Exercises 7 through 10, describe the new file created by the code.
7. Dim query = From line In 10.File.ReadAllLines("Justices.txt")
Let data = line.Split(","c)
Let firstName = data(0)
Let lastName = data(1)
Let yrAppointed = CInt(data(4))
Let fullName = firstName & " " & lastName
Let newLine = fullName &"," & yrAppointed
Where lastName.StartsWith("B")
Order By yrAppointed
Select newLine
IO.File.WriteAllLines("NewFile.txt", query)
The new file contains the full names of the justices whose last name
begins with the letter B and the years they were appointed to the
court. The justices are ordered by the year they were appointed.
8. Dim query = From line In IO.File.ReadAllLines("Justices.txt")
Let data = line.Split(","c)
Let firstName = data(0)
Let lastName = data(1)
Let state = data(3)
Let yrAppointed = CInt(data(4))
Let fullName = firstName & " " & lastName
Let newLine = state & "," & fullName
Where (yrAppointed >= 1990) And (yrAppointed < 2000)
Order By state
Select newLine
IO.File.WriteAllLines("NewFile.txt", query)
The new file contains the full name of justices whom appointed
between years 1990 and 200 and the justices are ordered by the years
the were appointed
9. Dim query = From line In IO.File.ReadAllLines("Justices.txt")
Let data = line.Split(","c)
Let firstName = data(0)
Let lastName = data(1)
Let pres = data(2)
Let newLine = firstName & "," & lastName & "," & pres
Select newLine
IO.File.WriteAllLines("NewFile.txt", query)
The new file is the same as he original file, its take the three files of
records.
10. Dim query = From line In IO.File.ReadAllLines("Justices.txt")
Let data = line.Split(","c)
Let firstName = data(0)
Let lastName = data(1)
Let yrAppointed = CInt(data(4))
Let yrLeft = CInt (data (5))
Let fullName = firstName & " " & lastName
Let newLine = fullName &","& yrAppointed
Where yrLeft = 0
Order By yrAppointed
Select newLine
IO.File.WriteAllLines("NewFile.txt", query)
The new file contains the fullnames of justices with the year that they
appointed are still in appointing. The justices are ordered by they were
appointed.

In Exercises 11 through 14, describe the new file created by the code.
Assume the file NYTimes.txt contains the names of subscribers to the New
York Times and the file WSJ.txt contains the names of the subscribers to
the Wall Street Journal.

11 . Dim times() As String = IO. File . ReadAllLines ( "NYTimes . txt")


Dim wsj() As String = IO.File.ReadAllLines("WSJ.txt")
IO.File.WriteAllLines("NewFile.txt", times.Union(wsj))

The new file contains the names of the people who subscribe to either
the New York Times or the Wall Street Journal or both.
12. Dim times() As String = IO.File.ReadAllLines("NYTimes.txt")
Dim wsj() As String = IO.File.ReadAllLines("WSJ.txt")
IO.File.WriteAllLines("NewFile.txt", times.Intersect(wsj))

The new file contains the names of the people who subscribe to either
the New York Times or the Wall Street Journal or both.

13. Dim times() As String = IO.File.ReadAllLines("NYTimes.txt")


Dim wsj() As String = IO.File.ReadAllLines("WSJ.txt")
IO.File.WriteAllLines("NewFile.txt", times.Except(wsj))

The new file contains the names of the people who subscribe to the
New York Times but not the Wall Street Journal.

14. Dim times() As String = IO.File.ReadAllLines("NYTimes.txt")


Dim wsj() As String = IO.File.ReadAllLines("WSJ.txt")
Dim unionArray() As String = times.Union(wsj).ToArray
Dim intersectArray () As String = times.Intersect(wsj).ToArray
IO.File.WriteAllLines("NewFile.txt", unionArray.Except(intersectArray))

The new file contains the names of the people who subscribe (New
York Times or the Wall Street Journal) and arent (New York times and
Wall Street Journal)

In Exercises 15 through 18, use the file USPres.txt that contains the
names of all the presidents of the United States and the file VPres.txt that
contains the names of all the vice-presidents.

15. U.S. Presidents Write a program that creates a file containing the names
of every president who also served as vice-president. The program also should
display the number of those presidents in a message box.

Dim president() As String = IO.File.ReadAllLines("US pres.txt")


Dim vice() As String = IO.File.ReadAllLines("VPres.txt")
IO.File.WriteAllLines("Newfile.txt", president.Intersect(visepresident))
Dim query = from line in IO.File.ReadAllLines(Newfile.txt)
Let data =lines.splite(,c)
Let name = data(0)
Let number = name.count
messageBox.show(Cstr( the number of president & Cstr(number))

16. U.S. Presidents Write a program that creates a file containing the names of
every person who served as either vice-president or president. The program also
should display the number of those names in a message box.
Dim president() As String = IO.File.ReadAllLines("US pres.txt")
Dim vice() As String = IO.File.ReadAllLines("VPres.txt")
IO.File.WriteAllLines("Newfile.txt", president.union(visepresident))
Dim query = from line in IO.File.ReadAllLines(Newfile.txt)
Let data =lines.splite(,c)
Let name = data(0)
Let number = name.count
messageBox.show(Cstr( the number of president & Cstr(number))

17. U.S. Presidents Write a program that creates a file containing the names of
every person who served as either vice-president or president, but not both. The
program also should display the number of those names in a message box.
Dim president() As String = IO.File.ReadAllLines("US pres.txt")
Dim vice() As String = IO.File.ReadAllLines("VPres.txt")
Dim unionArray() as string = president.Union(visepresident).ToArray
Dim intersectArray() as string =
president.intersect(visepresident).ToArray
IO.File.ReadAllLines(Newfile.txt,unionArray.Except(intersectArray))
Dim query = from line in IO.File.ReadAllLines(Newfile.txt)
Let data =lines.splite(,c)
Let name = data(0)
Let number = name.count
messageBox.Show( the number of president &number)

18. U.S. Presidents Write a program that creates a file containing the names
of every president who did not also serve as vice-president. The program also
should display the number of those presidents in a message box.
Dim president() As String = IO.File.ReadAllLines("US pres.txt")
Dim vice() As String = IO.File.ReadAllLines("VPres.txt")
IO.File.WriteAllLines("Newfile.txt", president.Except(visepresident))
Dim query = from line in IO.File.ReadAllLines(Newfile.txt)
Let data =lines.splite(,c)
Let name = data(0)
Let number = name.count
messageBox.show ( the number of president & number)

In Exercises 19 through 26, write a program for the stated example or


exercise from Section 7.3 without using a structure.
19. Section 7.3, Example 2
Private Sub frmCountry_Load() Handles MyBase.Load
Dim query = From line In IO.File.ReadAllLines("UN.txt")
Let data = line.Split(","c)
Let Name = data(0)
Let continent = data(1)
Let population =CDbl (data(2))
Let area = CDbl(data(3))
End Sub
Private Sub lstContinents_SelectedIndexChanged()Handles
_lstContinents.SelectIndexChange
Dim selectedquery as String = lstContinents.Text
lstContries.Items.Clear()
if selectedquery =Antarctica then
messageBox.Shoe(There are no countries in Antarctica)
else
for I as integer = 0 to 192
if nations(i).continent = selectedContinent then
lstCountries.Items.Add(nations(i).name)
end if
next
end sub

20. Section 7.3, Example 4


Private Sub frmColleges_Load() Handles MyBase.Load
Dim query = From line In IO.File.ReadAllLines("Colleges.txt")
Let data = line.Split(","c)
Let Name = data(0)
Let state = data(1)
Let yearFounded =CInt (data(2))
Let area = CDbl(data(3))
End Sub
Private sub btnDisplay_Click() Handles btnDisplay.Click
Dim query1 = from col in query1
Where col.states = mtbStates.Text.ToUpper
Order by col.names. col.yearFounded
LstColleges.Items.Add(institution.name & & instution.yearFounded)
Next
End Sub

27. Color at the beginning of 1900, a complete box o Crayola crayon had 72 colors
(in the file Pre 1900.txt).During the 1900s ,8 colors were retried (in the files
Retired.txt) and 56 new colors were added(in the file Added.txt).Write a program
that creates a text file listing the post 1990s set of 120 in the alphabetical order.
Dim Crayola () As String = IO. File . ReadAllLines ( "Pre1900 . txt")
Dim Retired() As String = IO.File.ReadAllLines(Retired.txt")
Dim Added() As String= IO.File.ReadAllLines(Added.txt)
Dim exceptCrayola() as String = Crayola.Except(Retired).ToArray
IO.File.WriteAllLines("NewFile.txt", exceptCaryola.Union(Added))

Exercises 28 through 34 should use file justices.txt discussed at the


beginning of this exercise set.
28. Supreme Court Write a program to create a file in which each record consist
of two field-the full name of Supreme justice and the justices state.
Dim query = From line In IO.File.ReadAllLines("Justices.txt")
Let data = line.Split(","c)
Let firstName = data(0)
Let lastName = data(1)
Let fullName = firstName & " " & lastName
Let state = data (3)
Select fullName &","& state
IO.File.WriteAllLines("NewFile.txt", query)
29. Supreme Court Write a program to create a file similar to justices.txt but
with the state deleted.
Dim query = From line In IO.File.ReadAllLines("Justices.txt")
Let data = line.Split(","c)
Let firstName = data(0)
Let lastName = data(1)
Let newLine = firstName & "," & lastName
Select newLine
IO.File.WriteAllLines("NewFile.txt", query)

30. Supreme Court Write a program that display the entire contents of the file
Justices.txt in a DataGridView control. See fig 8.5

Dim query = From line In IO.File.ReadAllLines("Justices.txt")


Let data = line.Split(","c)
Let firstName = data(0)
Let secondName = data(1)
Let AppPres= data(2)
Let state= data (3)
Let yrAppointed=CIntdata(4)
Let yrLeft = CIntdata (5)
Select firstName , secondName, AppPres, state,yrAppointed, yrLeft
dgvOutput.DataSource=query.ToList
dgvOutput.CurrentCall=Nothing
dgv.Column(firstName).Header.Text=First Name
dgv.Column(SecondName).Header.Text=Second Name
dgv.Column(Apppres).Header.Text=Appointed President
dgv.Columnd(yrAppointed).Header.Text=Year Appointed
dgv.Column(yrLeft).Header.Text=Year Left
End Sub

31.Supreme Court The file USStates.txt contains information about each of 50


states.Each record contains four fileds-name,abbrevation,land area(in square
miles),population in the year 2000.The records are ordered by the states date of
entry into the union .The first four lines of file are
Delaware,DE,1954,759000
Pennsylvania,PA,44817,12296000
New Jersey,NJ,7417,8135000
Georgia,GA,57906,7637000
Write a program that creates a file constiting of the states that have not produced
any Supreme Court justices.
Dim States () As String = IO. File.ReadAllLines ( "UsSStates . txt")
For I as integer = 4 to 49
IO.File.WriteAllLines("NewFile.txt", States(i))
Next
End Sub

32.Suprem Court The first Supreme Court justice was appointed in 1789.Write a
program to create a file that lists the years from 1789 through 2012 in which no
Supreme Court justices were appointed.The first four lines of the file will be
1792,1794,1795 and 1797.
Dim query = From line In IO.File.ReadAllLines("Justices.txt")
Let data = line.Split(","c)
LettName = data(0)
Let abbrevitation = data(1)
Let Area = data(2)
Let population = CInt(data(3))
Let yrAppointed=date(4)
Where (yrAppointed >= 1789 And (yrAppointed < 2012)
For I as integer =4 to 49
IO.File.ReadAllLines(NewFile.text,States(i))

33.Supreme Court Write a program to create a file that lists the states that have
produced Supreme Court justices along with the numbe rof justices produced.The
states should be in alphabetical order by thei abbreviations.The first four lines of the
file will be AL,3;AZ,2; and return the number of justices from the state.
Dim query = From line In IO.File.ReadAllLines("Justices.txt")
Let data = line.Split(","c)
LettName = data(0)
Let abbrevitation = data(1)
Let Area = data(2)
Let population = CInt(data(3))
Let yrAppointed=date(4)
Where (yrAppointed >= 1789 And (yrAppointed < 2012)
Order by abrrevation
Select name,abvreavtion ,area, population
IO.File.ReadAllLines(NewFile.text,States(i))

35.U.S States consider the file USStates.txt described in exercises 31.Write a


program to display the entire contenst of the file in DataGridView control with the
states in alphabetical order.See fig 8.6
Dim query = From line In IO.File.ReadAllLines("Justices.txt")
Let data = line.Split(","c)
Let Name = data(0)
Let abbrevation= data(1)
Let aresa= data(2)
Let population= data (3)
Select name , abbravation, area, population
dgvOutput.DataSource=query.ToList
dgvOutput.CurrentCall=Nothing
dgv.Column(firstName).Header.Text= Name
dgv.Column(SecondName).Header.Text=Abbrevation
dgv.Column(Apppres).Header.Text=Area
dgv.Columnd(yrAppointed).Header.Text=Population
End Sub

EXERCISE 8.2

In exercises 1 through 10 determine the output displayed in the text box


when the button is clicked.
1.Private Sub ntDisplay_Click() Hanldes btnDisplay.Click
Dim salutation As string
Dim sw as IO.StreamWriter=IO.File.CreateText(Greetings.txt)
Sw.WriteLine(Hello)
Sw.WriteLine(Aloha)
Sq.Close()
Dim sr As IO.StreamReader=IO.File.OpenTExt(Greetings.txt)
Salution=sr.ReadLine
txtOutput.Text=salution
sr.Close()
End Sub
The output is : Hello

2.Private Sub ntDisplay_Click() Hanldes btnDisplay.Click


Dim salution,welcome as string
Dim sw as IO.StreamWriter=IO.File.CreateText(Greetings.txt)
Sw.WriteLine(Hello)
Sw.WriteLine(Aloha)
Sw.close()
Dim sr as IO.StreamReader=IO.File.OpenText(Greetings.Txt)
Salutoin=sr.ReadLine
Welcome = sr.ReadLine
txtOutput.text=welcome
sr.close()
End Sub

3.Private Sub ntDisplay_Click() Hanldes btnDisplay.Click
Dim salution as string
Dim sw as IO.StreamWriter=IO.File.CreateText(Greetings.txt)
Sw.WriteLine(Hello)
Sw.WriteLine(Aloha)
Sw.WriteLine(Bon Jour)
Sw.close()
Dim sr as IO.StreamReader=IO.File.OpenText(Greetings.Txt)
Do until sr.EndOfStream
Salutoin=sr.ReadLine
txtOutput.text=salution
loop
sr.close()
End Sub
Bon Jour

4.Assume that the contents of the file Greetings,txt are as shown in the figure 8.8

Hello
Aloha
Bon Jour

Private Sub ntDisplay_Click() Hanldes btnDisplay.Click


Dim file,welcome as string
File=Greetings.txt
Dim sw as IO.StreamWriter=IO.File.AppendText(file)
Sw.WriteLine(Buenos Dias)
Sw.close()
Dim sr as IO.StreamReader=IO.File.OpenText(file)
For I as integer = 1 to 4
welcome=sr.ReadLine
txtOutput.text=welcome
next
sr.close()
End Sub
The output is : Buenos dias
Hello
Aloha
Bon Jour

5.Private Sub btnDisplay_Clik() Handles btnDisplay.Click


Dim num as integer
Try
Num=CInt(txtBox.text)
Txtoutput.text=Your number is & num
Catch
txtOutput.text=You must enter a number
end try
end sub
You must enter a number.

6. Private Sub btnDisplay_Clik() Handles btnDisplay.Click


Dim nafta() as string ={Canada,United States,Mexico}
Try
txtOutput.text=The third member of NAFTA is & nafta(3)
catch exc as IndexOfRangeException
txtoutput.text=Error occurred
end try
end sub
The output is : Error occured

7.Private Sub btnDisplay_click(...)Handles btnDisplay.Click


Try
Dim usPop as integr =315000000 Approx population Of US
Dim worldPop as integer
worldPop=21*usPop
txtoutput.Text=CStr(worldPop)
Catch exc as ArgumentOutOfRangeException
txtOutput.Text=Oops
catch exc as OverflowException
txtOutput.text=Error occured
End try
End sub
Error occurred.

8.Private Sub btnDisplay_Click() Handles btnDisplay.Click


Dim flowert as string Bougainvillea,lasLetter as string
Try
lastLetter =flower.Substring(14,1)
txtOutput.Text=lastLetter
Catch exc InvalidCasException
txtOutpu.text=Oops
catch exc As aRgumentOfRangeException
txtOutput.text=Error occured
End try
End sub
The error occured
9.Assume that the file Ages.txt is located in the bin\Debug subfolder of the folder
bin and the first line of the file is Twenty-one

Private Sub btnDisplay_Click(..)Handles btnDisplasy.Click


Dim sr as IO.StreamReader
Dim age as integer
Try
Sr=IO.File.OpenText(Ages.txt) FileNotFound
Age=CInt(sr.ReadLine) InvalidCast is fails
txtOutput.text=Age is & age
catch exc as IO.FileNotException
txtOutput.Text=Files Ages.txt not found
catch exc as InvalidCastException
txtOutput.text=file Ages.text contains an invalid age
Finally
Try
Sr.close()
catch
End try
End try
End sub
File Ages.txt contains an invalid age.

10.Redo Exercise 9 with the assumption that the file Ages.txt is not located in the
bin\Debug subfolder of the folder bin
The output is :File ages.txt not found

11.Assume that the contents of the file Greetings.txt are shown in the figure
8.8(page 39)
What is the effect of the following program?
Hello
Aloha
Bon Jour

Private Sub btnDisplay_Clikc() Handles btnDisplay.Click


Dim g as string
Dim sr as IO.StreamReader=IO.file.OpenText(Greetings.text)
Dim sw as IO.StreamWriter=IO.file.CreateText(Welcome.text)
Do until sr.endOfstream
g=sr.ReadLine
If(g<>Aloha) then
Sw.Writeline(g)
End if
Loop
Sr.close()
Sw.close()
End sub
The file Welcome.txt is created and has the following lines:
Hello Bon Jour

12.Assume that the file Name.txt contains a list of names in alphabetical order.
What is the effect of the Mystery function?

Private Sub btnFind_Click() Handles btnFind.Click


MessageBox.show(CStr(Mstery(Laura)))
End sub

Function Mystery(name as string) as Boolean


Dim sr as IO.StreamReader=IO.file.OpenText(Name.txt)
Dim inputname as string
Do until sr.EndOfStream
inputName=sr.ReadLine
If inputName =name then
Return true
Elseif inputname>name then
Return false
End if
Loop
Return false
End function
If inputname is equal to name then is display the messagebox.show() with
the name that the user that is an input. If else the function return false and
then

In Exercises 13 through 18, identify any errors. Assume that the contents
of the file Greetings are as show in Fig.8.8.
13. Private Sub btnDisplay_Click(. . . ) Handles btnDisplay .Click
Dim sw As IO.StreamWriter = IO.File.Appendix(Greetings.txt)
sw.WritenLine(Gutem Tag)
sw.Close()
End Sub
The filespec Greetings . txt should be delimited with quotation marks.

14. Private Sub btnDisplay_Click(. . . ) Handles btnDisplay .Click


Dim term As String
Dim sw As IO.Streamwiter = IO.File.CreateText(Greetings.txt)
term = sw.ReadLine
txtOputput.Text = term
sw.Close()
End Sub
The IO.File.CreateText should be IO.File.OpenText
15. Private Sub btnDisplay_Click(. . . ) Handles btnDisplay .Click
Copy the content of the file Greetings .txt into the file NewGreet.txt
Dim name, greeting As string
Dim sr As IO.StreamReader = IO.File.OpenText(Greetings.txt)
name =NewGreet.txt
Dim sw As IO.StreamWriter = IO.File.CreateText(name)
Do until sr.EndOfStream
greeting = sr.ReadLine
sw.WritenLine(greeting)
Loop
sr.Close()
sw.Close()
End Sub
There should be no quotations around the variable name as the
argument to the Create- Text method.

16. Private Sub btnDisplay_Click(. . . ) Handles btnDisplay .Click
Dim sw As IO.StreamReader = IO.File.CreateText(Greetings.txt)
Greetings.txt.Close()
End Sub
The erros is in line 3th , line should be sw.close()

17. Private Sub btnDisplay_Click(. . . ) Handles btnDisplay .Click


Try
Dim age As Integer
age = CInt(InputBox(Enter your age.))
Catch
MessageBox.Show(Invalid age.)
End try
MessageBox.Show(You are & age & years old)
End Sub
The variable age is declared within the Try-Catch-Finally block.
Therefore it has block- level scope and is not available below the line
End Try.

18. Private Sub btnDisplay_Click(. . . ) Handles btnDisplay .Click


Dim sw As IO.StreamWriter
Try
sw =IO.FileCreateFile(E:\Lakes.txt)
Catch IO.IOExeption
MessageBox.Show(Is there a CD in the F: drive?)
End try
sw.Close()
End Sub
The error is in catch, IO.IO should be the last on tested
Exercises 19 through 25 are related and use the date in Table 8.2. The file
created in Exercise 19 should be use in Exercises 20 through 25.
19. Cowboys Write a program to create the text file Cowboy.txt containing the
information in Table 8.2.
Private Sub ntDisplay_Click() Hanldes btnDisplay.Click
Dim salution as string
Dim sw as IO.StreamWriter=IO.File.CreateText(Greetings.txt)
Sw.WriteLine(Colt peavmaker & & 12.2)
Sw.WriteLine(Holster& & 2.00)
Sw.WriteLine(Levi Straiss jeans& & 1.35)
Sw.WriteLine(saddle & & 40.00)
Sw.WriteLine(stetson & & 10.00)
Sw.close()
End Sub

20. Cowboys Suppose the price of saddles is reduced by 20%. Use the file
Cowboys.txt to create a file, Cowboys2.txt, containing the new price list.

21. Cowboys Write a program to add the data Winchester Rifle, 20.50 to the end
of the file Cowboys.txt

22. Cowboys Suppose an order is placed for 3 Colt Peacemakers, 2 Holsters, 10


pairs of Levi Strauss jeans, 1 Saddle, and 4 Stetsons. Write a program to perform
the following tasks:
(a) Create the file Order.txt to hold the numbers 3, 2, 10, 1, and 4.
(b) Use the file Cowbous.txt to display a sales receipt with three columns giving the
quantity, name, and cost for each item ordered. See Fig 8.9.
(c) Compute the total cost of the items and display it at the end of the sales receipt.

23. Cowboys Write a program to request an additional item and price from the
user and then create a file called Cowboy2.txt containing all the information in the
file Cowboy.txt with the additional item (and price) inserted in its proper
alphabetical sequence. See Fig.8.10. Run the program for both following data item:
Boots, 20.00 and Horse, 35.00.
24. Cowboys Write a program to allow additional items and price to be input by
the user and added to the end of the file Cowboy.txt. Include a method to terminate
the process. See Fig.8.11.

25. Cowboys Write a program using a StreamReader that displays the contents of
the file Cowboys.txt In DataGridView control. See Fig.8.12.

26. Structured Exception Handling Visual cannot delete a file that is


open. Attempting to do so generates an exception. Write a short program that
users structured exception handling to handle such a Private Sub
btnDisplay_Clikc() Handles btnDisplay.Click

Private Sub btnDisplay_Click(..)Handles btnDisplasy.Click


Dim sr as IO.StreamReader
Dim age as integer
Try
Sr=IO.File.OpenText(Ages.txt)
Age=CInt(sr.ReadLine)
txtOutput.text=Age is & age
catch exc as IO.FileNotException
txtOutput.Text=Files Ages.txt not found
catch exc as InvalidCastException
txtOutput.text=file Ages.text contains an invalid age
Finally
Try
Sr.close()
catch
End try
End try
End sub

In Exercises 27 through 32, write a program to carry out the task without
using arrays or LINQ. Assume that the file Numbers.txt contains a list of
integers.

27. Numbers Display the number of numbers in the file Number.txt.

Private Sub ntDisplay_Click() Hanldes btnDisplay.Click


Dim num As integer
Dim sr As IO.StreamReader=IO.File.OpenTExt(Number.txt)
num=sr.ReadLine
txtOutput.Text=CStr(Num.count)
sr.Close()
End Sub

28. Numbers Display the largest numbers in the file Number.txt.

Private Sub ntDisplay_Click() Hanldes btnDisplay.Click


Dim num As integer,max as integer = 0
Dim sr As IO.StreamReader=IO.File.OpenTExt(Number.txt)
num=sr.ReadLine
If (num>max)then
Max=num
txtOutput.Text=CStr(max)
sr.Close()
end if
End Sub

Or

Private Sub ntDisplay_Click() Hanldes btnDisplay.Click


Dim num As integer,max as integer = 0
Dim sr As IO.StreamReader=IO.File.OpenTExt(Number.txt)
num=sr.ReadLine
txtOutput.Text=CStr(num.max)
sr.Close()

End Sub

29. Numbers Display the smallest numbers in the file Number.txt.

Private Sub ntDisplay_Click() Hanldes btnDisplay.Click


Dim num As integer,min as integer = 0
Dim sr As IO.StreamReader=IO.File.OpenTExt(Number.txt)
num=sr.ReadLine
If (num>min)then
Max=num
txtOutput.Text=CStr(min)
sr.Close()
end if
End Sub

Or

Private Sub ntDisplay_Click() Hanldes btnDisplay.Click


Dim num As integer,max as integer = 0
Dim sr As IO.StreamReader=IO.File.OpenTExt(Number.txt)
num=sr.ReadLine
txtOutput.Text=CStr(num.min)
sr.Close()
End Sub

30. Numbers Display the sum of the numbers in the file Number.txt.

Private Sub ntDisplay_Click() Hanldes btnDisplay.Click


Dim num As integer
Dim sr As IO.StreamReader=IO.File.OpenTExt(Number.txt)
num=sr.ReadLine
txtOutput.Text=CStr(num.sum)
sr.Close()
End Sub

31. Numbers Display the average of numbers in the file Number.txt.

Private Sub ntDisplay_Click() Hanldes btnDisplay.Click


Dim num As integer
Dim sr As IO.StreamReader=IO.File.OpenTExt(Number.txt)
num=sr.ReadLine
txtOutput.Text=CStr(num.sum/num.count)
sr.Close()
End Sub

32. Numbers Display the last number in the file Number.txt.

Private Sub btnDisplay_Click() Hanldes btnDisplay.Click


Dim number as integer
Dim sw as IO.StreamWriter=IO.File.CreateText(Number.txt)
Do until sr.EndOfStream
number=sr.ReadLine
txtOutput.text=CStr(number)
loop
sr.close()
End Sub
EXERCISES 8.3
In Exercise 1 through 6, determine if the name is proper name for an
element of an XML file.

1. 7up
No
2. vice president
yes
3. _77
No
4. Fred
Yes
5. xmlTitle
No
6. ?mark
No

In Exercises 7 through 10 , determine if the expression is a proper


element.
7.<begin>Hello</end>
No
8.<Team>Oakland Raiders</team>
No

9.<city>New York<city>
No
10.<first name>John</first name>
No
11. U.S. Presidents The first two lines of the file AgeAtlnaug.txt.are
George Washington ,57
John Adam, 61
Where each second has two fieldsname of president and his age when
inaafurated. Create a XML file containing these two records.
<?xml version=1.0>
<age_inaguration>
<president>
<name>George Washington</name>
<age>57</age>
</president>
<president>
<name>John Adam</name>
<age>61</age>
</president>
</age_inaguration>

12.Supreme Court The first two lines of the file Justice.txt are
Samuel,alitp,George M. Bush, NJ, 2006,0
Henry,Baldwin,Andrew Jackson,Pa, 1830,1844

Where each record has six fieldsfirst name, last name, appointing president, the
state from which the justice was appointed, year appointed, and year they left the
court. (For current justices, the last field is set to 0.).Create an XML file containing
these two records.
<?xml version=1.0>
<supremeCourt>
<Justice>
<firstname>Samuel</firstname>
<lastname>Alito</lastname>
<AppPres>George M. Bush</AppPres>
<state>NJ</state>
<yrappointed>2006</yrappointed>
</justice>
<Justice>
<firstname>Henry</firstname>
<lastname>Baldwin</lastname>
<AppPres> Adrew Jackson</AppPres>
<state>Pam</state>
<yrappointed>1830</yrappointed>
</justice>
</supremeCourt>

In Exercises 13 through 20, write a program to extract and display the


requested information from the file USStates.xml

13. U.S. States The total population of the \united States in the year 2000.
Private Sub btnField_Click() Handles btnFind.Click
Dim stateData as XElement = XElement.Load(USStates.xml)
Dim query = From st in StateDate.Descendants(state)
Let name = st.<name>.Value
Let pop = st.CInt(st.<population>.Value)
Let year = CInt(st.<year>.Value)
Where year = 2000
Select pop
End Sub

14. U.S. States The total area of the United States.


Private Sub btnField_Click() Handles btnFind.Click
Dim stateData as XElement = XElement.Load(USStates.xml)
Dim query = From st in StateDate.Descendants(state)
Let name = st.<name>.Value
Let pop = st.CInt(st.<population>.Value)
Let year = CInt(st.<year>.Value)
Let area =CInt(st.<area>.Value)
Select area
End Sub

15. U.S States The population density of the United States.


Private Sub btnField_Click() Handles btnFind.Click
Dim stateData as XElement = XElement.Load(USStates.xml)
Dim query = From st in StateDate.Descendants(state)
Let name = st.<name>.Value
Let pop = st.CInt(st.<population>.Value)
Let year = CInt(st.<year>.Value)
Let area =CInt(st.<area>.Value)
Let density = pop / area
Let formattedDensity = density.Tostring(N)
Select formattedDensity
End Sub

16. U.S States The state(or states) with the longest name.
Private Sub btnField_Click() Handles btnFind.Click
Dim stateData as XElement = XElement.Load(USStates.xml)
Dim query = From st in StateDate.Descendants(state)
Dim m as integer
Let name = st.<name>.Value
For I as integer = 0 to 49
If (m<name.length))
Select m.max
End Sub

17. U.S States The states with area greater than 100,000 square miles.
Display both the name and area of each states, with the state in decreasing order
by area. See Fig. 8.13.

Private Sub btnField_Click() Handles btnFind.Click


Dim stateData as XElement = XElement.Load(USStates.xml)
Dim query = From st in StateDate.Descendants(state)
Let name = st.<name>.Value
Let area =CInt(st.<area>.Value)
Order by area descending
Where area>1000000
Select namearea
dgvStates.DataSource = query.Tolist
dgv.States.CurrentCell = Nothing
dgv.Columns(name).HeaderText = State
dgv.Columns(Area).HeaderText= Area
End Sub

18. U.S States The states with population less than one million.
Display both the name and population of each state, with the states in
increasing order by population. See Fig. 8.14.
Private Sub btnField_Click() Handles btnFind.Click
Dim stateData as XElement = XElement.Load(USStates.xml)
Dim query = From st in StateDate.Descendants(state)
Let name = st.<name>.Value
Let pop =CInt(st.<area>.Value)
Order by pop ascending
Where pop<1000000
Select namearea
dgvStates.DataSource = query.Tolist
dgv.States.CurrentCell = Nothing
dgv.Columns(name).HeaderText = State
dgv.Columns(pop).HeaderText= pop
End Sub

19. U.S States The states whose name contain the most different
vowels. See Fig. 8.15.

Private Sub btnDisplay_Click()Handles btnDisplay.click


Dim stateData as XElement=XElement.Load(USSStates.xml)
Dim query =from st in stateData.Descendants(state)
Let name=st.<name>.value
Let abrevation=st.<abbreviation>.value
For I as integer = 0 to 49
If
(name=A)or(name =E) or( name =I) or( name = O) or (name
=U)
Select name
lstOutput.Items.Add(state,abbreviation)
End If
Next
End Sub

20. U.S States The states whose abbreviations are different than the
first two letters of their names. Display both the name and abbreviation of
each state in alphabetical order by the abbreviation. See Fig. 8.16.

Private Sub btnDisplay_Click () Handles btnDisplay.Click


Private Sub btnDisplay_Cilck(. . .) Handles btnDisplay.click
Dim stateDate As XElement = XElement.Load(USStates.xml)
Dim query = From st in stateDate.Descendants(state)
Let name = st.<name>.Value
Where name.substring(0,1)<>name.substring(1,2)
Select name
lstOutput.Items.Add(name)
End sub

21. Colleges Write a program that displays the colleges alphabetical


ordered (along with their year founded) that are in the state specified in a
masked text box. See Fig.8.18.

Dim college as XElement = XElement.Load (College)


Private Sub btnFind_Click() Handles btnFind.Click
Dim query = from cg in college.Descendants(College)
Let name = cg.<name>.Value
Let state = cg.<state>.Value
Let yearFounded= cg.<yearfounded>.Value
Order by name ascending
Where state = mtbstate.Text.ToUpper
Select name
End sub
22. Colleges Write a program that provides information about a
college selected from a list box by the user. The colleges should be displayed
in alphabetical order. See Fig. 8.19.
Dim college as XElement = XElement.Load (College)
Private Sub btnFind_Click() Handles btnFind.Click
Dim query = from cg in college.Descendants(College)
Let name = cg.<name>.Value
Let state = cg.<state>.Value
Let yearFounded= cg.<yearfounded>.Value
Order by name ascending
Where state = lstState.Selected
Select name,yearFounded
txtState.Text = state
txtYear.Text=yearFounded
End sub

23. Colleges Write a program that fills a list box with the years
before 1800 in which colleges were founded. When the user selects a year,
the colleges founded that year should be displayed in another list box. See
Fig. 8.20.

Dim collegeDate as XElement = XElement.Load(Colleges.xml)


Private Sub btnDisplay_Click(. . . ) Handles btnDisplay.Click
Dim query = From cg In collegeData.Descendants(college)
Let name =cg.<name>.value
Let state =cg.<state>.value
Let yearFounded =cg.<yearFounded>.value
Order by name ascending
Where yearFounded<1800
Select yearFounded
lstBox1.Items.Add(CStr(yearFounded))
Dim query1 = From cg In collegeData.Descendants(college)
Let name =cg.<name>.value
Let state =cg.<state>.value
Let yearFounded =cg.<yearFounded>.value
Order by name ascending
Where yearFounded.selected<1800
Select name
lstBox2.Items.Add(name)
End Sub
24. Colleges Write a program that displays the colleges and their
states in a DataGridView control when the colleges are alphabetical ordered
by their state abbreviations and secondarily by the year they were founded.
See Fig. 8.21.
Dim college as XElement = XElement.Load (College)
Private Sub btnFind_Click() Handles btnFind.Click
Dim query = from cg in college.Descendants(College)
Let name = cg.<name>.Value
Let state = cg.<state>.Value
Let yearFounded = =cg.<yearFounded>.value
Order by state, yearFounded
Select name.state
dgvStates.DataSource =query.Tolist
dgv.States.CurrentCell = Nothing
dgv.Columns(name).HeaderText = College
dgv.Columns(pop).HeaderText= State
End sub

25. U.S. States The CSV file Senate113.txt contains a record for each
member of the 113 U.S. Senate. (the 113th U.S. Senate was installed in
th

2013.) Each record contains three fields name, state, and party affiliation.
Some records in the files are
John McCain, Arizona, R
Bernie Sanders, Vermont, I
Kirsten Gillibrand, New York, D
(a) Write a program that uses the file Senate113.txt and creates an
XML file containing the same information
<?xml version=1.0>
<Senate113>
<Senate>
<name>John McCain</firstname>
<state>Arizona</state>
<partyaffiliation>R</partyaffiliation >
</Senate>
<Senate>
<name>Bernie Sanders </firstname>
<state>Vermont</state>
<partyaffiliation>I</partyaffiliation >
</Senate>
<Senate>
<name>Kristen Gillibrand </firstname>
<state>New Yorl</state>
<partyaffiliation>D</partyaffiliation >
</Senate>
</Senate113>
(b) Write a program that uses the XML file from part (a) to display
the names, states, and party affiliation of all the senators in a
DataGridView orderd by their state. See Fig. 8.22. The two senators
from each state should be ordered by their first names.
(c) Dim college as XElement = XElement.Load (senate)
Private Sub btnFind_Click() Handles btnFind.Click
Dim query = from cg in senate.Descendants(senate)
Let name = cg.<name>.Value
Let state = cg.<state>.Value
Let partyaffilation = cg.<partyaliffation>.values
Select name,state, yearaliffation
dgvStates.DataSource =query.Tolist
dgv.States.CurrentCell = Nothing
dgv.Columns(name).HeaderText = College
dgv.Columns(state).HeaderText= State
dgv.Columns(partyaliffation).HeaderText= Partyaliffation

End sub

26. Baseball The file Top23HR.xml contains statistics for the top
25 home-run hitters of all time in major league baseball. The first nine lines
of the file are shown in Fig. 8.23.
(a) Write a program that displays the contents of this files in a DataGridView
contron in descending order by the number of home runs hit. See Fig.8.24.
(b) Write a program that uses the file Top25HR.xnl and creates a CSV file
containing the same information.

You might also like