Skip to main content

SOLUTIONS MANUAL For An Introduction to Programming Using Visual Basic 2012, 9th Edition by David I.

Page 1

Instructor Solutions Manual (Page 4 of 221)

CHAPTER 2 EXERCISES 2.2 1. While the mouse is still hovering over the button that was just clicked, the button has a pale blue color. 2. Tabbing to another control, clicking on another control, or pressing Alt plus the access key for another control. 3. Click on the form to make it the selected object. Click on the Properties window or Press F4 to activate the Properties window. Select the Text property. Type "CHECKING ACCOUNT" and press the Enter key. 4. Double-click the TextBox icon in the Toolbox. Activate the Properties window, and select the ForeColor property. Click on the down-arrow button to the right of the Settings box. Click on the Custom tab. Click on the desired blue in the palette. Move around the Properties window with the up- and down-arrow keys until the Text property is selected. Click on the Settings box and then type "PLAY IT, SAM" (without the quotes). Click on the text box and then widen it slightly to see the words. 5. Double-click the TextBox icon in the Toolbox. Activate the Properties window. Select the BackColor property. Click on the down-arrow to the right of the Settings box. Click on the Custom tab, and then click on the desired yellow in the palette. Click on the form to see the empty yellow text box. 6. Double-click on the TextBox icon in the Toolbox. Activate the Properties window, and select the Name property. Type "txtGreeting". (The name will appear in the Settings box.) Select the Text property. Type the requested word, "HELLO". Select the Font property. Click on the ellipsis to the right of the Settings box. Click on the Size box. To increase the size of the word, either type the number for the font size (such as "14") or click on a number in the list below the current size. Click on Italic in the "Font style" list. Click OK. If necessary, widen the text box.


Instructor Solutions Manual (Page 5 of 221)

7. Double-click on the Label icon in the Toolbox. Activate the Properties window, and select the AutoSize property. Set the AutoSize property to False. Select the Text property and type the requested sentence.

Select the TextAlign property. Click on the down-arrow button to the right of the Settings box, and click on one of the center rectangles. Resize the label so that the sentence occupies three lines. 8. Double-click on the TextBox icon in the Toolbox. Activate the Properties window, and select the Text property. Type "Visual Basic" and then press the Enter key. If the text isn't all visible, drag the text box's right sizing handle to the right until all the text can be seen. Select the ReadOnly property. Double-click on the ReadOnly property to change it's setting to True. (Or, go to the Settings box, press the down-arrow button, and click on True.) Select the Font property. Click on the ellipsis to the right of the Settings box. In the Font style box, click on Bold. Click OK. Select the BackColor property and click on the down-arrow button. Click on the Custom tab. Click on the desired red in the palette. Select the ForeColor property and click on the down-arrow button. Click on the Custom tab. Click on the white square in the upper-left corner of the palette. 9. Double-click on the TextBox icon in the Toolbox. Activate the Properties window. Set the Name property to txtLanguage. Select the Text property and type "Visual Basic 2012". Select the Font property and click on the ellipsis to the right of the Settings box. Scroll up the Font list box, and click on Courier New in the Font box. Click OK. Widen the text box to accommodate its text. 10. Double-click on the Button icon in the Toolbox. Activate the Properties window, and select the Text property. Type "PUSH". Select the BackColor property and click on the down-arrow button. Click on the Custom tab. Click on the yellow square (the third square in the fourth column) in the palette. Double-click on the setting for the (Name) property, type in "btnPush", and press the Enter key.


Instructor Solutions Manual (Page 6 of 221)

11. Double-click on the Button icon in the Toolbox. Activate the Properties window, and select the BackColor property. Click on the down-arrow button to the right of the Settings box. Click on the Custom tab, and then click on the white square in upper-left corner of the palette. Select the Text property and type "PUSH". Select the Font property, and click on the ellipsis. Click on Italic (with Windows Vista) or Oblique (with Windows 7 & 8) in the "Font style" list. Click on 24 in the Size box and click OK. Resize the button. 12. Double-click on the Button icon in the Toolbox. Activate the Properties window, and select the Text property. Type "&PUSH". Select the Font property and click on the ellipsis. Click on Bold in the "Font Style" box. Click OK. Click on the form to see the resulting button. 13. Double-click on the Button icon in the Toolbox. Activate the Properties window. Select the Text property and type "PUS&H". Click on the form to see the resulting button. 14. Double-click on the Label icon in the Toolbox. Activate the Properties window, and select the Text property. Type "ALIAS". Select the ForeColor property and click on the down-arrow button. Click on the Custom tab. Click on the desired white in the palette. Select the BackColor property and click on the down-arrow button. Click on the Custom tab. Click on the desired shade of blue in the palette. Click on the form to see the resulting label.


Instructor Solutions Manual (Page 7 of 221)

15. Double-click on the Label icon in the Toolbox. Activate the Properties window. Select the Name property and type "lblAKA". Select the Text property and type "ALIAS". Select the AutoSize property and set it to False. Select the Font property and click on the ellipsis. Click on Italic (with Windows Vista) or Oblique (with Windows 7 & 8) in the "Font style" list. Click OK. Select the TextAlign property, click on the down-arrow box to the right of the Settings box, and click on one of the center rectangles. 16. Click on the form to make it the selected object. Activate the Properties window, and select the Text property. Type "BALANCE SHEET". Select the BackColor property and click on the down-arrow button. Click on the Custom tab. Click on the desired shade of yellow in the palette. 17. Double-click on the Label icon in the Toolbox. Activate the Properties window, and select the TextAlign property. Click on the down-arrow box to the right of the Settings box, and click on one of the rectangles on the right. Select the AutoSize property and set it to False. Select the Text property, type "VISUAL BASIC", and press Enter. If the words " VISUAL BASIC " are on one line, resize the label until the words occupy two lines. 18. In the Solution Explorer, right-click on the file Form1.vb. Select “Rename” from the drop-down list. Change the filename from Form1.vb to frmHello.vb. In the Properties window, change the setting of the Text property from Form1 to Hello World. 19. Double-click on the Label icon in the Toolbox. Activate the Properties window and set the Text property of the label to PROGRAM. Select the Font property, and click on the ellipsis to the right of its Settings box. Click on Italic (with Windows Vista) or Oblique (with Windows 7 & 8) in the "Font style" list, and click on the Underline box. Click on the OK button.


Instructor Solutions Manual (Page 8 of 221)

20. Double-click on the Label icon in the Toolbox. Activate the Properties window, and select the Text property. Type "ALIAS". Select the Font property and click on the ellipsis. Click on Bold in the Font style box. Click on Courier New in the Font box and press OK. Click on the form to see the resulting label. 21. Double-click on the ListBox icon in the Toolbox. Activate the Properties window, and select the BackColor property. Click on the down-arrow button to the right of the Settings box. Click on the Custom tab and click on the desired yellow square in the palette. Click on the form. 22. Double-click on the ListBox icon in the Toolbox. Activate the Properties window, and select the Visible property. Double-click on the Visible property to change it's setting to False. (Or, go to the Settings box, press the down-arrow button, and click on False.) 23. In the Solution Explorer window, right click on “Form1.vb” and select Rename from the context menu that appears. Change Form1.vb to frmYellow.vb. Right-click on the form in the Form Designer, and select Properties from the context menu. Click on BackColor property in the Properties window. Click on the down-arrow button in the right part of the Settings box, click on the Custom tab, and click on a yellow square. 24. Double-click on the Button icon in the Toolbox. Activate the Properties window and set the Text property of the button to BUTTON. Select the Font property, and click on the ellipsis to the right of its Settings box. Click on Bold in the "Font style" list. Place a check mark in the small square to the left of the word "Underline" by clicking on the square. Click on the OK button. 25. Begin a new program. Change the text in the form's title bar to "Dynamic Duo". Place two buttons on the form. Position and resize the buttons as shown. Enter “Batman” as the text of the first button, and enter “Robin” as the text of the second button. Increase the font size for both buttons to 14.


Instructor Solutions Manual (Page 9 of 221)

26. Begin a new program. Change the text in the form's title bar to "Enter Names". Place on the form a label, a text box, and a button in the sizes and locations shown. Change the text on the label to "Name". Change the text on the button to "Enter". Increase the Font size for the label and the button to 12. 27. Begin a new program. Change the text in the form's title bar to "Fill the Blank". Place a label, a text box, and another label on the form at appropriate locations. Change the Text setting of the first label to "I’m the king of the" and the Text setting of the second label to "A Quote by Leonardo DiCaprio". 28. Begin a new program. Change the text in the form's title bar to "Similarity". Place a big label and a normal-sized label on the form. Move the small label to the bottom of the form, and move and resize the big label so that it covers most of the top of the form. Select the normal-sized label. Change the setting of the Text property to "A Quote". Select the big label. Change the setting of the Text property to the specified sentence. Increase the font size to 12. Resize and position the labels as needed. 29. Begin a new program. Change the text in the form's title bar to "Uncle's Advice". Place five labels and three buttons on the form at appropriate locations. Change the Text setting of each label as indicated. Change the settings of the buttons' Text properties to "1", "2", and "3". Resize and position the labels and buttons. 30. Begin a new program. Change the text in the form's title bar "3 Rectangles". Place a label on the form and increase its size to provide plenty of space. Change the background color to red. Place a smaller label inside the red label. Change its background color to some shade of white. Finally, place a yet smaller label inside the white box. Change its background color to blue. Resize and position the labels as needed. 33. 1

34. 0

35. Each arrow key moves the text box in the indicated direction.


Instructor Solutions Manual (Page 10 of 221)

36. Pressing the right- and left-arrow keys widen and narrow the text box. The up- and downarrow keys have no effect. 37. Pressing the right and left arrow keys widens and narrows the text boxes, buttons, and list boxes in the group of selected controls. The up and down arrow keys shorten and lengthen the buttons and list boxes in the group. The arrow keys have no effect on the labels, and only the left and right arrow keys affect the text boxes. 38. Each arrow key moves every control in the group in the indicated direction. 39. Drag a label and a list box onto the form. Click on the label. Hold down the Ctrl key and click on the list box. (You have now selected a group of two controls.) In the Properties window, click on the symbol to the left of the Font property. Click on the Size property, change the setting to 12, and press the Enter key. (Alternative: Replace the last three lines with the following steps.) In the Properties window, select the Font property. Click on the ellipsis button to the right of the Settings box. Click on 12 in the Size list and click on the OK button. 40. The button moves to a comfortable distance from one of the sides of the form. 41. The label is positioned just to the left of the text box, and the middles of the two controls are aligned. 42. The left sides of the buttons are aligned and the two buttons are a comfortable distance apart. 43. Center refers to the midpoint horizontally, whereas middle refers to the midpoint vertically. 44. Select the four buttons as a group. Click on the Format menu, click on Make Same Size, and then click on Both. Click on the Format menu again, click on Vertical Spacing, and then click on Make Equal. 45. First blue snap line: tops of the two controls are aligned Purple snap line: texts of the two controls are aligned Second blue snap line: bottoms of the two controls are aligned 46. The setting toggles between True and False. 47. The setting is cycling through the different available colors.


Instructor Solutions Manual (Page 11 of 221)

EXERCISES 2.3 1. The word Hello 2. The word Hello in red letters 3. The word Hello on an orange-colored background 4. The word Hello 5. The text box vanishes. 6. The word Hello on a yellow background 7. The word Hello in green letters 8. The word Hello on a white background 9. The word Hello on a gold background. 10. Nothing, the label cannot be seen. 11. Form1.Text should be Me.Text. 12. The word Hello must be surrounded with quotation marks. 13. Red should be replaced with Color.Red. 14. Replace txtBox with txtBox.Text. 15. Font.Size is a read-only property. The statement txtOutput.Text = txtBox.Font.Size is valid since it is reading the value of txtBox.Font.Size. However, txtBox.Font.Size = 20 is not valid since it is setting the value of txtBox.Font.Size. 16. Me.Color must be replaced by Me.ForeColor or Me.BackColor 17. lblTwo.Text = "E.T. phone home." 18. lblTwo.Text = "Play it, Sam." 19. txtBox.ForeColor = Color.Red txtBox.Text = "The stuff that dreams are made of." 20. txtBox.ForeColor = Color.Blue txtBox.BackColor = Color.Gold txtBox.Text = "Life is like a box of chocolates." 21. txtBox.Enabled = False


Instructor Solutions Manual (Page 12 of 221)

22. Me.Text = "Hello World" 23. lblTwo.Visible = False 24. lblName.ForeColor = Color.Red

25. btnOutcome.Enabled = True 26. btnCompute.Focus()

27. txtBoxTwo.Focus() 28. Me.BackColor = Color.White

29. The Enter event occurs when a control gets the focus. 30. A control's Leave event occurs when the control loses the focus. 31. Private Sub Label1_Click(...) Handles Label1.Click lstOutput.Items.Add("Click") End Sub Private Sub Label1_DoubleClick(...) Handles Label1.DoubleClick lstOutput.Items.Add("Double Click") End Sub

Whenever the DoubleClick event is raised, the Click event is also raised. 32. Private Sub Button1_Click(...) Handles Button1.Click lstOutput.Items.Add("Click") End Sub 33. Private Sub btnLeft_Click(...) Handles btnLeft.Click txtBox.Text = "Left Justify" txtBox.TextAlign = HorizontalAlignment.Left End Sub Private Sub btnCenter_Click(...) Handles btnCenter.Click txtBox.Text = "Center" txtBox.TextAlign = HorizontalAlignment.Center End Sub Private Sub btnRight_Click(...) Handles btnRight.Click txtBox.Text = "Right Justify" txtBox.TextAlign = HorizontalAlignment.Right End Sub 34. Private Sub btnSmile_Click(...) Handles btnSmile.Click lblFace.Text = ":-)" End Sub Private Sub btnFrown_Click(...) Handles btnFrown.Click lblFace.Text = ":-("


Instructor Solutions Manual (Page 13 of 221) End Sub 35. Private Sub btnRed_Click(...) Handles btnRed.Click txtBox.BackColor = Color.Red End Sub Private Sub btnBlue_Click(...) Handles btnBlue.Click txtBox.BackColor = Color.Blue End Sub Private Sub btnWhite_Click(...) Handles btnWhite.Click txtBox.ForeColor = Color.White End Sub Private Sub btnYellow_Click(...) Handles btnYellow.Click txtBox.ForeColor = Color.Yellow End Sub 36. Private Sub txtOne_Enter(...) Handles txtOne.Enter txtOne.ForeColor = Color.Red txtTwo.ForeColor = Color.Black txtThree.ForeColor = Color.Black End Sub Private Sub txtTwo_Enter(...) Handles txtTwo.Enter txtOne.ForeColor = Color.Black txtTwo.ForeColor = Color.Red txtThree.ForeColor = Color.Black End Sub Private Sub txtThree_Enter(...) Handles txtThree.Enter txtOne.ForeColor = Color.Black txtTwo.ForeColor = Color.Black txtThree.ForeColor = Color.Red End Sub Private Sub btnLeft_Click(...) Handles btnLeft.Click txtOne.TextAlign = HorizontalAlignment.Left txtTwo.TextAlign = HorizontalAlignment.Left txtThree.TextAlign = HorizontalAlignment.Left End Sub Private Sub btnRight_Click(...) Handles btnRight.Click txtOne.TextAlign = HorizontalAlignment.Right txtTwo.TextAlign = HorizontalAlignment.Right txtThree.TextAlign = HorizontalAlignment.Right End Sub 37. Private Sub txtLife_Enter(...) Handles txtLife.Enter txtQuote.Text = "I like life, it's something to do." End Sub Private Sub txtFuture_Enter(...) Handles txtFuture.Enter txtQuote.Text = "The future isn't what it used to be." End Sub


Instructor Solutions Manual (Page 14 of 221) Private Sub txtTruth_Enter(...) Handles txtTruth.Enter txtQuote.Text = "Tell the truth and run." End Sub 38. Private Sub btnDisable_Click(...) Handles btnDisable.Click txtBox.Enabled = False End Sub Private Sub btnEnable_Click(...) Handles btnEnable.Click txtBox.Enabled = True txtBox.Focus() End Sub 39. Private Sub btnOne_Click(...) Handles btnOne.Click btnOne.Visible = False btnTwo.Visible = True btnThree.Visible = True btnFour.Visible = True End Sub Private Sub btnTwo_Click(...) Handles btnTwo.Click btnOne.Visible = True btnTwo.Visible = False btnThree.Visible = True btnFour.Visible = True End Sub Private Sub btnThree_Click(...) Handles btnThree.Click btnOne.Visible = True btnTwo.Visible = True btnThree.Visible = False btnFour.Visible = True End Sub Private Sub btnFour_Click(...) Handles btnFour.Click btnOne.Visible = True btnTwo.Visible = True btnThree.Visible = True btnFour.Visible = False End Sub


Instructor Solutions Manual (Page 15 of 221) 40. Private Sub txtGreen_Enter(...) Handles txtGreen.Enter txtGreen.BackColor = Color.Green txtYellow.BackColor = Color.DarkGray txtRed.BackColor = Color.DarkGray End Sub Private Sub txtYellow_Enter(...) Handles txtYellow.Enter txtGreen.BackColor = Color.DarkGray txtYellow.BackColor = Color.Yellow txtRed.BackColor = Color.DarkGray End Sub Private Sub txtRed_Enter(...) Handles txtRed.Enter txtGreen.BackColor = Color.DarkGray txtYellow.BackColor = Color.DarkGray txtRed.BackColor = Color.Red End Sub 41. Private Sub btnVanish_Click(...) Handles btnVanish.Click lblFace.Visible = False End Sub Private Sub btnReappear_Click(...) Handles btnReappear.Click lblFace.Visible = True End Sub 42. Private Sub txtName_Enter(...) Handles txtName.Enter lblInstructions.Text = "Enter your full name." End Sub Private Sub txtPhone_Enter(...) Handles txtPhone.Enter lblInstructions.Text = "Enter your phone number, including area code." End Sub 43. Private Sub btnAny_Click(...) Handles btnOne.Click, btnTwo.Click txtOutput.Text = "You just clicked on a button." End Sub 44. Private Sub txtBox1_Click(...) Handles txtBox1.Click txtBox2.Text = txtBox1.Text txtBox1.Clear() End Sub Private Sub txtBox2_Click(...) Handles txtBox2.Click txtBox1.Text = txtBox2.Text txtBox2.Clear() End Sub


Instructor Solutions Manual (Page 4 of 196) CHAPTER 8 EXERCISES 8.1 1. Samuel Alito,NJ Henry Baldwin,PA

2. SAMUEL ALITO was appointed in 2006. HENRY BALDWIN was appointed in 1830.

3. Alito was appointed by Bush Baldwin was appointed by Jackson 4. (In 2013 output will be as follows.) Alito appointed 7 years ago Baldwin appointed 183 years ago 5. Alito,Samuel,2006 Baldwin,Henry,1830 6. Bush,Alito,NJ Jackson,Baldwin,PA

7. 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. The new file contains the states and the full names of the justices appointed during the 1990s. The justices are ordered by their states. 9. The new file is the same as the original file except that the last three fields have been deleted from each record. 10. The new file contains the full names of the current justices and the years they were appointed. The records are ordered by the year appointed. (Note: The file represents the makeup of the court in January 2013.) 11. 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. The new file contains the names of the people who subscribe to both the New York Times and the Wall Street Journal. 13. The new file contains the names of the people who subscribe to the New York Times but not the Wall Street Journal. 14. The new file contains the names of the people who subscribe to either the New York Times or the Wall Street Journal, but not both.


Instructor Solutions Manual (Page 5 of 196) 15. Private Sub btnBoth_Click(...) Handles btnBoth.Click 'Create a file of presidents who were also vice presidents Dim vicePres() As String = IO.File.ReadAllLines("VPres.txt") Dim presidents() As String = IO.File.ReadAllLines("USPres.txt") Dim both() As String = presidents.Intersect(vicePres).ToArray IO.File.WriteAllLines("Both.txt", both) MessageBox.Show(both.Count & " presidents", "File Created") End Sub

16. Private Sub btnOr_Click(...) Handles btnOr.Click 'Create a combined list of presidents and vice presidents Dim vicePres() As String = IO.File.ReadAllLines("VPres.txt") Dim presidents() As String = IO.File.ReadAllLines("USPres.txt") Dim eitherOr() As String = presidents.Union(vicePres).ToArray IO.File.WriteAllLines("Or.txt", eitherOr) MessageBox.Show(eitherOr.Count & " people", "File Created") End Sub 17. Private Sub btnXor_Click(...) Handles btnXor.Click 'Create a file of people who were pres or VP but not both Dim vicePres() As String = IO.File.ReadAllLines("VPres.txt") Dim presidents() As String = IO.File.ReadAllLines("USPres.txt") Dim eitherOr() As String = presidents.Union(vicePres).ToArray Dim both() As String = presidents.Intersect(vicePres).ToArray Dim exclusiveOr() As String = eitherOr.Except(both).ToArray IO.File.WriteAllLines("Xor.txt", exclusiveOr) MessageBox.Show(exclusiveOr.Count & " presidents or vice presidents, but not both", "File Created") End Sub

18. Private Sub btnNotVP_Click(...) Handles btnNotVP.Click 'Create a file of presidents who were not vice-presidents Dim vicePres() As String = IO.File.ReadAllLines("VPres.txt") Dim presidents() As String = IO.File.ReadAllLines("USPres.txt") Dim presOnly() As String = presidents.Except(vicePres).ToArray IO.File.WriteAllLines("NotVP.txt", presOnly) MessageBox.Show(presOnly.Count & " presidents were not vice presidents", "File Created") End Sub


Instructor Solutions Manual (Page 6 of 196) 19. Dim countries() As String = IO.File.ReadAllLines("UN.txt") 'lstContinents was filled at design time Private Sub lstContinents_SelectedIndexChanged(...) Handles _ lstContinents.SelectedIndexChanged Dim selectedContinent As String = lstContinents.Text If (selectedContinent = "Antarctica") Then lstCountries.DataSource = Nothing MessageBox.Show("There are no countries in Antarctica.") Else Dim query = From nation In countries Let data = nation.Split(","c) Let name = data(0) Let continent = data(1) Where continent = selectedContinent Select name lstCountries.DataSource = query.ToList lstCountries.SelectedItem = Nothing End If End Sub

20. Dim colleges() As String = IO.File.ReadAllLines("Colleges.txt") Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display the colleges in Colleges.txt located in the given state Dim chosenState As String = mtbState.Text.ToUpper Dim query = From col In colleges Let data = col.Split(","c) Let name = data(0) Let state = data(1) Let yearFounded = data(2) Where state = chosenState Order By name Ascending Select name, yearFounded lstColleges.Items.Clear() For Each institution In query lstColleges.Items.Add(institution.name & " " & institution.yearFounded) Next End Sub


Instructor Solutions Manual (Page 7 of 196) 21. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim cities() As String = IO.File.ReadAllLines("Cities.txt") Dim query = From city In cities Let data = city.Split(","c) Let pop2010 = CDbl(data(3)) Order By pop2010 Descending Select pop2010 Dim pops() As Double = query.ToArray ReDim Preserve pops(9) txtOutput.Text = (100000 * pops.Sum).ToString("N0") End Sub

22. Dim states() As String = IO.File.ReadAllLines("USStates.txt") Private Sub btnFind_Click(...) Handles btnFind.Click Dim query = From line In states Let data = line.Split(","c) Let name = data(0) Let abbrev = data(1) Let area = data(2) Where abbrev = mtbAbbrev.Text.ToUpper Select name, area txtOutput.Text = "The area of " & query.First.name & " is " & (CDbl(query.First.area)).ToString("N0") & " square miles." End Sub


Instructor Solutions Manual (Page 8 of 196) 23. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim states() As String = IO.File.ReadAllLines("USStates.txt") Dim query = From line In states Let name = line.Split(","c)(0).ToUpper Let abbrev = line.Split(","c)(1) Where Not name.StartsWith(abbrev) Order By name Ascending Select abbrev, name dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("abbrev").HeaderText = "State Abbreviation" dgvOutput.Columns("name").HeaderText = "State" End Sub

24. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim usStates() As String = IO.File.ReadAllLines("USStates.txt") Dim query = From line In usStates Let name = line.Split(","c)(0) Let abbrev = line.Split(","c)(1) Let area = CInt(line.Split(","c)(2)) Let pop = CInt(line.Split(","c)(3)) Let density = pop / area Let formattedDensity = density.ToString("N") Order By density Descending Select name, formattedDensity dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "State" dgvOutput.Columns("formattedDensity").HeaderText = "People per Square Mile" End Sub


Instructor Solutions Manual (Page 9 of 196) 25. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim states() As String = IO.File.ReadAllLines("USStates.txt") Dim query1 = From line In states Let area = CInt(line.Split(","c)(2)) Select area Dim totalArea = query1.Sum Dim query2 = From line In states Let name = line.Split(","c)(0) Let area = CInt(line.Split(","c)(2)) Let percentArea = (area / totalArea).ToString("P") Order By area Descending Select name, percentArea dgvOutput.DataSource = query2.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "State" dgvOutput.Columns("percentArea").HeaderText = "Percentage of Total Area" End Sub

26. Dim baseball() As String = IO.File.ReadAllLines("Baseball.txt") Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From line In baseball Let fullName = line.Split(","c)(0) Let team = line.Split(","c)(1) Let atBats = CInt(line.Split(","c)(2)) Let hits = CInt(line.Split(","c)(3)) Let firstName = fullName.Split(" "c).First Let lastName = fullName.Split(" "c).Last Let ave = (hits / atBats).ToString("N3") Where team.ToUpper = txtTeam.Text.ToUpper Order By lastName, firstName Select fullName, ave dgvPlayers.DataSource = query.ToList dgvPlayers.CurrentCell = Nothing dgvPlayers.Columns("fullName").HeaderText = "Player" dgvPlayers.Columns("ave").HeaderText = "Batting Average" End Sub


Instructor Solutions Manual (Page 10 of 196) 27. Private Sub btnUpdate_Click(...) Handles btnUpdate.Click Dim colors() As String = IO.File.ReadAllLines("Pre1990Colors.txt") Dim retired() As String = IO.File.ReadAllLines("RetiredColors.txt") Dim added() As String = IO.File.ReadAllLines("AddedColors.txt") Dim tempArray() As String = colors.Except(retired).ToArray Dim query = From color In tempArray.Concat(added) Order By color Select color IO.File.WriteAllLines("NewColors.txt", query) End Sub

28. Private Sub btnCreate_Click(...) Handles btnCreate.Click Dim justices() As String = IO.File.ReadAllLines("Justices.txt") Dim query = From justice In justices Let data = justice.Split(","c) Let fullName = data(0) & " " & data(1) Let state = data(3) Select fullName & "," & state IO.File.WriteAllLines("Justices_States.txt", query) End Sub 29. Private Sub btnCreate_Click(...) Handles btnCreate.Click Dim justices() As String = IO.File.ReadAllLines("Justices.txt") Dim query = From justice In justices Let data = justice.Split(","c) Let firstName = data(0) Let secondName = data(1) Let pres = data(2) Let yrAppt = data(4) Let yrLeft = data(5) Select firstName & "," & secondName & "," & pres & "," & yrAppt & "," & yrLeft IO.File.WriteAllLines("JusticesNoState.txt", query) End Sub


Instructor Solutions Manual (Page 11 of 196) 30. Private Sub btnCreate_Click(...) Handles btnDisplay.Click Dim justices() As String = IO.File.ReadAllLines("Justices.txt") Dim query = From justice In justices Let data = justice.Split(","c) Let firstName = data(0) Let secondName = data(1) Let pres = data(2) Let state = data(3) Let yrAppt = data(4) Let yrLeft = data(5) Select firstName, secondName, pres, state, yrAppt, yrLeft dgvJustices.DataSource = query.ToList dgvJustices.CurrentCell = Nothing End Sub

31. Private Sub btnCreate_Click(...) Handles btnDisplay.Click 'query1: all states; query2: states with justices Dim states() As String = IO.File.ReadAllLines("USStates.txt") Dim justices() As String = IO.File.ReadAllLines("Justices.txt") Dim query1 = From state In states Let abbrev = state.Split(","c)(1) Select abbrev Dim query2 = From justice In justices Let state = justice.Split(","c)(3) Select state IO.File.WriteAllLines("NoJustices.txt", query1.Except(query2)) End Sub


Instructor Solutions Manual (Page 12 of 196) 32. Private Sub btnCreate_Click(...) Handles btnCreate.Click 'query1: all years; query2: years in which justices were appointed Dim justices() As String = IO.File.ReadAllLines("Justices.txt") Dim years(220) As Integer For i As Integer = 0 To 223 years(i) = i + 1789 Next Dim query1 = From yr In years Select CStr(yr) Dim query2 = From justice In justices Let yearAppointed = justice.Split(","c)(4) Select yearAppointed IO.File.WriteAllLines("NoAppointments.txt", query1.Except(query2)) End Sub 33. Dim justices() As String = IO.File.ReadAllLines("Justices.txt") Private Sub Create_Click(...) Handles Create.Click Dim query = From line In justices Let state = line.Split(","c)(3) Order By state Ascending Select state & "," & NumberOfJustices(state) Distinct IO.File.WriteAllLines("NewFile.txt", query) End Sub Function NumberOfJustices(state As String) As Integer Dim query = From line In justices Let place = line.Split(","c)(3) Where place = state Select place Return query.Count End Function

34. Dim justices() As String = IO.File.ReadAllLines("Justices.txt") Private Sub btnCreate_Click(...) Handles btnCreate.Click Dim query = From line In justices Let pres = line.Split(","c)(2) Order By pres Ascending Select pres & "," & NumberOfJustices(pres) Distinct IO.File.WriteAllLines("NewFile.txt", query) End Sub Function NumberOfJustices(pres As String) As Integer Dim query = From line In justices Let chief = line.Split(","c)(2) Where chief = pres Select chief Return query.Count End Function


Instructor Solutions Manual (Page 13 of 196)

35. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From state In IO.File.ReadAllLines("USStates.txt") Let data = state.Split(","c) Let name = data(0) Let abbrev = data(1) Let area = (CDbl(data(2))).ToString("N0") Let pop = (CDbl(data(2))).ToString("N0") Order By name Select name, abbrev, area, pop dgvStates.DataSource = query.ToList dgvStates.CurrentCell = Nothing End Sub

EXERCISES 8.2 1. Hello

2. Aloha

3. Bon Jour

5. You must enter a number. 8. Error occurred

4. Buenos Dias

6. Error occurred.7. Error occurred.

9. File Ages.txt contains an invalid age.

10. File Ages.txt not found

11. The file Welcome.txt is created and has the following lines: Hello Bon Jour

12. The Mystery function returns the value True if Laura is in the file, and returns False otherwise. 13. The filespec Greetings.txt should be delimited with quotation marks. 14. A StreamWriter cannot read from a file. 15. There should be no quotations around the variable name as the argument to the CreateText method.


Instructor Solutions Manual (Page 14 of 196) 16. The string literal "Greetings.txt" should be replaced with the variable sw to close the reader in the third line. Also, replace StreamReader with StreamWriter. 17. 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. In line 4, CreateFile should be replaced with CreateText. In line 5, the words "exp As" should be inserted after the word "Catch". Also, the sw.Close() statement will generate an exception if the file was not found. 19. Private Sub btnCreate_Click(...) Handles btnCreate.Click 'Create a text file and populate it Dim sw As IO.StreamWriter = IO.File.CreateText("Cowboy.txt") sw.WriteLine("Colt Peacemaker,12.20") sw.WriteLine("Holster,2.00") sw.WriteLine("Levi Strauss jeans,1.35") sw.WriteLine("Saddle,40.00") sw.WriteLine("Stetson,10.00") sw.Close() 'Always close the writer when finished. MessageBox.Show("The file has been created.", "Done") End Sub

20. Private Sub btnCreate_Click(...) Handles btnCreate.Click 'Markdown the price of a saddle by 20% and 'store new list into Cowboy2.txt 'Open Cowboy for reading and Cowboy2 for creating Dim sr As IO.StreamReader = IO.File.OpenText("Cowboy.txt") Dim sw As IO.StreamWriter = IO.File.CreateText("Cowboy2.txt") Dim line As String = "" Dim data() As String Dim item As String Dim price As Double Do While Not sr.EndOfStream 'Loop until the end of file. line = sr.ReadLine 'Read the current item and price. data = line.Split(","c) item = data(0) price = CDbl(data(1)) If (item.ToUpper = "SADDLE") Then price = price * 0.8 'Adjust the price of the Saddle item. End If 'Write the item and price sw.WriteLine(item & "," & price.ToString("N")) Loop sr.Close() 'Always close the reader and writer when finished. sw.Close() MessageBox.Show("New file created.", "Done") End Sub


Instructor Solutions Manual (Page 15 of 196) 21. Private Sub btnAdd_Click(...) Handles btnAdd.Click 'Append item to a text file Dim sw As IO.StreamWriter = IO.File.AppendText("Cowboy.txt") sw.WriteLine("Winchester Rifle,20.50") sw.Close() MessageBox.Show("The item has been added to the file.", "Done") End Sub

22. Private Sub frmSalesReceipt_Load(...) Handles MyBase.Load 'Create a file containing the order Dim sw As IO.StreamWriter = IO.File.CreateText("Order.txt") sw.WriteLine(3) sw.WriteLine(2) sw.WriteLine(10) sw.WriteLine(1) sw.WriteLine(4) sw.Close() 'Always close writer when finished End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Read the order and items and display a receipt 'Open order and item files Dim srOrder As IO.StreamReader = IO.File.OpenText("Order.txt") Dim srItem As IO.StreamReader = IO.File.OpenText("Cowboy.txt") Dim total As Double = 0 Dim data() As String lstOutput.Items.Clear() Do While Not srItem.EndOfStream 'Loop over all records in Order Dim quantity As Integer = CInt(srOrder.ReadLine) Dim line As String = srItem.ReadLine data = line.Split(","c) Dim price As Double = CDbl(data(1)) lstOutput.Items.Add(quantity & " " & data(0) & ": " & (quantity * price).ToString("C")) total += quantity * price Loop srOrder.Close() 'Always close readers when finished srItem.Close() lstOutput.Items.Add("TOTAL: " & total.ToString("C")) End Sub


Instructor Solutions Manual (Page 16 of 196) 23. Private Sub btnAdd_Click(...) Handles btnAdd.Click Dim item As String Dim price As Double Dim sr As IO.StreamReader = IO.File.OpenText("Cowboy.txt") Dim sw As IO.StreamWriter = IO.File.CreateText("Cowboy2.txt") Dim flag As Boolean = False Dim line As String = "" Dim data() As String Do While (line < txtItem.Text) And (Not sr.EndOfStream) line = sr.ReadLine data = line.Split(","c) item = data(0) price = CDbl(data(1)) If item > txtItem.Text Then sw.WriteLine(txtItem.Text & "," & txtPrice.Text) 'Set flag to True so we don't add it again at the end flag = True End If sw.WriteLine(line) Loop Do Until sr.EndOfStream line = sr.ReadLine sw.WriteLine(line) Loop If Not flag Then sw.WriteLine(txtItem.Text & "," & txtPrice.Text) End If sr.Close() sw.Close() MessageBox.Show("Item added to Cowboy2.txt") txtItem.Clear() txtPrice.Clear() End Sub


Instructor Solutions Manual (Page 17 of 196) 24. Dim sw As IO.StreamWriter = IO.File.AppendText("Cowboy.txt") Private Sub btnAdd_Click(...) Handles btnAdd.Click 'Add item to list If (txtItem.Text <> "") And (txtPrice.Text <> "") Then sw.WriteLine(txtItem.Text & "," & txtPrice.Text) 'Reset input text boxes. txtItem.Clear() txtPrice.Clear() Else MessageBox.Show("Must enter item name and price.") End If txtItem.Focus() 'Reset focus End Sub Private Sub btnDone_Click(...) Handles btnDone.Click sw.Close() Me.Close() 'Terminate the program. End Sub

25. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim sr As IO.StreamReader = IO.File.OpenText("Cowboy.txt") Dim lines(4) As String For i As Integer = 0 To 4 lines(i) = sr.ReadLine Next Dim query = From line In lines Let data = line.Split(","c) Let item = data(0) Let cost = (CDbl(data(1))).ToString("C") Select item, cost dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing End Sub


Instructor Solutions Manual (Page 18 of 196) 26. Private Sub frmCreateFiles_Load(...) Handles MyBase.Load Dim sw As IO.StreamWriter = IO.File.CreateText("Greetings.txt") sw.WriteLine("Hello") sw.Close() End Sub Private Sub btnDelete_Click(...) Handles btnDelete.Click Dim sw As IO.StreamWriter = IO.File.AppendText("Greetings.txt") sw.WriteLine("Hi") Try IO.File.Delete("Greetings.txt") Catch ex As Exception sw.Close() IO.File.Delete("Greetings.txt") End Try End Sub

27. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim sr As IO.StreamReader = IO.File.OpenText("Numbers.txt") Dim counter As Integer = 0 Dim num As Double Do Until sr.EndOfStream num = CDbl(sr.ReadLine) counter += 1 Loop txtOutput.Text = CStr(counter) sr.Close() End Sub


Instructor Solutions Manual (Page 19 of 196) 28. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim sr As IO.StreamReader = IO.File.OpenText("Numbers.txt") Dim num As Double Dim max As Double = CDbl(sr.ReadLine) Do Until sr.EndOfStream num = CDbl(sr.ReadLine) If (num > max) Then max = num End If Loop txtOutput.Text = CStr(max) sr.Close() End Sub

29. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim sr As IO.StreamReader = IO.File.OpenText("Numbers.txt") Dim num As Double Dim min As Double = CDbl(sr.ReadLine) Do Until sr.EndOfStream num = CDbl(sr.ReadLine) If (num < min) Then min = num End If Loop txtOutput.Text = CStr(min) sr.Close() End Sub


Instructor Solutions Manual (Page 20 of 196) 30. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim sr As IO.StreamReader = IO.File.OpenText("Numbers.txt") Dim total As Double = 0 Dim num As Double Do Until sr.EndOfStream num = CDbl(sr.ReadLine) total += num Loop txtOutput.Text = CStr(total) sr.Close() End Sub

31. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim sr As IO.StreamReader = IO.File.OpenText("Numbers.txt") Dim counter As Integer = 0 Dim total As Double = 0 Dim num As Double Do Until sr.EndOfStream num = CDbl(sr.ReadLine) counter += 1 total += num Loop txtOutput.Text = (total / counter).ToString("N") sr.Close() End Sub 32. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim sr As IO.StreamReader = IO.File.OpenText("Numbers.txt") Dim num As Double Do Until sr.EndOfStream num = CDbl(sr.ReadLine) Loop txtOutput.Text = CStr(num) sr.Close() End Sub


Instructor Solutions Manual (Page 21 of 196)

EXERCISES 8.3 1. No

2. No

3. No

4. Yes

5. No

6. No

7. No

8. No

9. No

10. No

11. <?xml version='1.0'?> <!-- This file contains the ages of the presidents when inaugurated.--> <Presidents> <president> <name>George Washington</name> <ageAtInauguation>57</ageAtInauguation> </president> <president> <name>John Adams</name> <ageAtInauguation>61</ageAtInauguation> </president> </Presidents> 12. <?xml version="1.0" ?> <!-- This file contains data on each Supreme Court justice. --> <Supreme_Court> <justice> <firstName>Samuel</firstName> <secondName>Alito</secondName> <appointingPres>George W. Bush</appointingPres> <state>NJ</state> <yrAppointed>2006</yrAppointed> <yrLeft>0</yrLeft> </justice> <justice> <firstName>Henry</firstName> <secondName>Baldwin</secondName> <appointingPres>Andrew Jackson</appointingPres> <state>PA</state> <yrAppointed>1830</yrAppointed> <yrLeft>1844</yrLeft> </justice> </Supreme_Court>


Instructor Solutions Manual (Page 22 of 196) 13. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim stateData As XElement = XElement.Load("USStates.xml") Dim query = From st In stateData.Descendants("state") Let pop = CInt(st.<population>.Value) Select pop txtOutput.Text = (query.Sum).ToString("N0") End Sub

14. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim stateData As XElement = XElement.Load("USStates. xml ") Dim query = From st In stateData.Descendants("state") Let area = CInt(st.<area>.Value) Select area txtOutput.Text = (query.Sum).ToString("N0") & " square miles" End Sub 15. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim stateData As XElement = XElement.Load("USStates.xml") Dim queryPop = From st In stateData.Descendants("state") Let pop = CInt(st.<population>.Value) Select pop Dim queryArea = From st In stateData.Descendants("state") Let area = CInt(st.<area>.Value) Select area txtOutput.Text = (queryPop.Sum / queryArea.Sum).ToString("N") & " people per square mile" End Sub

16. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim stateData As XElement = XElement.Load("USStates. xml ") Dim query1 = From st In stateData.Descendants("state") Let name = st.<name>.Value Let len = name.Length Order By len Descending Select len Dim maxLength As Integer = query1.First Dim query2 = From st In stateData.Descendants("state") Let name = st.<name>.Value Let len = name.Length Where len = maxLength Select name lstOutput.DataSource = query2.ToList lstOutput.SelectedItem = Nothing End Sub


Instructor Solutions Manual (Page 23 of 196)

17. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim stateData As XElement = XElement.Load("USStates.xml") Dim query = From st In stateData.Descendants("state") Let name = st.<name>.Value Let area = CDbl(st.<area>.Value) Let formattedArea = area.ToString("N0") Where area > 100000 Order By area Descending Select name, formattedArea dgvStates.DataSource = query.ToList dgvStates.CurrentCell = Nothing dgvStates.Columns("name").HeaderText = "State" dgvStates.Columns("formattedArea").HeaderText = "Area" End Sub

18. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim stateData As XElement = XElement.Load("USStates.xml") Dim query = From st In stateData.Descendants("state") Let name = st.<name>.Value Let pop = CDbl(st.<population>.Value) Let formattedPop = pop.ToString("N0") Where pop < 1000000 Order By pop Ascending Select name, formattedPop dgvStates.DataSource = query.ToList dgvStates.CurrentCell = Nothing dgvStates.Columns("name").HeaderText = "State" dgvStates.Columns("formattedPop").HeaderText = "Population" End Sub 19. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim stateData As XElement = XElement.Load("USStates.xml") Dim query1 = From st In stateData.Descendants("state") Let name = st.<name>.Value Let numVowels = NumberOfVowels(name) Order By numVowels Descending Select numVowels Dim maxVowels As Integer = query1.First Dim query2 = From st In stateData.Descendants("state") Let name = st.<name>.Value Where NumberOfVowels(name) = maxVowels Select name lstOutput.DataSource = query2.ToList lstOutput.SelectedItem = Nothing End Sub


Instructor Solutions Manual (Page 24 of 196) Function NumberOfVowels(word As String) As Integer word = word.ToUpper Dim num As Integer = 0 If (word.IndexOf("A") <> -1) Then num += 1 End If If (word.IndexOf("E") <> -1) Then num += 1 End If If (word.IndexOf("I") <> -1) Then num += 1 End If If (word.IndexOf("O") <> -1) Then num += 1 End If If (word.IndexOf("U") <> -1) Then num += 1 End If Return num End Function

20. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim stateData As XElement = XElement.Load("USStates.xml") Dim query = From st In stateData.Descendants("state") Let name = st.<name>.Value.ToUpper Let abbrev = st.<abbreviation>.Value Where Not name.StartsWith(abbrev) Order By abbrev Ascending Select name, abbrev dgvStates.DataSource = query.ToList dgvStates.CurrentCell = Nothing dgvStates.Columns("name").HeaderText = "State" dgvStates.Columns("abbrev").HeaderText = "Abbreviation" End Sub


Instructor Solutions Manual (Page 25 of 196) 21. Dim colleges As XElement = XElement.Load("Colleges.xml") Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display the colleges in Colleges.xml located in the given state Dim chosenState As String = mtbState.Text.ToUpper 'mask LL Dim query = From col In colleges.Descendants("college") Let name = col.<name>.Value Let state = col.<state>.Value Let yearFounded = col.<yearFounded>.Value Where state = chosenState Order By name Ascending Select name & " " & yearFounded lstColleges.DataSource = query.ToList lstColleges.SelectedItem = Nothing End Sub

22. Dim colleges As XElement = XElement.Load("Colleges.xml") Private Sub frmColleges_Load(...) Handles MyBase.Load Dim query = From col In colleges.Descendants("college") Let name = col.<name>.Value Order By name Ascending Select name lstColleges.DataSource = query.ToList End Sub Private Sub lstColleges_SelectedIndexChanged(...) Handles _ lstColleges.SelectedIndexChanged Dim chosenCollege As String = lstColleges.Text Dim query = From col In colleges.Descendants("college") Let name = col.<name>.Value Let state = col.<state>.Value Let yearFounded = col.<yearFounded>.Value Where name = chosenCollege Select state, yearFounded txtState.Text = query.First.state txtYear.Text = query.First.yearFounded End Sub


Instructor Solutions Manual (Page 26 of 196) 23.Dim colleges As XElement = XElement.Load("Colleges.xml") Private Sub frmColleges_Load(...) Handles MyBase.Load 'Place the years for each college into the array schools Dim query = From col In colleges.Descendants("college") Let yearFounded = col.<yearFounded>.Value Order By yearFounded Ascending Select yearFounded Distinct lstYears.DataSource = query.ToList lstYears.SelectedItem = Nothing End Sub Private Sub lstYears_SelectedIndexChanged(...) Handles _ lstYears.SelectedIndexChanged Dim chosenYear As String = lstYears.Text Dim query = From col In colleges.Descendants("college") Let name = col.<name>.Value Let yearFounded = col.<yearFounded>.Value Where yearFounded = chosenYear Select name lstColleges.DataSource = query.ToList lstColleges.SelectedItem = Nothing End Sub

24. Dim colleges As XElement = XElement.Load("Colleges.xml") Private Sub frmColleges_Load(...) Handles MyBase.Load Dim query = From col In colleges.Descendants("college") Let name = col.<name>.Value Let state = col.<state>.Value Let yearFounded = col.<yearFounded>.Value Order By state, yearFounded Select name, state dgvColleges.DataSource = query.ToList dgvColleges.CurrentCell = Nothing dgvColleges.Columns("name").HeaderText = "College" dgvColleges.Columns("state").HeaderText = "State" End Sub


Instructor Solutions Manual (Page 27 of 196) Note: In the text file Senate113.txt, replace the name William Cowan with the winner of the June 25, 2013 special senate election in Massachusetts. 25(a). Private Sub btnSenate_Click(...) Handles btnSenate.Click Dim sr As IO.StreamReader = IO.File.OpenText("Senate113.txt") Dim sw As IO.StreamWriter = IO.File.CreateText("Senate113.xml") sw.WriteLine("<?xml version='1.0'?>") sw.WriteLine("<!-- This file contains data on the 113th Senate -->") sw.WriteLine("<Senate113>") Dim temp As String = "" Do Until sr.EndOfStream temp = sr.ReadLine sw.WriteLine(" <senator>") sw.WriteLine(" <name>" & temp.Split(","c)(0) & "</name>") sw.WriteLine(" <state>" & temp.Split(","c)(1) & "</state>") sw.WriteLine(" <party>" & temp.Split(","c)(2) & "</party>") sw.WriteLine(" </senator>") Loop sw.WriteLine("</Senate113>") sr.Close() sw.Close() MessageBox.Show("File Created") End Sub

25(b). Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim senateData As XElement = XElement.Load("Senate113.XML") Dim query = From st In senateData.Descendants("senator") Let name = st.<name>.Value Let state = st.<state>.Value Let party = st.<party>.Value Order By state, name Ascending Select name, state, party dgvSenators.DataSource = query.ToList dgvSenators.CurrentCell = Nothing dgvSenators.Columns("name").HeaderText = "Senator" dgvSenators.Columns("state").HeaderText = "State" dgvSenators.Columns("party").HeaderText = "Party Affiliation" End Sub


Instructor Solutions Manual (Page 28 of 196) 26(a). Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim sluggerData As XElement = XElement.Load("Top25HR.xml") Dim query = From st In sluggerData.Descendants("player") Let name = st.<name>.Value Let atBats = st.<atBats>.Value Let homeRuns = st.<homeRuns>.Value Order By homeRuns Descending Select name, atBats, homeRuns dgvSenators.DataSource = query.ToList dgvSenators.CurrentCell = Nothing dgvSenators.Columns("name").HeaderText = "Player" dgvSenators.Columns("atBats").HeaderText = "At Bats" dgvSenators.Columns("homeRuns").HeaderText = "Home Runs" End Sub

26(b). Private Sub btnCreate_Click(...) Handles btnCreate.Click Dim sluggerData As XElement = XElement.Load("Top25HR.xml") Dim query = From st In sluggerData.Descendants("player") Let name = st.<name>.Value Let atBats = st.<atBats>.Value Let homeRuns = st.<homeRuns>.Value Let line = name & "," & atBats & "," & homeRuns Select line IO.File.WriteAllLines("Top25HR.txt", query.ToArray) MessageBox.Show("File Created") End Sub


Instructor Solutions Manual (Page 29 of 196) CHAPTER 8 PROGRAMMING PROJECTS 1. Private Sub btnDisplay_Click(...) Handles btnCreate.Click Dim query = From line In IO.File.ReadAllLines("ALE.txt") Let data = line.Split(","c) Let team = data(0) Let wins = CInt(data(1)) Let losses = CInt(data(2)) Let pct = wins / (wins + losses) Let formattedPct = pct.ToString("N3") Order By pct Descending Select team & "," & wins & "," & losses & "," & formattedPct IO.File.WriteAllLines("OrderedALE.txt", query.ToArray) End Sub

Note: In the text files NewSen.txt and Senate113.txt, replace the name William Cowan with the winner of the June 25, 2013 special senate election in Massachusetts. 2(a). Private Sub btnCreate_Click(...) Handles btnCreate.Click Dim query1 = From senator In IO.File.ReadAllLines("Senate112.txt") Select senator Dim query2 = From senator In IO.File.ReadAllLines("RetiredSen.txt") Select senator Dim query3 = From senator In IO.File.ReadAllLines("NewSen.txt") Select senator Dim query4 = From senator In query1.Except(query2) Select senator Dim query5 = From senator In query4.Concat(query3) Order By senator.Split(","c)(1) Select senator IO.File.WriteAllLines("Senate113.txt", query5) MessageBox.Show("File Created") End Sub


Instructor Solutions Manual (Page 30 of 196) 2(b). Private Sub btnCount_Click(...) Handles btnCount.Click Dim senators() As String = IO.File.ReadAllLines("Senate113.txt") Dim queryDem = From senator In senators Let data = senator.Split(","c) Let party = data(2) Where party = "D" Select party txtDemocrats.Text = CStr(queryDem.Count) Dim queryRep = From senator In senators Let data = senator.Split(","c) Let party = data(2) Where party = "R" Select party txtRepublicans.Text = CStr(queryRep.Count) Dim queryInd = From senator In senators Let data = senator.Split(","c) Let party = data(2) Where party = "I" Select party txtIndependents.Text = CStr(queryInd.Count) End Sub


Instructor Solutions Manual (Page 31 of 196) 2(c). Dim senators() As String = IO.File.ReadAllLines("Senate113.txt") Private Sub btnCount_Click(...) Handles btnCount.Click Dim query = From senator In senators Let data = senator.Split(","c) Let state = data(1) Select state Distinct Dim total As Integer = 0 For Each state In query If SameParty(state) Then total += 1 End If Next txtSameParty.Text = CStr(total) End Sub Function SameParty(state As String) As Boolean Dim query = From senator In senators Let data = senator.Split(","c) Where data(1) = state Let party = data(2) Select party If (query.First = query.Last) Then Return True Else Return False End If End Function


Instructor Solutions Manual (Page 32 of 196) 2(d). Dim senators() As String = IO.File.ReadAllLines("Senate113.txt") Private Sub frmSenate_Load(...) Handles MyBase.Load Dim query = From senator In senators Let data = senator.Split(","c) Let state = data(1) Select state Distinct lstStates.DataSource = query.ToList lstStates.SelectedItem = Nothing End Sub Private Sub lstStates_SelectedIndexChangedc Handles _ lstStates.SelectedIndexChanged Dim query = From senator In senators Let data = senator.Split(","c) Let name = data(0) Let state = data(1) Where state = lstStates.Text Select name lstSenators.DataSource = query.ToList lstSenators.SelectedItem = Nothing End Sub

3(a)Dim sr As IO.StreamReader = IO.File.OpenText("Names.txt") Dim sw As IO.StreamWriter = IO.File.CreateText("NewFile.txt") Private Sub btnInsert_Click(...) Handles btnInsert.Click Dim newName = txtName.Text Dim name As String Dim insertFlag As Boolean = False Do Until sr.EndOfStream name = sr.ReadLine Select Case newName Case Is < name sw.WriteLine(newName) insertFlag = True sw.WriteLine(name) Finish() Exit Do Case name Finish() Exit Do Case Is > name sw.WriteLine(name) End Select Loop


Instructor Solutions Manual (Page 33 of 196) If Not insertFlag Then sw.WriteLine(newName) End If sr.Close() sw.Close() End Sub Sub Finish() Dim nom As String Do Until sr.EndOfStream nom = sr.ReadLine sw.WriteLine(nom) Loop sr.Close() sw.Close() End Sub

3(b). Private Sub btnInsert_Click(...) Handles btnInsert.Click Dim newName = txtName.Text Dim query1 = From name In IO.File.ReadAllLines("Names.txt") Select name Dim names() = query1.ToArray Dim n = names.Count - 1 ReDim Preserve names(n + 1) names(n + 1) = newName Dim query2 = From name In names Order By name Select name Distinct IO.File.WriteAllLines("NewFile.txt", query2.ToArray) End Sub


Instructor Solutions Manual (Page 34 of 196) 4.

Dim fileName As String = ""

'Current phone directory

Private Sub frmPhone_Load(...) Handles MyBase.Load DisplayDirectories() End Sub Private Sub btnCreate_Click(...) Handles btnCreate.Click Dim dirNames() As String = IO.File.ReadAllLines("Directories.txt") Dim sw As IO.StreamWriter = IO.File.AppendText("Directories.txt") Dim newDir As String = InputBox("Enter a file name.").ToUpper If (Array.IndexOf(dirNames, newDir) = -1) Then sw.WriteLine(newDir) Dim sw2 As IO.StreamWriter = IO.File.CreateText(newDir) sw2.Close() End If sw.Close() DisplayDirectories() End Sub Private Sub btnOpen_Click(...) MessageBox.Show("Click on an existing phone directory.") End Sub Sub DisplayDirectories() lstDirs.Items.Clear() If IO.File.Exists("Directories.txt") Then Dim query = From phoneDir In IO.File.ReadAllLines("Directories.txt") Order By phoneDir Select phoneDir For Each phoneDir In query lstDirs.Items.Add(phoneDir) Next End If End Sub Private Sub lstDirs_SelectedIndexChanged(...) Handles _ lstDirs.SelectedIndexChanged fileName = lstDirs.Text txtCurrent.Text = lstDirs.Text End Sub Private Sub btnAdd_Click(...) Handles btnAdd.Click 'Add name to directory (do not keep the file open). If (txtName.Text.Trim.Length = 0) Or (txtPhoneNumber.Text.Trim.Length = 0) Then MessageBox.Show("You must enter a name and number.") Else Dim sw As IO.StreamWriter = IO.File.AppendText(fileName) sw.WriteLine(txtName.Text & "," & txtPhoneNumber.Text) sw.Close() txtName.Clear() txtPhoneNumber.Clear() txtName.Focus() End If End Sub


Instructor Solutions Manual (Page 35 of 196) Private Sub btnRemove_Click(...) Handles btnRemove.Click Dim query = From line In IO.File.ReadAllLines(fileName) Let name = line.Split(","c)(0) Let phoneNum = line.Split(","c)(1) Where name <> txtName.Text Select name & "," & phoneNum IO.File.WriteAllLines(fileName, query.ToArray) txtName.Clear() txtPhoneNumber.Clear() txtName.Focus() End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click If ((fileName <> "") And IO.File.Exists(fileName)) Then Dim query = From line In IO.File.ReadAllLines(fileName) Let name = line.Split(","c)(0) Let phoneNum = line.Split(","c)(1) Order By name Select name, phoneNum dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "Name" dgvOutput.Columns("phoneNum").HeaderText = "Phone Number" End If End Sub


Instructor Solutions Manual (Page 36 of 196) 5. (Assume Imports System.IO placed at top of Code Editor) Private Sub frmUPC_Load(...) Handles MyBase.Load File.Delete("Items.txt") mtbUPC.Focus() End Sub Private Sub btnNewCustomer_Click(...) Handles btnNewCustomer.Click File.Delete("Items.txt") lstReceipt.Items.Clear() mtbUPC.Focus() End Sub Private Sub btnDisplayReceipt_Click(...) Handles btnDisplayReceipt.Click Dim UPC() As String = File.ReadAllLines("UPC.txt") Dim total As Double 'sum of all item prices Dim sr As StreamReader = File.OpenText("Items.txt") Dim code As String lstReceipt.Items.Clear() Do Until sr.EndOfStream code = sr.ReadLine Dim query = From line In UPC Let cd = line.Split(","c)(0) Let desc = line.Split(","c)(1) Let price = CDbl(line.Split(","c)(2)) Where cd = code Select desc, price If (query.Count = 0) Then 'UPC is not in the database lstReceipt.Items.Add("UPC " & code & " not found" & " " & "-----") Else lstReceipt.Items.Add(query.First.desc & ": " & (query.First.price).ToString("C")) total += query.First.price End If Loop sr.Close() lstReceipt.Items.Add("TOTAL: " & total.ToString("C") End Sub Private Sub btnAddItem_Click(...) Handles btnAddItem.Click Dim sw As StreamWriter = File.AppendText("Items.txt") If isValidUPC(mtbUPC.Text) Then sw.WriteLine(mtbUPC.Text) lstReceipt.Items.Add(mtbUPC.Text & " -- OK") Else lstReceipt.Items.Add("UPC Error -- Please re-enter UPC") End If sw.Close() mtbUPC.Clear() mtbUPC.Focus() End Sub


Instructor Solutions Manual (Page 37 of 196) Function isValidUPC(upc As String) As Boolean Dim upcLength As Integer = 12 Dim d(upcLength) As Integer 'Array of digits of UPC code as numbers Dim checksum As Integer 'Weighted sum of digits as given by formula 'Determines whether the given upc code is a valid UPC If (upc.Length <> 12) Then isValidUPC = False Else For i As Integer = 1 To upcLength d(i) = CInt(upc.Substring(i - 1, 1)) Next i checksum = 0 For i As Integer = 1 To (upcLength – 1) Step 2 checksum = checksum + (3 * d(i)) + d(i + 1) Next i If (checksum Mod 10) = 0 Then isValidUPC = True Else isValidUPC = False End If End If End Function


Instructor Solutions Manual (Page 38 of 196) 6.

Dim playerData As XElement = XElement.Load("Baseball.xml") Private Sub frmBaseball_Load(...) Handles MyBase.Load Dim query = From pl In playerData.Descendants("player") Let team = pl.<team>.Value Order By team Select team Distinct For Each club In query lstTeams.Items.Add(club) Next End Sub Private Sub lstTeams_SelectedIndexChanged(...) Handles _ lstTeams.SelectedIndexChanged Dim query = From pl In playerData.Descendants("player") Let team = pl.<team>.Value Let atBats = CInt(pl.<atBats>.Value) Let hits = CInt(pl.<hits>.Value) Let battingAverage = hits / atBats Where team = lstTeams.Text Select battingAverage Dim teamAverage As Double = query.Average Dim query2 = From pl In playerData.Descendants("player") Let name = pl.<name>.Value Let team = pl.<team>.Value Let atBats = CInt(pl.<atBats>.Value) Let hits = CInt(pl.<hits>.Value) Let battingAverage = hits / atBats Let formattedBattingAve = battingAverage.ToString("N3") Where (team = lstTeams.Text) And (battingAverage > teamAverage) Order By battingAverage Descending Select name, formattedBattingAve dgvPlayers.DataSource = query2.ToList dgvPlayers.CurrentCell = Nothing dgvPlayers.Columns("name").HeaderText = "Player" dgvPlayers.Columns("formattedBattingAve").HeaderText = "Batting Average" End Sub


Instructor Solutions Manual (Page 39 of 196)

CHAPTER 9 EXERCISES 9.1 1.

Chopin is deleted from the list.

2.

The first item, Bach, is removed from lstBox.

3.

The currently selected item in lstBox, Mozart, is deleted.

4.

The last item, Tchaikovsky, is removed from lstBox.

5.

The item Haydn is inserted into lstBox between Chopin and Mozart.

6.

The number 2 is displayed in the text box.

7.

The names in the list box will appear in descending alphabetical order.

8.

The names in the list box will appear in descending alphabetical order.

9.

cboBox.Text = "Dante"

10. cboBox.Text = CStr(cboBox.Items(2)) 11. cboBox.Items.Remove("Shakespeare") 12. cboBox.Items.Remove("Goethe") 13. cboBox.Items.RemoveAt(cboBox.Items.Count - 1) 14. For i As Integer = 0 To (cboBox.Items.Count – 1) Step 2 lstOutput.Items.Add(cboBox.Items(i)) Next 15. Dim i As Integer = 0 Do While i < cboBox.Items.Count If (CStr(cboBox.Items(i)).Substring(0, 1) = "M") Then cboBox.Items.RemoveAt(i) Else i += 1 End If Loop


Instructor Solutions Manual (Page 40 of 196) 16. Dim found As Boolean = False For i As Integer = 0 To (cboBox.Items.Count – 1) If CStr(cboBox.Items(i)) = "Cervantes" Then found = True End If Next If found Then txtOutput.Text = "Cervantes is in the list." Else txtOutput.Text = "Cervantes not found." End If 17. Private Sub btnSort_Click(...) Handles btnSort.Click 'Assume the String Collection Editor was filled with the numbers '4, 9, 2, 11, 5, 17, 3, 6 at design time Dim n As Integer = lstBox.Items.Count - 1 Dim nums(n) As Double For i As Integer = 0 To n nums(i) = CDbl(lstBox.Items(i)) Next Dim query = From num In nums Order By num Ascending Select num lstBox.DataSource = query.ToList lstBox.SelectedItem = Nothing End Sub

18. Private Sub btnRemove_Click(sender As System.Object, e As System.EventArgs) Handles btnRemove.Click Dim n As Integer = lstDOW.Items.Count - 1 Dim stocks(n) As String For i As Integer = 0 To n stocks(i) = CStr(lstDOW.Items(i)) Next Dim query = From stock In stocks Select stock Distinct lstDOW.DataSource = query.ToList lstDOW.SelectedItem = Nothing End Sub


Instructor Solutions Manual (Page 41 of 196) 19. Private Sub frmList_Load(...) Handles MyBase.Load lblCount.Text = CStr(lstOutput.Items.Count) End Sub Private Sub btnAdd_Click(...) Handles btnAdd.Click Dim first(), last() As String Dim location As Integer = lstOutput.SelectedIndex Dim newItem As String = InputBox("Enter item to add to list:", "Add Item") If (location = -1) Then ReDim first(lstOutput.Items.Count - 1) For i As Integer = 0 To (lstOutput.Items.Count – 1) first(i) = CStr(lstOutput.Items(i)) Next lstOutput.Items.Clear() lstOutput.Items.Add(newItem) For i As Integer = 0 To (first.Count – 1) lstOutput.Items.Add(first(i)) Next Else ReDim first(location - 1) For i As Integer = 0 To (location - 1) first(i) = CStr(lstOutput.Items(i)) Next ReDim last(lstOutput.Items.Count - location - 1) For i As Integer = 0 To (lstOutput.Items.Count - location - 1) last(i) = CStr(lstOutput.Items(location + i)) Next lstOutput.Items.Clear() For i As Integer = 0 To (first.Count – 1) lstOutput.Items.Add(first(i)) Next lstOutput.Items.Add(newItem) For i As Integer = 0 To (last.Count – 1) lstOutput.Items.Add(last(i)) Next End If lblCount.Text = CStr(lstOutput.Items.Count) 'Update the counter. End Sub Private Sub btnDelete_Click(...) Handles btnDelete.Click Dim location As Integer = lstOutput.SelectedIndex 'Only delete if something is selected. If (location >= 0) Then lstOutput.Items.RemoveAt(location) lblCount.Text = CStr(lstOutput.Items.Count) 'Update the counter. End If End Sub


Instructor Solutions Manual (Page 42 of 196) 20. Private Sub btnSort_Click(...) Handles btnSort.Click Dim n As Integer = lstBox.Items.Count - 1 Dim words(n) As String For i As Integer = 0 To n words(i) = CStr(lstBox.Items(i)) Next Dim query = From word In words Order By word Descending Select word lstBox.DataSource = query.ToList lstBox.SelectedItem = Nothing End Sub 21. Private Sub btnSort_Click(...) Handles btnSort.Click Dim names() As String = IO.File.ReadAllLines("PopularNames.txt") lstOutput.Sorted = True lstOutput.DataSource = names lstOutput.SelectedItem = Nothing For i As Integer = 0 To (lstOutput.Items.Count – 1) names(i) = CStr(lstOutput.Items(i)) Next IO.File.WriteAllLines("SortedNames.txt", names) MessageBox.Show("The ordered file has been created.", "Done") End Sub


Instructor Solutions Manual (Page 43 of 196) 22. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Convert a length from one unit to the other. 'The inches array stores the number of inches in each unit. Dim inches() As Double = {1, 12, 3 * 12, 100 / 2.54, 12 * 5280} 'If input is not specified, display message. If ((lstFrom.SelectedIndex < 0) Or (lstTo.SelectedIndex < 0) Or (txtAmount.Text = "")) Then MessageBox.Show("Please select both units and " & "enter a length.", "INCOMPLETE") Else 'Convert the first units to inches, then convert to second units. Dim result As Double = CDbl(txtAmount.Text) * inches(lstFrom.SelectedIndex) / inches(lstTo.SelectedIndex) 'Display the decimal places in the result depending upon the size. If (result < 1) Then txtOutput.Text = result.ToString("N6") Else txtOutput.Text = result.ToString("N") End If End If End Sub 23. Dim ages() As String = IO.File.ReadAllLines("AgesAtInaugural.txt") Private Sub frmPres_Load(...) Handles MyBase.Load Dim pres() As String = IO.File.ReadAllLines("USPres.txt") lstPres.DataSource = pres End Sub Private Sub lstPres_SelectedIndexChanged(...) Handles _ lstPres.SelectedIndexChanged txtAge.Text = ages(lstPres.SelectedIndex) End Sub

24. Private Sub btnReport_Click(...) Handles btnReport.Click 'Display the space chosen txtAnswer.Text = "You have landed on " & cboMonopoly.Text & "." End Sub


Instructor Solutions Manual (Page 44 of 196) 25. 'Note: This event procedure handles events from all three combo boxes Private Sub SelectedIndexChanged(...) Handles _ cboBrand.SelectedIndexChanged, cboMemory.SelectedIndexChanged, cboMonitor.SelectedIndexChanged 'Update output if all choices have been made. If ((cboBrand.SelectedIndex >= 0) And (cboMemory.SelectedIndex >= 0) And (cboMonitor.SelectedIndex >= 0)) Then txtOutput.Text = "You have a " & cboBrand.Text & " computer with " & cboMemory.Text & " of memory and a " & cboMonitor.Text & " monitor." End If End Sub

EXERCISES 9.2 1. The Tick event will be triggered every 5 seconds (5000 milliseconds). 2. The control Timer1 is disabled. 3. The tooltip will appear one second after the cursor is hovered over a control. 4. The tooltip will remain visible for 4 seconds after it appears. 5. A check mark appears in front of the mnuOrderAsc menu item. 6. The menu item mnuOrderAsc appears without a check mark to its left. 7. The Tick event will be triggered every intVar seconds. 8. A number from 1 through 100 is randomly selected and displayed in txtBox. 9. The name of one of the 44 U.S. presidents is selected at random and displayed in txtBox. 10. A character that can be displayed with the computer keyboard is selected at random and displayed in txtBox. 11. Two states are selected at random and displayed in the list box. 12. A card is drawn at random from a standard deck of playing cards. 13. The contents of the Clipboard are deleted.


Instructor Solutions Manual (Page 45 of 196) 14. The contents of the clipboard become the string "Hello". 15. The text currently selected in txtBox, if any, is copied into the Clipboard. 16. The currently selected text in the text box is replaced with the contents of the clipboard. If no text is currently selected, the clipboard's contents are inserted into the text box at the current cursor position. 17. The contents of the Clipboard are displayed in txtBox. 18. The contents of the clipboard become the string "Happy". 19. The contents of the Clipboard are assigned to the variable strVar. 20. Any picture placed into the picture box will be automatically enlarged or contracted to fit the picture box. 21. A blue circle of radius 50 pixels will be drawn in the picture box. Its upper- leftmost point will be 20 pixels from the left side of the picture box and 30 pixels from the top side. 22. A green rectangle of width 200 pixels and height 100 pixels will be drawn in the picture box. Its upper-left corner will be 25 pixels from the left side of the picture box and 50 units from the top side. 23. A picture of an airplane will be placed in the picture box. 24. The scroll box moves so that its left side is in the middle of the horizontal scroll bar. 25. Clicking on the arrow on either end of the scroll bar will move the button the same ("large") distance as clicking on the bar between the scroll box and an arrow. 26. Timer1.Interval = 500 Timer1.Enabled = True 27. Timer1.Enabled = False 28. Dim randomNum As New Random() txtBox.Text = names(randomNum.Next(0, 20)) 29. Dim randomNum As New Random() txtBox.Text = CStr(randomNum.Next(1, 13)) 30. Dim randomNum As New Random() 'A and Z have ANSI values 65 and 90. txtBox.Text = Chr(randomNum.Next(65, 91)) 31. Dim sr As IO.StreamReader = IO.Files.ReadText("Towns.txt") Dim randomNum As New Random() Dim num As Integer = randomNum.Next(1, 26) Dim city As String For i As Integer = 1 To num city = sr.ReadLine Next txtBox.Text = city 32. Dim randomNum As New Random() txtBox.Text = CStr(randomNum(1, 7) + randomNum(1, 7))


Instructor Solutions Manual (Page 46 of 196) 33. Dim n As Integer = rivers.Count If (n >= 2) Then Dim randomNum As New Random() Dim firstNumber, secondNumber As Integer firstNumber = randomNum.Next(0, n) Do secondNumber = randomNum.Next(0, n) Until secondNumber <> firstNumber lstBox.Items.Add(rivers(firstNumber)) lstBox.Items.Add(rivers(secondNumber)) Else MessageBox.Show("The array has fewer than two elements.") End If 34. txtBox.SelectedText = Clipboard.GetText 35. Clipboard.SetText("") 36. Clipboard.SetText("Rosebud") 37. Clipboard.SetText(txtBox.SelectedText) 38. txtBox.SelectedText = "" 39. Dim amount As Integer amount = CInt(Clipboard.GetText) 40. PictureBox1.CreateGraphics.DrawEllipse(Pens.Yellow, 10, 10, 100, 100) 41. mnuOrderDesc.Checked = False 42.

mnuOrderDesc.Text = "Decreasing Order"

43. VScrollBar2.Value = VScrollBar2.Minimum 44. HScrollBar2.Value = CInt(HScrollBar2.Minimum + (HScrollBar2.Maximum - HScrollBar2.Minimum) / 3)

45. The menu item mnuOrderAsc is grayed out and cannot be selected. 46. The menu item mnuOrderAsc is not visible in the pull-down menu.


Instructor Solutions Manual (Page 47 of 196) 47. Private Sub frmClock_Load(...) Handles MyBase.Load picBox.Image = Image.FromFile("Trees.bmp") UpdateClock() End Sub Private Sub tmrClock_Tick(...) Handles tmrClock.Tick UpdateClock() End Sub Private Sub UpdateClock() Dim timeStr As String = "" timeStr = timeStr & (Hour(Now)).ToString("N0") timeStr &= ":" & PadZero(Minute(Now)) timeStr &= ":" & PadZero(Second(Now)) lblTime.Text = timeStr End Sub Function PadZero(num As Integer) As String 'Pads a one-digit number with a zero Dim result As String result = num.ToString("N0") If num < 10 Then Return "0" & result Else Return result End If End Function

48. Dim randomNum As New Random()

'Random number generator

Private Sub btnToss_Click(...) Handles btnToss.Click 'Toss a coin, and keep track of results. If randomNum.Next(0, 2) = 0 Then txtOutcome.Text = "Heads" txtHeads.Text = CStr(CInt(txtHeads.Text) + 1) Else txtOutcome.Text = "Tails" txtTails.Text = CStr(CInt(txtTails.Text) + 1) End If 'Display total tosses and percentage. txtTosses.Text = CStr(CInt(txtTosses.Text) + 1) txtPercentHeads.Text = (CDbl(txtHeads.Text) / CDbl(txtTosses.Text)).ToString("P") End Sub


Instructor Solutions Manual (Page 48 of 196) 49. Private Sub btnSelect_Click(...) Handles btnSelect.Click 'Assume there are at least three members in the club. Dim names() As String = IO.File.ReadAllLines("Members.txt") Dim n As Integer = names.Count Dim p As Integer Dim randomNum As New Random() p = randomNum.Next(0, n) txtPresident.Text = names(p) 'Swap President with the person in the last array element. names(p) = names(n - 1) names(n - 1) = txtPresident.Text 'Choose a random person from first n-1 for Treasurer. p = randomNum.Next(0, n - 1) txtTreasurer.Text = names(p) 'Swap Treasurer with the person in the next to last array element. names(p) = names(n - 2) names(n - 2) = txtTreasurer.Text 'Choose a random person from first n-2 for Secretary. p = randomNum.Next(0, n - 2) txtSecretary.Text = names(p) End Sub


Instructor Solutions Manual (Page 49 of 196) 50. Private Sub btnDeal_Click(...) Handles btnDeal.Click 'Deal five cards at random Dim deckOfCards(51) As String Dim suits() As String = {"Hearts", "Diamonds", "Clubs", "Spades"} Dim randomNum As New Random() Dim temp As String Dim n As Integer 'Populate each suit of the deck. For i As Integer = 0 To 3 'Populate numbers 2 through 10. For j As Integer = 2 To 10 deckOfCards(i * 13 + j) = j & " of " & suits(i) Next 'Populate the honors cards. deckOfCards(i * 13 + 0) = "King of " & suits(i) deckOfCards(i * 13 + 1) = "Ace of " & suits(i) deckOfCards(i * 13 + 11) = "Jack of " & suits(i) deckOfCards(i * 13 + 12) = "Queen of " & suits(i) Next lstOutput.Items.Clear() 'Choose and display five cards at random. For i As Integer = 1 To 5 'Choose a card at random. n = randomNum.Next(0, 53 - i) lstOutput.Items.Add(deckOfCards(n)) 'Swap the chosen card with the one at the end. temp = deckOfCards(n) deckOfCards(n) = deckOfCards(52 - i) deckOfCards(52 - i) = temp Next End Sub


Instructor Solutions Manual (Page 50 of 196) 51. Private Sub tmrMoon_Tick(...) Handles tmrMoon.Tick 'Update the phase and display the image. 'Timer Interval setting is 2000; Timer Enabled setting is True phase += 1 If phase = 9 Then phase = 1 End If picBox.Image = Image.FromFile("Moon" & phase & ".bmp") End Sub

52. Private Sub btnSelect_Click(...) Handles btnSelect.Click Dim j As Integer Dim names() As String = IO.File.ReadAllLines("Names.txt") Dim temp As String = "" Dim randomNum As New Random For i As Integer = 0 To 39 j = randomNum.Next(i, 100) 'swap names(i) and names(j) temp = names(i) names(i) = names(j) names(j) = temp Next 'Display the forty selected names lstOutput.Items.Clear() For i As Integer = 0 To 39 lstOutput.Items.Add(names(i)) Next End Sub


Instructor Solutions Manual (Page 51 of 196) 53. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim match As Boolean Dim num, i As Integer Dim people(22) As Integer Dim randomNum As New Random For k As Integer = 1 To 1000 match = False For j As Integer = 0 To 22 people(j) = randomNum.Next(1, 366) Next i = 0 Do Until i = 22 Or match For j As Integer = i + 1 To 22 If people(i) = people(j) Then match = True End If Next i += 1 Loop If match Then num += 1 End If Next txtNum.Text = CStr(num / 10) End Sub


Instructor Solutions Manual (Page 52 of 196) 54. Private Sub btnPlay_Click(...) Handles btnPlay.Click Dim deckOfCards(51) As String Dim suits() As String = {"Hearts", "Diamonds", "Clubs", "Spades"} Dim n, earnings As Integer Dim randomNum As New Random() Dim temp, card As String Dim numberOfDiamonds As Integer = 0 Dim numberOfWins As Integer = 0 Dim numberOfLosses As Integer = 0 For i As Integer = 0 To 3 'Populate numbers 2 through 10. For j As Integer = 2 To 10 deckOfCards(i * 13 + j) = j & " of " & suits(i) Next deckOfCards(i * 13 + 0) = "King of " & suits(i) deckOfCards(i * 13 + 1) = "Ace of " & suits(i) deckOfCards(i * 13 + 11) = "Jack of " & suits(i) deckOfCards(i * 13 + 12) = "Queen of " & suits(i) Next For d As Integer = 1 To 1000 numberOfDiamonds = 0 'Choose and display two cards at random. For i As Integer = 1 To 2 n = randomNum.Next(0, 53 - i) card = deckOfCards(n) If card.Substring(card.Length - 8) = "Diamonds" Then numberOfDiamonds += 1 End If 'Swap the chosen card with the one at the end. temp = deckOfCards(n) deckOfCards(n) = deckOfCards(52 - i) deckOfCards(52 - i) = temp Next If numberOfDiamonds = 0 Then earnings -= 1 Else earnings += 1 End If Next Select Case earnings Case 0 txtResult.Text = "You broke even." Case Is > 0 txtResult.Text = "You won " & earnings & " dollars." Case Is < 0 txtResult.Text = "You lost " & (-1 * earnings) & " dollars." End Select End Sub


Instructor Solutions Manual (Page 53 of 196) 55. (no code)

56. Private Sub lstBox_DoubleClick(...) Handles lstBox.DoubleClick lstBox.Items.Remove(lstBox.Text) End Sub 57. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display the open file dialog box to get the file Dim fileSpec As String OpenFileDialog1.ShowDialog() fileSpec = OpenFileDialog1.FileName 'Display picture contained in the file. picBox.Image = Image.FromFile(fileSpec) End Sub

58. Private Sub mnuCopy_Click(...) Handles mnuCopy.Click 'Copy selected text into Clipboard. If txtBox.SelectedText <> "" Then Clipboard.SetText(txtBox.SelectedText) Else MessageBox.Show("You must first select some text to be copied.") End If End Sub Private Sub mnuPaste_Click(...) Handles mnuPaste.Click 'Paste Clipboard into text box. txtBox.SelectedText = Clipboard.GetText End Sub Private Sub mnuCut_Click(...) Handles mnuCut.Click 'Copy selected text into Clipboard, and delete selected text. If txtBox.SelectedText <> "" Then Clipboard.SetText(txtBox.SelectedText) txtBox.SelectedText = "" Else MessageBox.Show("You must first select some text to be cut.") End If End Sub


Instructor Solutions Manual (Page 54 of 196) 59. Dim randomNum As New Random() Private Sub btnPlay_Click(...) Handles btnPlay.Click 'Roll a pair of dice until 7 appears 1000 times. Dim die1, die2 As Integer Dim numberOfSevens As Integer = 0 Dim numberOfRolls As Integer = 0 Do 'Roll the dice die1 = randomNum.Next(1, 7) die2 = randomNum.Next(1, 7) 'If lucky 7, increment the sevens counter. If (die1 + die2) = 7 Then numberOfSevens += 1 End If numberOfRolls += 1 'Increment the rolls counter. Loop Until (numberOfSevens = 1000) 'Display the result to two decimal places. txtOutput.Text = (numberOfRolls / numberOfSevens).ToString("N") End Sub

60. Public Sub vsbFahren_Scroll(...) Handles vsbFahren.Scroll 'When Fahrenheit value changes, update the Celsius value. 'vsbFahren.Minimum = 32, vsbFahren.Maximum = 225 'vsbFahren.SmallChange = 1, vsbFahren.LargeChange = 14 txtFahren.Text = CStr(vsbFahren.Value) Dim celsius As Integer = CInt((5 / 9) * (vsbFahren.Value - 32)) vsbCelsius.Value = celsius txtCelsius.Text = CStr(vsbCelsius.Value) End Sub Public Sub vsbCelsius_Scroll(...) Handles vsbCelsius.Scroll 'When Celsius value changes, update the Fahrenheit value 'vsbCelsius.Minimum = 0, vsbCelsius.Maximum = 125 'vsbCelsius.SmallChange = 1, vsbCelsius.LargeChange = 10 txtCelsius.Text = CStr(vsbCelsius.Value) Dim fahrenheit As Integer = CInt((9 / 5) * vsbCelsius.Value + 32) vsbFahren.Value = fahrenheit txtFahren.Text = CStr(vsbFahren.Value) End Sub


Instructor Solutions Manual (Page 55 of 196) 61. Private Sub tmrBall_Tick(...) Handles tmrBall.Tick 'Update the value of the scroll bar and label. 'Timer Interval setting is 1000 'vsbBall.Minimum = 0, vsbBall.Maximum = 10 count = count - 1 vsbBall.Value = 10 - count lblBall.Text = CStr(count) 'If at zero, display the message and end program. If count = 0 Then tmrBall.Enabled = False MessageBox.Show("HAPPY NEW YEAR", "NYE") Me.Close() End If End Sub

62. Private Sub btnRollDice_Click(...) Handles btnRollDice.Click Dim randomNum As New Random Dim num1, num2 As Integer Dim dicePicture1, dicePicture2 As String num1 = randomNum.Next(1, 7) num2 = randomNum.Next(1, 7) dicePicture1 = "die" & CStr(num1) & ".jpg" dicePicture2 = "die" & CStr(num2) & ".jpg" picDie1.Image = Image.FromFile(dicePicture1) picDie2.Image = Image.FromFile(dicePicture2) txtSum.Text = CStr(num1 + num2) End Sub 63. Structure Country Dim name As String Dim alreadyShown As Boolean End Structure Dim flags() As String = IO.File.ReadAllLines("flagCountries.txt") 'flags() is used to count the number of flags and to populate the list box Dim countries(flags.Length) As Country 'primary array for program Dim n As Integer Dim count As Integer = 0 'number of flags shown Dim randomNum As New Random Private Sub frmFlags_Load(...) Handles MyBase.Load For i As Integer = 0 To (flags.Length – 1) countries(i).name = flags(i) countries(i).alreadyShown = False


Instructor Solutions Manual (Page 56 of 196) Next n = CInt(randomNum.Next(0, flags.Length)) picFlag.Image = Image.FromFile("flag" & flags(n) & ".jpg") countries(n).alreadyShown = True count += 1 lstCountries.DataSource = flags lstCountries.SelectedIndex = -1 End Sub Private Sub lstCountries_Click(...) Handles lstCountries.Click If lstCountries.SelectedIndex = n Then MessageBox.Show("Correct") Else MessageBox.Show("Not Correct") End If lstCountries.SelectedIndex = -1 End Sub Private Sub btnDisplayFlag_Click(...) Handles btnDisplayFlag.Click If count < flags.Length Then Dim found As Boolean = False Do Until found n = CInt(randomNum.Next(0, flags.Length)) If countries(n).alreadyShown = False Then found = True End If countries(n).alreadyShown = True Loop picFlag.Image = Image.FromFile("flag" & flags(n) & ".jpg") count += 1 Else MessageBox.Show("All flags shown.") End If End Sub

EXERCISES 9.3 1. $106.00

2. John, you are not yet 21 years old.

3. Your last name begins with K.

4. The average is 90.


Instructor Solutions Manual (Page 57 of 196) 5. 'Form1's code Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Form2.ShowDialog() txtQuotation.Text = Form2.quotation End Sub 'Form2's code (Movies) Public quotation As String Private Sub btnProcessSelection_Click(...) Handles _ btnProcessSelection.Click If rad1.Checked Then quotation = "Plastics." End If If rad2.Checked Then quotation = "Rosebud." End If If rad3.Checked Then quotation = "That's all folks." End If Me.Close() End Sub

6. 'Form Name's code Public fullName As String Private Sub btnExtract_Click(...) Handles btnExtract.Click fullName = txtFull.Text Form2.ShowDialog() End Sub 'Form2's code (Parsed Name) Private Sub Form2_Load(...) Handles MyBase.Load Dim parsedName() As String = frmName.fullName.Split(" "c) txtFirst.Text = parsedName.First txtLast.Text = parsedName.Last End Sub


Instructor Solutions Manual (Page 58 of 196)

7. 'Code for frmMillionaire Public numberOfYrs As Integer Public Const INTEREST_RATE As Double = 0.06 Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim balance As Double, numYears As Integer balance = CDbl(txtAmount.Text) Do While balance < 1000000 balance += INTEREST_RATE * balance numYears += 1 Loop txtWhen.Text = "In " & numYears & " years you will have a million dollars." numberOfYrs = numYears frmBalance.ShowDialog() End Sub 'Code for frmBalance Structure Year Dim num As Integer Dim amount As Double End Structure Private Sub frmBalance_Activated(...) Handles Me.Load Dim a(frmMillionaire.numberOfYrs) As Year a(0).num = 0 a(0).amount = CDbl(frmMillionaire.txtAmount.Text) For i As Integer = 1 To (a.Count – 1) a(i).num = i a(i).amount = (1 + frmMillionaire.INTEREST_RATE) * a(i - 1).amount Next Dim query = From yr In a Let Year = yr.num Let Amount = (yr.amount).ToString("C") Select Year, Amount dgvBalance.DataSource = query.ToList dgvBalance.CurrentCell = Nothing End Sub Private Sub frmBalance_FormClosing(...) Handles Me.FormClosing frmMillionaire.txtAmount.Clear() frmMillionaire.txtWhen.Clear() frmMillionaire.txtAmount.Focus() End Sub


Instructor Solutions Manual (Page 59 of 196) 8. Structure Month Dim number As Integer Dim principalPaid As Double Dim interestPaid As Double Dim endBalance As Double End Structure Structure EffectOfRate Dim interestRate As Double Dim monthlyPayment As Double End Structure Private Sub btnPayment_Click(...) Handles btnPayment.Click Dim principal As Double 'Amount of loan Dim yearlyRate As Double 'Annual rate of interest Dim numMonths As Integer 'Number of months to repay loan InputData(principal, yearlyRate, numMonths) Dim monthlyRate As Double = yearlyRate / 12 Dim monthlyPayment As Double 'Calculate monthly payment monthlyPayment = Payment(principal, monthlyRate, numMonths) 'Display results MessageBox.Show("Monthly payment: " & monthlyPayment.ToString("C"), "PAYMENT") End Sub Private Sub btnAmort_Click(...) Handles btnAmort.Click Dim principal As Double 'Amount of loan Dim yearlyRate As Double 'Annual rate of interest Dim numMonths As Integer 'Number of months to repay loan InputData(principal, yearlyRate, numMonths) Dim months(numMonths - 1) As Month Dim monthlyRate As Double = yearlyRate / 12 Dim monthlyPayment As Double = Payment(principal, monthlyRate, numMonths) months = FillMonthsArray(principal, monthlyRate, numMonths) Dim query = From mnth In months Let num = mnth.number Let interest = (mnth.interestPaid).ToString("C") Let prin = (mnth.principalPaid) .ToString("C") Let bal = (mnth.endBalance) .ToString("C") Select num, interest, prin, bal frmAmort.dgvResults.DataSource = query.ToList frmAmort.dgvResults.CurrentCell = Nothing frmAmort.dgvResults.Columns("num").HeaderText = "Month" frmAmort.dgvResults.Columns("interest").HeaderText = "Amount Paid for Interest" frmAmort.dgvResults.Columns("prin").HeaderText = "Amount Paid for Principal" frmAmort.dgvResults.Columns("bal").HeaderText = "Balance at End of Month" frmAmort.ShowDialog() End Sub


Instructor Solutions Manual (Page 60 of 196) Private Sub btnShow_Click(...) Handles btnShow.Click Dim principal As Double 'Amount of loan Dim yearlyRate As Double 'Annual rate of interest Dim numMonths As Integer 'Number of months to repay loan InputData(principal, yearlyRate, numMonths) Dim months(numMonths - 1) As Month Dim monthlyRate As Double = yearlyRate / 12 Dim monthlyPayment As Double = Payment(principal, monthlyRate, numMonths) months = FillMonthsArray(principal, monthlyRate, numMonths) Dim beginningMonth As Integer = CInt(InputBox("Enter beginning month: ")) Dim query = From mnth In months Where (mnth.number >= beginningMonth) And (mnth.number < beginningMonth + 12) Select mnth.interestPaid MessageBox.Show("Interest Paid for year beginning with month " & beginningMonth & ": " & (query.Sum).ToString("C"), "INTEREST FOR YEAR") End Sub Private Sub btnRateTable_Click(...) Handles btnRateTable.Click Dim principal As Double 'Amount of loan Dim yearlyRate As Double 'Annual rate of interest Dim numMonths As Integer 'Number of months to repay loan InputData(principal, yearlyRate, numMonths) Dim rates(16) As EffectOfRate Dim monthlyRate As Double = yearlyRate / 12 'Dim monthlyPayment As Double = Payment(principal, monthlyRate, numMonths) 'Fill rates array For i As Integer = 0 To 16 rates(i).interestRate = (yearlyRate - 0.01) + i * 0.00125 rates(i).monthlyPayment = Payment(principal, rates(i).interestRate / 12, numMonths) Next Dim query = From rate In rates Let annualRate = (rate.interestRate).ToString("P3") Let monthlyPayment = (rate.monthlyPayment).ToString("C") Select annualRate, monthlyPayment frmIntRate.dgvResults.DataSource = query.ToList frmIntRate.dgvResults.CurrentCell = Nothing frmIntRate.dgvResults.Columns("annualRate").HeaderText = "Interest Rate" frmIntRate.dgvResults.Columns("monthlyPayment").HeaderText = "Monthly Payment" frmIntRate.ShowDialog() End Sub Private Sub btnQuit_Click(...) Handles btnQuit.Click End End Sub Sub InputData(ByRef principal As Double, ByRef yearlyRate As Double, ByRef numMonths As Integer) Dim percentageRate As Double, numYears As Integer principal = CDbl(txtPrincipal.Text) percentageRate = CDbl(txtYearlyRate.Text) yearlyRate = percentageRate / 100 'Convert interest rate to decimal form numYears = CInt(txtNumYears.Text) numMonths = numYears * 12 'Duration of loan in momths End Sub


Instructor Solutions Manual (Page 61 of 196)

Function Payment(principal As Double, monthlyRate As Double, numMonths As Double) As Double Dim estimate As Double 'Estimate of monthly payment estimate = principal * monthlyRate / (1 - (1 + monthlyRate) ^ (-numMonths)) ' Round the payment up if it there are fractions of a cent If estimate = Math.Round(estimate, 2) Then Return estimate Else Return Math.Round(estimate + 0.005, 2) End If End Function Function FillMonthsArray(principal As Double, monthlyRate As Double, numMonths As Integer) As Month() Dim months(numMonths - 1) As Month Dim monthlyPayment As Double = Payment(principal, monthlyRate, numMonths) months(0).number = 1 months(0).interestPaid = monthlyRate * principal months(0).endBalance = (1 + monthlyRate) * principal - monthlyPayment months(0).principalPaid = monthlyPayment - months(0).interestPaid 'Assign values for interior months For i As Integer = 1 To (numMonths – 2) months(i).number = i + 1 months(i).interestPaid = monthlyRate * months(i - 1).endBalance months(i).endBalance = (1 + monthlyRate) * months(i - 1).endBalance monthlyPayment months(i).principalPaid = monthlyPayment - months(i).interestPaid Next months(numMonths - 1).number = numMonths months(numMonths - 1).interestPaid = monthlyRate * months(numMonths - 2).endBalance months(numMonths - 1).endBalance = 0 months(numMonths - 1).principalPaid = monthlyPayment months(numMonths - 1).interestPaid Return months End Function


Instructor Solutions Manual (Page 62 of 196)


Instructor Solutions Manual (Page 63 of 196)

9. Form1's Code 'Class-level named constants and variables 'Data files that store information Const INIT_FILE As String = "Initial_Info.txt" Public Const TRANS_FILE As String = "Transactions.txt" 'Variables used for each entry Dim isCheck As Boolean Dim nameOnChk As String 'Name to appear on checks Dim lastCkNum As Integer 'Number of last check written Dim lastDpNum As Integer 'Number of last deposit slip processed Dim curBal As Double 'Current balance in account Private Sub frmAccount_Load(...) Handles MyBase.Load 'Sets the class variables from a new or existing text file InitializeData() 'Set name and balance labels lblName.Text = nameOnChk txtBalance.Text = curBal.ToString("C") 'Set the date field to the current date. txtDate.Text = CStr(Today) SetupCheck() ResetInput() End Sub Private Sub InitializeData() If IO.File.Exists(INIT_FILE) Then Dim data() As String 'holds the data read from the file Dim initFileContents() As String = IO.File.ReadAllLines(INIT_FILE) 'Split the single line of the INIT_FILE using the separator data = initFileContents.First.Split(","c) 'Load the name to appear on checks, current balance, number of 'last check written and number of last deposit slip processed nameOnChk = data(0) curBal = CDbl(data(1)) lastCkNum = CInt(data(2)) lastDpNum = CInt(data(3)) 'Possibly update the values above by looking at last record of TRANS_FILE If IO.File.Exists(TRANS_FILE) Then Dim transFileContents() As String = IO.File.ReadAllLines(TRANS_FILE) data = transFileContents.Last.Split(","c) curBal = CDbl(data(2)) lastCkNum = CInt(data(3)) lastDpNum = CInt(data(4)) End If


Turn static files into dynamic content formats.

Create a flipbook
SOLUTIONS MANUAL For An Introduction to Programming Using Visual Basic 2012, 9th Edition by David I. by digitaldownload87 - Issuu