Instructor Solutions Manual (Page 1 of 221)
SOLUTIONS MANUAL For An Introduction to Programming Using Visual Basic 2012, 9th Edition by David I. Schneider
Part A Chapters 2 through 7 : Page 1-224 Part B Chapters 8 through 11: Page 225-422
All Chapters Solutions Manual Supplement files download link at the end of this file.
Instructor Solutions Manual (Page 3 of 221)
Part A CONTENTS Chapter 2 Visual Basic Controls and Events Exercises 2.2 Visual Basic Controls 4 Exercises 2.3 Visual Basic Events 11 Chapter 3 Variables, Input, and Output Exercises 3.1 Numbers 16 Exercises 3.2 Strings 20 Exercises 3.3 Input and Output 29 Programming Projects 33 Chapter 4 Decisions Exercises 4.1 Relational and Logical Operators 37 Exercises 4.2 If Blocks 37 Exercises 4.3 Select Case Blocks 51 Exercises 4.4 Input via User Selection 61 Programming Projects 71 Chapter 5 General Procedures Exercises 5.1 Function Procedures 80 Exercises 5.2 Sub Procedures, Part I 86 Exercises 5.3 Sub Procedures, Part II 94 Programming Projects 99 Chapter 6 Repetition Exercises 6.1 Do Loops 108 Exercises 6.2 For…Next Loops 117 Exercises 6.3 List Boxes and Loops 128 Programming Projects 142 Chapter 7 Arrays Exercises 7.1 Creating and Using Arrays 151 Exercises 7.2 Using LINQ with Arrays 165 Exercises 7.3 Arrays of Structures 175 Exercises 7.4 Two-Dimensional Arrays 190 Programming Projects 203
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 16 of 221)
CHAPTER 3 EXERCISES 3.1 1. 12
2. 49
3. .125
4. 23
5. 8
6. –96
7. 2
8. 2
9. 1
10. 3
11. Not valid
12. Not valid
13. Valid
14. Not valid
15. Not valid
16. Not valid
17. 10
18. 14
19. 16
20. 16
21. 9
22. 8
23. Private Sub btnCompute_Click(...) Handles btnCompute.Click lstOutput.Items.Add((7 * 8) + 5) End Sub 24. Private Sub btnCompute_Click(...) Handles btnCompute.Click lstOutput.Items.Add((1 + (2 * 9)) ^ 3) End Sub 25. Private Sub btnCompute_Click(...) Handles btnCompute.Click lstOutput.Items.Add(0.055 * 20) End Sub 26. Private Sub btnCompute_Click(...) Handles btnCompute.Click lstOutput.Items.Add(15 - 3 * (2 + (3 ^ 4))) End Sub 27. Private Sub btnCompute_Click(...) Handles btnCompute.Click lstOutput.Items.Add(17 * (3 + 162)) End Sub 28. Private Sub btnCompute_Click(...) Handles btnCompute.Click lstOutput.Items.Add((4 + (1 / 2)) - (3 + (5 / 8))) End Sub 29. Private Sub btnEvaluate_Click(...) Handles btnEvaluate.Click Dim x, y As Double x = 2 y = 3 * x x = y + 5 lstResults.Items.Clear() lstResults.Items.Add(x + 4) y = y + 1 End Sub
x
y
0 2 2 11 11 11 11
0 0 6 6 6 6 7
Get complete Order files download link below htps://www.mediafire.com/file/�351cwx7zi5x55/SM+ An+Introduc�on+to+Programming+Using+Visual+Basic +2012,+9e+David+Schneider.zip/file
If this link does not work with a click, then copy the complete Download link and paste link in internet explorer/firefox/google chrome and get all files download successfully.
Instructor Solutions Manual (Page 17 of 221) 30. Private Sub btnEvaluate_Click(...) Handles btnEvaluate.Click Dim bal, inter, withDr As Double bal = 100 inter = 0.05 withDr = 25 bal += inter * bal bal = bal – withDr End Sub 31. 6
32. 24
33. 1 8 9
34. 10
35. 1 64
36. 225
bal
inter
withDr
0 100 100 100 105 80
0 0 0.05 0.05 0.05 0.05
0 0 0 25 25 25
37. 2 15
38. 5 10
39. The third line should read c = a + b 40. The third assignment statement does not work. In the last statement, there needs to be an asterisk after the 5. Also, the last statement needs two extra closing parenthesis at the end. 41. The first assignment statement should not contain a comma. The second assignment statement should not contain a dollar sign. 42. The first assignment statement should read interest = 0.05 43. 9W is not a valid variable name. 44. Round should be changed to Math.Round 45. Dim quantity As Integer = 12 46. Dim m As Integer = 2, n As Double = 3 47. 10
48. 7
49. 6
50. 8
51. 3.128
52. -3
53. –3
54. 2
55. 0
56. 3
57. 6
58. 1
59. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim revenue, costs, profit As Double revenue = 98456 costs = 45000 profit = revenue - costs lstOutput.Items.Add(profit) End Sub
Instructor Solutions Manual (Page 18 of 221)
60. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim costPerShare, numberOfShares, amount As Double costPerShare = 25.625 numberOfShares = 400 amount = costPerShare * numberOfShares lstOutput.Items.Add(amount) End Sub 61. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim price, discountPercent, markdown As Double price = 19.95 discountPercent = 30 markdown = (discountPercent / 100) * price price = price - markdown lstOutput.Items.Add(Math.Round(price, 2)) End Sub 62. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim fixedCosts, pricePerUnit, costPerUnit, breakEvenPoint As Double fixedCosts = 5000 pricePerUnit = 8 costPerUnit = 6 breakEvenPoint = fixedCosts / (pricePerUnit - costPerUnit) lstOutput.Items.Add(breakEvenPoint) End Sub 63. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim balance As Double balance = 100 balance += 0.05 * balance balance += 0.05 * balance balance += 0.05 * balance lstOutput.Items.Add(Math.Round(balance, 2)) End Sub 64. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim balance As Double balance = 100 balance += 0.05 * balance + 100 balance += 0.05 * balance + 100 balance += 0.05 * balance lstOutput.Items.Add(Math.Round(balance, 2)) End Sub 65. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim balance As Double balance = 100 balance = balance * (1.05 ^ 10) lstOutput.Items.Add(Math.Round(balance, 2)) End Sub
Instructor Solutions Manual (Page 19 of 221) 66. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim purchasePrice, sellingPrice, percentProfit As Double purchasePrice = 10 sellingPrice = 15 percentProfit= 100 * (sellingPrice - purchasePrice) / purchasePrice lstOutput.Items.Add(percentProfit) End Sub 67. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim acres, yieldPerAcre, corn As Double acres = 30 yieldPerAcre = 18 corn = yieldPerAcre * acres lstOutput.Items.Add(corn) End Sub
68. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim initialVelocity, initialHeight, height, t As Double initialVelocity = 50 initialHeight = 5 t = 3 height = (-16 * t ^ 2) + (initialVelocity * t) + initialHeight lstOutput.Items.Add(height) End Sub 69. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim distance, elapsedTime, averageSpeed As Double distance = 233 elapsedTime = 7 - 2 averageSpeed = distance / elapsedTime lstOutput.Items.Add(averageSpeed) End Sub
70. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim miles, gallonsUsed, milesPerGallon As Double miles = 23695 - 23352 gallonsUsed = 14 milesPerGallon = miles / gallonsUsed lstOutput.Items.Add(milesPerGallon) End Sub
Instructor Solutions Manual (Page 20 of 221) 71. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim waterPerPersonPerDay, people, days, waterUsed As Double waterPerPersonPerDay = 1600 people = 315000000 days = 365 waterUsed = waterPerPersonPerDay * people * days lstOutput.Items.Add(waterUsed) End Sub
72. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim numPerDay As Integer numPerDay = 350 * 60 * 60 * 24 lstOutput.Items.Add(numPerDay) End Sub 73. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim pizzarias, percent, restaurants As Double pizzarias = 70000 percent = 0.12 restaurants = pizzarias / percent lstOutput.Items.Add(Math.Round(restaurants)) End Sub
74. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim pop2000, pop2050, percentGrowth As Double pop2000 = 281 pop2050 = 404 percentGrowth = Math.Round(100 * ((pop2050 - pop2000) / pop2000)) lstOutput.Items.Add((percentGrowth)) End Sub
EXERCISES 3.2 1. Visual Basic
2. Hello
3. Ernie
4. Bert
5. flute
6. acute
7. 123
8. 8
9. Your age is 21.
10. Fred has 2 children.
11. A ROSE IS A ROSE IS A ROSE
12. 76 trombones
Instructor Solutions Manual (Page 21 of 221)
13. 5.5
14. 3
17. WALLAWALLA
18. murmur
19. ABC 2 4 55 mph STU
20. 8 ball 21. 12 22. 9 -1 MUNICIPALITY microsoft 5 city os evolutionary 6 5 10
23. 8 (0 through 7)
24. 7
15. goodbye
25. True
16. eighth
26. True
27. The variable phoneNumber should be declared as type String, not Double. 28. The sentence in the second line should be surrounded by quotation marks. 29. End is a keyword and cannot be used as a variable name. 30. txtBox should be changed to txtBox.Text. 31. The IndexOf method cannot be applied to a number, only a string. 32. A number does not have a Length property, only a String has a Length property. 33. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim firstName, middleName, lastName As String Dim yearOfBirth As Integer firstName = "Thomas" middleName = "Alva" lastName = "Edison" yearOfBirth = 1847 txtOutput.Text = firstName & " " & middleName & " " & lastName & ", " & yearOfBirth End Sub 34. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim item As String, regularPrice, discount As Double item = "ketchup" regularPrice = 1.8 discount = 0.27 txtOutput.Text = (regularPrice - discount) & " is the sale price of " & item & "." End Sub 35. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim publisher As String publisher = "Pearson" txtOutput.Text = "(c) " & publisher End Sub
Instructor Solutions Manual (Page 22 of 221) 36. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim prefix As String prefix = "Fore" txtOutput.Text = prefix & "warned is " & prefix & "armed." End Sub 37. Dim str As String
'Place in the Declarations section of the program
38. Dim str As String
'Place near the top of the event procedure
39. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim distance As Double distance = CDbl(txtNumSec.Text) / 5 distance = Math.Round(distance, 2) txtOutput.Text = "The distance of the storm is " & distance & " miles." End Sub
40. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim thr, age, rhr As Double age = CDbl(txtAge.Text) rhr = CDbl(txtRestHR.Text) thr = 0.7 * (220 - age) + 0.3 * rhr thr = Math.Round(thr) txtTrainHR.Text = "Your THR is " & thr & " beats per minute." End Sub 41. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim cycling, running, swimming, pounds As Double cycling = CDbl(txtCycle.Text) running = CDbl(txtRun.Text) swimming = CDbl(txtSwim.Text) pounds = (200 * cycling + 475 * running + 275 * swimming) / 3500 pounds = Math.Round(pounds, 1) txtWtLoss.Text = pounds & " pounds were lost." End Sub
Instructor Solutions Manual (Page 23 of 221)
42. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim wattage, hours, price, costInCents, costInDollars As Double wattage = CDbl(txtWattage.Text) hours = CDbl(txtHoursUsed.Text) price = CDbl(txtPricePerKWh.Text) costInCents = (wattage * hours) / (10 * price) 'cost = (wattage * hours) / (1000 * price) costInDollars = Math.Round(costInCents) / 100 txtCost.Text = CStr(costInDollars) End Sub 43. Private Sub btnAdd_Click(...) Handles btnAdd.Click Dim hr1, hr2, min1, min2, totalMinutes, totalHours As Integer hr1 = CInt(txtHours1.Text) hr2 = CInt(txtHours2.Text) min1 = CInt(txtMin1.Text) min2 = CInt(txtMin2.Text) totalMinutes = (min1 + min2) Mod 60 totalHours = hr1 + hr2 + ((min1 + min2) \ 60) txtSum.Text = totalHours & " hours and " & totalMinutes & " minutes" End Sub
44. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim numberOfGames As Integer Dim percent, percentage As Double numberOfGames = CInt(txtWon.Text) + CInt(txtLost.Text) percent = CDbl(txtWon.Text) / numberOfGames percentage = 100 * Math.Round(percent, 5) txtPercent.Text = "The " & txtTeam.Text & " won " & percentage & " percent of their games." End Sub
Instructor Solutions Manual (Page 24 of 221)
45. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim revenue, expenses, income As Double revenue = CDbl(txtRevenue.Text) expenses = CDbl(txtExpenses.Text) income = revenue - expenses txtNetIncome.Text = CStr(income) End Sub
46. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim per As Double per = CDbl(txtPrice.Text) / CDbl(txtEarnings.Text) txtPER.Text = CStr(per) End Sub 47. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim speed, distance As Double distance = CDbl(txtDistanceSkidded.Text) speed = Math.Sqrt(24 * distance) speed = Math.Round(speed, 2) txtEstimatedSpeed.Text = speed & " mph" End Sub
48. Private Sub btnConvert_Click(...) Handles btnConvert.Click Dim per As String, num As Double per = txtPercent.Text per = per.Substring(0, per.Length - 1) num = CDbl(per) / 100 txtNumber.Text = CStr(num) End Sub
Instructor Solutions Manual (Page 25 of 221) 49. Dim number As Integer = 100
'in Declarations section
Private Sub btnPressMe_Click(...) Handles btnPressMe.Click number = number - 1 'decrease number by 1 txtOutput.Text = CStr(number) End Sub
50. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim phoneNumber As String phoneNumber = txtPhoneNumber.Text txtAreaCode.Text = phoneNumber.Substring(0, 3) End Sub 51. Dim sum As Double Dim num As Integer
'sum of the scores entered 'number of scores entered
Private Sub btnRecord_Click(...) Handles btnRecord.Click num += 1 sum += CDbl(txtScore.Text) txtScore.Clear() txtScore.Focus() End Sub Private Sub btnCalculate_Click(...) Handles btnCalculate.Click txtAverage.Text = CStr(sum / num) End Sub
52. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim sentence = "THE QUICK BROWN FOX JUMPS OVER A LAZY DOG" Dim letter As String, position As Integer letter = txtLetter.Text.ToUpper position = sentence.IndexOf(letter) txtOutput.Text = letter & " first occurs in position " & position & "." End Sub
Instructor Solutions Manual (Page 26 of 221) 53. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim amount, percentage, tip As Double amount = CDbl(txtAmount.Text) percentage = CDbl(txtPercentage.Text) tip = amount * (percentage / 100) txtTip.Text = CStr(Math.Round(tip, 2)) End Sub
54. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim number As String, position As Integer number = txtNumber.Text position = number.IndexOf(".") txtLeft.Text = CStr(position) txtRight.Text = CStr(number.Length - position - 1) End Sub 55. Private Sub btnModifySentence_Click(...) Handles btnModifySentence.Click Dim sentence, oldWord, newWord As String Dim position As Integer sentence = txtSentence.Text oldWord = txtOriginalWord.Text newWord = txtReplacementWord.Text position = sentence.IndexOf(oldWord) txtOutput.Text = sentence.Substring(0, position) & newWord & sentence.Substring(position + oldWord.Length) End Sub
Instructor Solutions Manual (Page 27 of 221) 56. Dim totalSales As Double Private Sub btnDisplay_Click(...) Handles btnDisplay.Click lstOutput.Items.Add(txtItem.Text & ": " & txtPrice.Text) totalSales += CDbl(txtPrice.Text) txtItem.Clear() txtPrice.Clear() txtItem.Focus() End Sub Private Sub btnShow_Click(...) Handles btnShow.Click lstOutput.Items.Add("Total commission = " & (0.06 * totalSales)) End Sub
57. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim num1, num2, sum As Double num1 = CDbl(txtFirstNum.Text) num2 = CDbl(txtSecondNum.Text) sum = num1 + num2 txtSum.Text = CStr(sum) End Sub Private Sub txtEitherNum_TextChanged(...) Handles _ txtFirstNum.TextChanged, txtSecondNum.TextChanged txtSum.Clear() End Sub
Instructor Solutions Manual (Page 28 of 221) 58. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim principal, interestRate, balance As Double Dim numYears As Integer principal = CDbl(txtPrincipal.Text) interestRate = CDbl(txtInterest.Text) numYears = CInt(txtYears.Text) balance = principal * (1 + interestRate / 100) ^ numYears txtBalance.Text = balance.ToString("C") End Sub
59. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim futureValue, interestRate, presentValue As Double Dim numYears As Integer futureValue = CDbl(txtFutureValue.Text) interestRate = CDbl(txtInterest.Text) numYears = CInt(txtYears.Text) presentValue = futureValue / (1 + interestRate / 100) ^ numYears txtPresentValue.Text = CStr(Math.Round(presentValue, 2)) End Sub
Instructor Solutions Manual (Page 29 of 221) 60. Private Sub btnConvert_Click(...) Handles btnConvert.Click Dim numMonths As Integer = CInt(txtMonths.Text) Dim years As Integer = numMonths \ 12 Dim remainingMonths = numMonths Mod 12 txtAnswer.Text = years.ToString("N0") & " years and " & remainingMonths & " months" End Sub
61. Private Sub btnConvert_Click(...) Handles btnConvert.Click Dim feet, inches As Integer inches = CInt(txtInches.Text) feet = inches \ 12 inches = inches Mod 12 txtFeetAndInches.Text = feet & " feet and " & inches & " inches" End Sub
EXERCISES 3.3 1. 1,235
2. –12.346
3. 1,234.0
5. 0.0
6. 0.1
11. 12
12. $1,234.50
15. ($0.23)
7. -0.67
8. 1.20
13. $12,346
16. $3,200.00
19. $0.08
20. -5.000 %
23. 66.67 %
24. 75.0 %
4. 12,345.00
17. $0.80 21. 100.00 %
25. Pay to France $27,267,622.00
9. 12,346.000
10. 12
14. ($1,234,567.00) 18. 4% 22. 1.00 %
26. Manhattan was purchased for $24.00
27. 25.6% of the U.S. population 25+ years old are college graduates. 28. 1,711,500 degrees were conferred. 29. The likelihood of Heads is 50%
30. Pi = 3.1416
31. 10/23/2012
32. Sunday, June 15, 2014
33. Thursday, November 28, 2013
34. 1/1/2012
35. 10/2/2014
36. 2/9/2013
37. 4/5/2016
38. 11/2/2012
39. 29
40. 366
41. 5
42. 2
Instructor Solutions Manual (Page 30 of 221) 43. 1
44. 2013
47. You might win 360 dollars.
45. 2015
46. 3
48. Untied
49. Hello John Jones
50. At the current interest rate, money will double in 18 years. 51. $106.00
52. You owe $900,000.00 in estate taxes.
53. The statement n += 1 is not valid since the value of a named constant cannot be changed. 54. The statement n = n.ToUpper is not valid since the value of a constant cannot be changed.
55. The second line should use CDbl to convert the right-hand side to type Double. 56. There needs to be a string inside the InputBox() call (i.e., the "Prompt" argument is required). 57. (123456).ToString("N") is a string and therefore cannot be assigned to a numeric variable. 58. Must remove the dollar sign. 59. You must insert .Show after the word MessageBox. 60. 1776 should be surrounded with quote marks 61. 000
62. LLLLLLLLLL
63. LLL000
64. 0LLL000
65. 0-00-000000-&
66. LL
67. MessageBox.Show("First solve the problem. Then write the code.", "Good Advice") 68. MessageBox.Show("You can't steal second base and keep one foot on first.", "Taking Risks Proverb") 69. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim begOfYearCost, endOfYearCost As Double Dim percentIncrease As Double begOfYearCost = 200 endOfYearCost = CDbl(InputBox("Enter cost at the end of the year:")) percentIncrease = (endOfYearCost - begOfYearCost) / begOfYearCost txtOutput.Text = "The increase in cost for the year is " & percentIncrease.ToString("P") & "." End Sub 70. Private Sub btnDisplayReport_Click(..) Handles btnDisplayReport.Click 'Report the amount of money raised in a walk-a-thon Dim pledge, miles As Double pledge = CDbl(InputBox("Enter amount pledged per mile:", "Walk-A-Thon")) miles = CDbl(InputBox("Enter number of miles walked:", "Walk-A-Thon")) txtReport.Text = "Collect " & (pledge * miles).ToString("C") & " from this sponsor." End Sub
Instructor Solutions Manual (Page 31 of 221) 71. Private Sub txtPhoneNumber_Enter(...) Handles txtPhoneNumber.Enter MessageBox.Show("Be sure to include the area code!", "Reminder") End Sub
72. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim dateDOC As Date = #7/4/1776# Dim numDays As Double = DateDiff(DateInterval.Day, dateDOC, Today) txtNumDays.Text = numDays.ToString("N0") End Sub 73. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim firstDayOfYr, firstDayOfNextYr As Date Dim numDays As Double firstDayOfYr = CDate("1/1/" & mtbYear.Text) firstDayOfNextYr = firstDayOfYr.AddYears(1) numDays = DateDiff(DateInterval.Day, firstDayOfYr, firstDayOfNextYr) txtNumDays.Text = CStr(numDays) End Sub
74. Private Sub Determine_Click(...) Handles btnDetermine.Click Dim dt As Date = CDate(mtbDate.Text) Dim fullDate As String = dt.ToString("D") Dim position As Integer = fullDate.IndexOf(",") Dim dayOfWeek As String = fullDate.Substring(0, position) txtDayOfWeek.Text = dayOfWeek End Sub 75. Private Sub Determine_Click(...) Handles btnDetermine.Click Dim dt As Date = CDate(mtbDate.Text) Dim laterDate = dt.AddYears(10) Dim fullDate As String = laterDate.ToString("D") Dim position As Integer = fullDate.IndexOf(",") Dim dayOfWeek As String = fullDate.Substring(0, position) txtDayOfWeek.Text = dayOfWeek End Sub
Instructor Solutions Manual (Page 32 of 221)
76. Private Sub Determine_Click(...) Handles btnDetermine.Click Dim dt As Date = CDate(mtbDate.Text) Dim turn21Date = dt.AddYears(21) Dim fullDate As String = turn21Date.ToString("D") Dim position As Integer = fullDate.IndexOf(",") Dim dayOfWeek As String = fullDate.Substring(0, position) txtDayOfWeek.Text = dayOfWeek End Sub 77. Private Sub btnConvert_Click(...) Handles btnConvert.Click Dim dt As Date dt = CDate(txtUS.Text) txtEurope.Text = dt.Day & "/" & dt.Month & "/" & dt.Year End Sub
78. Private Sub btnWhen_Click(...) Handles btnWhen.Click Dim yr As String Dim dt As Date yr = txtYear.Text dt = CDate("2/14/" & yr) txtDate.Text = dt.ToString("D") End Sub 79. Private Sub Determine_Click(...) Handles btnDetermine.Click Dim month, yr As Integer 'month given as 1 through 12 Dim dt, dt2 As Date Dim numDays As Double month = CInt(txtMonth.Text) yr = CInt(mtbYear.Text) dt = CDate(month & "/1/" & yr) dt2 = dt.AddMonths(1) numDays = DateDiff(DateInterval.Day, dt, dt2) txtNumDays.Text = CStr(numDays) End Sub
Instructor Solutions Manual (Page 33 of 221)
80. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim dob As Date = CDate(mtbDayOfBirth.Text) Dim ageOnEarthInDays, ageOnMercuryInYears As Double txtToday.Text = Today.ToString("d") ageOnEarthInDays = DateDiff(DateInterval.Day, dob, Today) ageOnMercuryInYears = ageOnEarthInDays / 88 txtAgeOnMercury.Text = ageOnMercuryInYears.ToString("N1") & " Mercurian years" End Sub
CHAPTER 3 PROGRAMMING PROJECTS 1. Private Sub btnAdd_Click(...) Handles btnAdd.Click Dim num1 As Double = CDbl(txtFirstNum.Text) Dim num2 As Double = CDbl(txtSecondNum.Text) txtOutput.Text = num1 & " + " & num2 & " = " & num1 + num2 End Sub Private Sub btnSubtract_Click(...) Handles btnSubtract.Click Dim num1 As Double = CDbl(txtFirstNum.Text) Dim num2 As Double = CDbl(txtSecondNum.Text) txtOutput.Text = num1 & " - " & num2 & " = " & num1 - num2 End Sub Private Sub btnMultiply_Click(...) Handles btnMultiply.Click Dim num1 As Double = CDbl(txtFirstNum.Text) Dim num2 As Double = CDbl(txtSecondNum.Text) txtOutput.Text = num1 & " x " & num2 & " = " & (num1 * num2) End Sub Private Sub input_TextChanged(...) Handles txtFirstNum.TextChanged, txtSecondNum.TextChanged txtOutput.Clear() End Sub
Instructor Solutions Manual (Page 34 of 221)
2. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim labor, parts, total As Double Dim laborRate, tax As Double laborRate = 55 'dollars per hour tax = 0.05 '5% sales tax labor = CDbl(txtHours.Text) * 35 '$35/hour labor cost parts = CDbl(txtCost.Text) parts += parts * 0.05 '5% sales tax total = labor + parts lstBill.Items.Clear() lstBill.Items.Add("Customer " & txtCustomer.Text) lstBill.Items.Add("Labor cost " & labor.ToString("C")) lstBill.Items.Add("Parts cost " & parts.ToString("C")) lstBill.Items.Add("Total cost " & total.ToString("C")) End Sub
3. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim remainder As Integer = CInt(txtAmount.Text) Dim quarters, dimes, nickels, cents As Integer quarters = remainder \ 25 remainder = remainder Mod 25 dimes = remainder \ 10 remainder = remainder Mod 10 nickels = remainder \ 5 remainder = remainder Mod 5 cents = remainder txtQuarters.Text = CStr(quarters) txtDimes.Text = CStr(dimes) txtNickels.Text = CStr(nickels) txtCents.Text = CStr(cents) End Sub
Instructor Solutions Manual (Page 35 of 221)
4. Private Sub btnConvert_Click(...) Handles btnConvert.Click Dim totalInches As Double Dim totalMeters As Double Dim meters, kilometers As Double Dim centimeters As Double 'Step #1: Add up given measurements into inches totalInches = CDbl(txtInches.Text) 'inches box totalInches += 12 * CDbl(txtFeet.Text) 'add in feet totalInches += 36 * CDbl(txtYards.Text) 'add in yards totalInches += 63360 * CDbl(txtMiles.Text) 'add in miles 'Step #2: Convert total inches into total meters totalMeters = totalInches / 39.37 'total inches to total meters 'Step #3: Compute kilometers, whole meters, and centimeters 'Step 3a: compute # of kilometers, subtract from meters kilometers = Int(totalMeters / 1000) totalMeters = totalMeters – (1000 * kilometers) 'Put the whole part of totalMeters into meters, 'and the fractional part into centimeters. meters = Int(totalMeters) centimeters = 100 * (totalMeters - meters) centimeters = Math.Round(centimeters, 1) lstOutput.Items.Clear() lstOutput.Items.Add("The metric length is") lstOutput.Items.Add(kilometers & " kilometers") lstOutput.Items.Add(meters & " meters") lstOutput.Items.Add(centimeters & " centimeters.") End Sub
5. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim loanAmount, interestRate, monthlyPayment, i As Double 'i is the monthly interest in decimal form Dim numYears As Integer loanAmount = CDbl(txtAmount.Text) interestRate = CDbl(txtInterest.Text) numYears = CInt(txtYears.Text) i = interestRate / 1200 monthlyPayment = (i / (1 - ((1 + i) ^ (-12 * numYears)))) * loanAmount txtMonthlyPayment.Text = monthlyPayment.ToString("C") End Sub
Instructor Solutions Manual (Page 36 of 221) 6. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim price, pricePerOunce As Double Dim pounds, ounces, weightInOunces As Integer price = CDbl(txtPrice.Text) pounds = CInt(txtPounds.Text) ounces = CInt(txtOunces.Text) weightInOunces = 16 * pounds + ounces pricePerOunce = price / weightInOunces txtUnitPrice.Text = pricePerOunce.ToString("C") End Sub
Instructor Solutions Manual (Page 37 of 221)
CHAPTER 4 EXERCISES 4.1 1. hi
2. C#
3. The letter before G is F
4. B
5. "We're all in this alone." - Lily Tomlin 6. D is the 4th letter of the alphabet.
7. True
8. False
9. True
10. False
11. True
12. False
13. True
14. True
15. False
16. False
17. False
19. True
21. True
22. True
23. False
24. True
25. False
26. True
27. False
28. True
29. True
30. True
31. Equivalent
32. Not Equivalent
33. Not Equivalent
34. Equivalent
35. Equivalent
36. Not Equivalent
37. Not Equivalent
38. Not Equivalent
39. a <= b
40. (a <> b) And (a <> d)
41. (a >= b) Or (c = d)
42. (a = b) Or (a > b)
43. (a = "") Or (a >= b) Or (a.Length >= 5)
44. a > b
[In Exercises 45 through 48, execute a statement of the form txtOutput.Text = CStr(Boolean expression.).] 45. True 46. True
47. True 48. False
49. False
50. True
51. False
52. True
53. True 54. True
55. True 56. False
57. False
58. True
59. True
60. False
EXERCISES 4.2 1. Less than ten.
2. Student
3. tomorrow is another day.
4. Your change contains 3 dollars.
5. 10
6. Cost of call: $11.26
7. To be, or not to be.
8. A is a vowel.
9. Hi
10. positive
11. You are old enough to vote in 7 days.
12. You are younger than Nick.
13. Syntax error. Third line should be If ((1 < num) And (num < 3)) Then
Instructor Solutions Manual (Page 38 of 221)
14. The variable num is missing from the second part of the condition. Should be If ((num > 5) And (num < 9)) Then
15. Syntax error. Fourth line should be If ((major = "Business") Or (major = "Computer Science")) Then
16. Faulty logic. If the user enters "True", the switch changes to "off" and then back to "on". 17. a = 5 18. If j = 7 Then b = 1 Else b = 2 End If 19. message = "Is Alaska bigger than Texas and California combined?" answer = InputBox(message) If (answer.Substring(0, 1).ToUpper = "Y") Then txtOutput.Text = "Correct" Else txtOutput.Text = "Wrong" End If 20. message = "How tall (in feet) is the Statue of Liberty?" feet = CDbl(InputBox(message)) If (feet > 141) And (feet < 161) Then lstOutput.Items.Add("Close") Else lstOutput.Items.Add("Nope") End If lstOutput.Items.Add("The statue is 151 feet from base to torch.") 21. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim cost, tip As Double cost = CDbl(InputBox("Enter cost of meal:")) tip = cost * 0.15 If tip < 1 Then tip = 1 End If txtOutput.Text = tip.ToString("C") End Sub
Instructor Solutions Manual (Page 39 of 221) 22. Private Sub btnCompute_Click(...) Handles btnCompute.Click 'Determine cost of bagels. Dim num As Integer, cost As Double num = CInt(txtNumber.Text) If num < 6 Then cost = 0.75 * num Else cost = 0.6 * num End If txtCost.Text = cost.ToString("C") End Sub
23. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim num, cost As Double num = CDbl(txtNumber.Text) If num < 100 Then cost = 0.25 * num '25 cents each Else cost = 0.2 * num '20 cents each End If txtOutput.Text = cost.ToString("C") End Sub 24. Private Sub btnCompute_Click(...) Handles btnCompute.Click 'Determine cost of copies. Dim num As Integer, cost As Double num = CInt(txtNumber.Text) If num < 100 Then cost = 0.05 * num Else cost = 5 + 0.03 * (num - 100) End If txtCost.Text = cost.ToString("C") End Sub
Instructor Solutions Manual (Page 40 of 221) 25. Private Sub btnAskQuestion_Click(...) Handles btnAskQuestion.Click Dim name As String name = (txtAnswer.Text).ToUpper If name = "WILLARD SCOTT" Then txtOutput.Text = "Correct." Else txtOutput.Text = "Nice try." End If End Sub
26. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim wage, hours, grossPay As Double wage = CDbl(txtHourlyWage.Text) 'Hourly pay hours = CDbl(txtHoursWorked.Text) 'Hours worked If hours <= 40 Then grossPay = wage * hours Else grossPay = (wage * 40) + (1.5 * wage * (hours - 40)) End If txtGrossPay.Text = grossPay.ToString("C") End Sub 27. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim s1, s2, s3 As Double '3 scores Dim avg As Double 'average of the two highest scores s1 = CDbl(txtScore1.Text) s2 = CDbl(txtScore2.Text) s3 = CDbl(txtScore3.Text) If (s1 <= s2) And (s1 <= s3) Then 's1 is smallest number avg = (s2 + s3) / 2 ElseIf (s2 <= s1) And (s2 <= s3) Then 's2 is smallest number avg = (s1 + s3) / 2 Else 's3 is smallest number avg = (s1 + s2) / 2 End If txtAverage.Text = CStr(avg) End Sub
Instructor Solutions Manual (Page 41 of 221)
28. Private Sub btnCompute_Click(...) Handles btnTranslate.Click 'convert to Pig Latin Dim word, firstLetter As String Dim positionOfFirstVowel As Integer word = txtWord.Text.ToLower firstLetter = word.Substring(0, 1) If "aeiou".IndexOf(firstLetter) <> -1 Then word &= "way" Else positionOfFirstVowel = word.Length - 1 If (word.IndexOf("a") <> -1) And (word.IndexOf("a") < positionOfFirstVowel) Then positionOfFirstVowel = word.IndexOf("a") End If If (word.IndexOf("e") <> -1) And (word.IndexOf("e") < positionOfFirstVowel) Then positionOfFirstVowel = word.IndexOf("e") End If If (word.IndexOf("i") <> -1) And (word.IndexOf("i") < positionOfFirstVowel) Then positionOfFirstVowel = word.IndexOf("i") End If If (word.IndexOf("o") <> -1) And (word.IndexOf("o") < positionOfFirstVowel) Then positionOfFirstVowel = word.IndexOf("o") End If If (word.IndexOf("u") <> -1) And (word.IndexOf("u") < positionOfFirstVowel) Then positionOfFirstVowel = word.IndexOf("u") End If word = word.Substring(positionOfFirstVowel) & word.Substring(0, positionOfFirstVowel) & "ay" End If txtOutput.Text = "The word in pig latin is " & word & "." End Sub 29. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim weight, cost, amount, change As Double weight = CDbl(txtWeight.Text) amount = CDbl(txtAmount.Text) cost = weight * 2.5 If (amount >= cost) Then change = amount - cost txtOutput.Text = "Your change is " & change.ToString("C") & "." Else txtOutput.Text = "I need " & (cost - amount).ToString("C") & " more." End If End Sub
Instructor Solutions Manual (Page 42 of 221)
30. Private Sub btnCompute_Click(...) Handles btnCompute.Click 'Savings account withdrawal Dim balance, amountOfWithdrawal As Double balance = CDbl(txtCurrentBalance.Text) amountOfWithdrawal = CDbl(txtWithdrawal.Text) If (balance >= amountOfWithdrawal) Then balance = balance - amountOfWithdrawal txtOutput.Text = "New balance is " & balance.ToString("C") & "." If balance < 150 Then MessageBox.Show("Balance below $150", "Warning") End If Else txtOutput.Text = "Withdrawal denied." End If End Sub 31. Private Sub btnQuit_Click(...) Handles btnQuit.Click 'Quit? Dim answer As String answer = InputBox("Do you really want to quit? (Y/N)") answer = answer.Substring(0, 1).ToUpper If (answer = "Y") Then Me.Close() End If End Sub 32. Private Sub btnCompute_Click(...) Handles lblDetermine.Click 'Test if year is a leap year 'Note: The number n is divisible by 4 if n Mod 4 = 0. Dim yr As Integer yr = CInt(txtYear.Text) If (yr Mod 4 = 0) And ((yr Mod 100 <> 0) Or (yr Mod 400 = 0)) Then txtLeapYear.Text = "YES" Else txtLeapYear.Text = "NO" End If End Sub
Instructor Solutions Manual (Page 43 of 221)
33. Dim numLines As Integer = 0 'In Declarations section of Code Editor 'numLines tells the number of lines that have been displayed. Private Sub btnBogart_Click(...) Handles btnBogart.Click If numLines = 0 Then lstOutput.Items.Add("I came to Casablanca for the waters.") numLines += 1 ElseIf numLines = 2 Then lstOutput.Items.Add("I was misinformed.") numLines += 1 End If End Sub Private Sub btnRaines_Click(...) Handles btnRaines.Click If numLines = 1 Then lstOutput.Items.Add("But we're in the middle of the desert.") numLines += 1 End If End Sub
34. Dim hue As String = "Black" Private Sub btnChangeColor_Click(...) Handles btnChangeColor.Click If hue = "Black" Then txtBox.ForeColor = Color.Red hue = "Red" btnChangeColor.Text = "Change Color of Text to Black" Else txtBox.ForeColor = Color.Black hue = "Black" btnChangeColor.Text = "Change Color of Text to Red" End If End Sub
Instructor Solutions Manual (Page 44 of 221)
35. Private Sub btnConvertToRegular_Click(...) Handles btnConvertToRegular.Click Dim partOfDay As String Dim time As String = mtbMilitary.Text Dim hours As Integer = CInt(time.Substring(0, 2)) Dim minutes As String = time.Substring(2, 2) If hours >= 12 Then partOfDay = "pm" Else partOfDay = "am" End If If time = "0000" Then txtRegular.Text = "midnight" ElseIf time = "1200" Then txtRegular.Text = "noon" ElseIf hours = 0 Or hours = 12 Then txtRegular.Text = "12:" & minutes & " " & partOfDay Else txtRegular.Text = (hours Mod 12) & ":" & minutes & " " & partOfDay End If End Sub
Instructor Solutions Manual (Page 45 of 221) 36. Dim h1, h2 As Double '2 highest test scores, in order 'h1 has highest value of the two Private Sub btnRead_Click(...) Handles btnRead.Click Dim newScore As Double 'Read in a test score newScore = CDbl(txtScore.Text) If newScore > h1 Then h2 = h1 h1 = newScore ElseIf newScore > h2 Then h2 = newScore End If txtScore.Text = "" txtScore.Focus() End Sub Private Sub btndisplay_Click(...) Handles btndisplay.Click 'Show the two highest test scores so far txtHighest.Text = h1 & " " & h2 txtScore.Focus() End Sub 37. Dim numGuesses As Integer = 0 Private Sub btnEvaluate_Click(...) Handles btnEvaluate.Click 'Assume that the Text property of txtNumberOfGuesses 'was set to 0 in the Form Designer numGuesses += 1 txtNumberOfGuesses.Text = CStr(numGuesses) Dim msg As String If txtAnswer.Text.ToUpper.IndexOf("COOLIDGE") <> -1 Then MessageBox.Show("Calvin Coolidge was born on July 4, 1872.", "Correct") Me.Close() ElseIf CInt(numGuesses) = 10 Then msg = "Calvin Coolidge was born on July 4, 1872." MessageBox.Show(msg, "You've Run Out of Guesses") Me.Close() Else If CInt(numGuesses) = 3 Then msg = "He once said, 'If you don't say anything," & " you won't be called upon to repeat it.'" ElseIf CInt(numGuesses) = 7 Then msg = "His nickname was 'Silent Cal.'" Else msg = "Sorry!" End If MessageBox.Show(msg, "Incorrect") End If txtAnswer.Clear() txtAnswer.Focus() End Sub
Instructor Solutions Manual (Page 46 of 221)
38. Private Sub btnCalculateTax_Click(...) Handles btnCalculateTax.Click 'Calculate state income tax Dim income, tax As Double income = CDbl(txtIncome.Text) If income <= 20000 Then tax = 0.02 * income Else If income <= 50000 Then tax = 400 + 0.025 * (income - 20000) Else tax = 1150 + 0.035 * (income - 50000) End If End If txtOutput.Text = "Tax is " & tax.ToString("C") End Sub 39. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim dob As Date = CDate(txtDOB.Text) Dim numDays As Double Dim birthdayToUse As Date birthdayToUse = CDate(dob.Month & "/" & dob.Day & "/" & Today.Year) If birthdayToUse < Today Then birthdayToUse = birthdayToUse.AddYears(1) End If numDays = DateDiff(DateInterval.Day, Today, birthdayToUse) If numDays = 0 Then MessageBox.Show("HAPPY BIRTHDAY") End If txtNumDays.Text = CStr(numDays) txtToday.Text = CStr(Today) End Sub
Instructor Solutions Manual (Page 47 of 221) 40. Private Sub Determine_Click(...) Handles btnDetermine.Click 'DateDiff(DateInterval.Year, d1, d2) uses only the year 'parts of the two dates in its computation. 'lblAnswer.Text = "Twenty-five?" 'lblDays.Text = "Days to wait:" lblDays.Visible = False txtDays.Visible = False Dim dt As Date = CDate(mtbDate.Text) Dim turn25Date = dt.AddYears(25) Dim approximateAge As Double = DateDiff(DateInterval.Year, dt, Today) If Today >= turn25Date Then txtAnswer.Text = "YES" Else txtAnswer.Text = "NO" Dim numDays As Double = DateDiff(DateInterval.Day, Today, turn25Date) lblDays.Visible = True txtDays.Visible = True txtDays.Text = CStr(numDays) End If End Sub 41. Private Sub Determine_Click(...) Handles btnDetermine.Click 'DateDiff(DateInterval.Year, d1, d2) uses only the year 'parts of the two dates in its computation. Dim dt, dt2 As Date Dim approximateAge As Double dt = CDate(mtbDate.Text) approximateAge = DateDiff(DateInterval.Year, dt, Today) dt2 = dt.AddYears(CInt(approximateAge)) If Today < dt2 Then txtAge.Text = CStr(approximateAge - 1) Else txtAge.Text = CStr(approximateAge) End If End Sub
42. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click If lblLanguage.Visible Then lblLanguage.Visible = False btnDisplay.Text = "Show Name of Language" Else lblLanguage.Visible = True btnDisplay.Text = "Hide Name of Language" End If End Sub
Instructor Solutions Manual (Page 48 of 221) 43. Private Sub btnCompute_Click(...) Handles lblDetermine.Click Dim day As String Dim day1, day2 As Date Dim numDays As Double day = "1/1/" & txtYear.Text day1 = CDate(day) day2 = day1.AddYears(1) numDays = DateDiff(DateInterval.Day, day1, day2) If numDays = 366 Then txtLeapYear.Text = "YES" Else txtLeapYear.Text = "NO" End If End Sub
44. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim ipp1, ipp2 As Double Dim apy1, apy2 As Double ipp1 = CDbl(txtRate1.Text) / (100 * CDbl(txtPeriods1.Text)) ipp2 = CDbl(txtRate2.Text) / (100 * CDbl(txtPeriods2.Text)) apy1 = (1 + ipp1) ^ CInt(txtPeriods1.Text) - 1 apy2 = (1 + ipp2) ^ CInt(txtPeriods2.Text) - 1 txtAPY1.Text = apy1.ToString("P3") txtAPY2.Text = apy2.ToString("P3") If apy1 = apy2 Then txtBest.Text = "Neither" ElseIf apy1 < apy2 Then txtBest.Text = "Bank 2" Else txtBest.Text = "Bank 1" End If End Sub
Instructor Solutions Manual (Page 49 of 221) 45. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim gpa As Double = CDbl(txtGPA.Text) Dim honors As String = "" If gpa >= 3.9 Then honors = " summa cum laude." End If If (3.6 <= gpa) And (gpa < 3.9) Then honors = " magna cum laude." End If If (3.3 <= gpa) And (gpa < 3.6) Then honors = " cum laude." End If If (2 <= gpa) And (gpa < 3.3) Then honors = "." End If txtOutput.Text = "You graduated" & honors End Sub
46. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim gpa As Double = CDbl(txtGPA.Text) txtOutput.Text = "" If (2 <= gpa) And (gpa <= 4) Then Dim honors As String = "" If gpa >= 3.9 Then honors = " summa cum laude." ElseIf gpa >= 3.6 Then honors = " magna cum laude." ElseIf gpa >= 3.3 Then honors = " cum laude." ElseIf gpa >= 2 Then honors = "." End If txtOutput.Text = "You graduated" & honors Else MessageBox.Show("GPA must be between 2 and 4.", "Try Again.") End If End Sub
Instructor Solutions Manual (Page 50 of 221)
47. Private Sub btnFind_Click(...) Handles btnFind.Click Dim largestNum As Double = CDbl(txtFirstNum.Text) If CDbl(txtSecondNum.Text) > largestNum Then largestNum = CDbl(txtSecondNum.Text) End If If CDbl(txtThirdNum.Text) > largestNum Then largestNum = CDbl(txtThirdNum.Text) End If txtLargestNum.Text = CStr(largestNum) End Sub
48. Private Sub btnAdd_Click(...) Handles btnAdd.Click Dim num1 As Double = CDbl(txtFirstNum.Text) Dim num2 As Double = CDbl(txtSecondNum.Text) txtOutput.Text = num1 & " + " & num2 & " = " & num1 + num2 End Sub Private Sub btnSubtract_Click(...) Handles btnSubtract.Click Dim num1 As Double = CDbl(txtFirstNum.Text) Dim num2 As Double = CDbl(txtSecondNum.Text) txtOutput.Text = num1 & " - " & num2 & " = " & num1 - num2 End Sub Private Sub btnMultiply_Click(...) Handles btnMultiply.Click Dim num1 As Double = CDbl(txtFirstNum.Text) Dim num2 As Double = CDbl(txtSecondNum.Text) txtOutput.Text = num1 & " x " & num2 & " = " & (num1 * num2) End Sub Private Sub btnDivide_Click(...) Handles btnDivide.Click Dim num1 As Double = CDbl(txtFirstNum.Text) Dim num2 As Double = CDbl(txtSecondNum.Text) txtOutput.Text = num1 & " / " & num2 & " = " & (num1 / num2) End Sub Private Sub input_TextChanged(...) _ Handles txtFirstNum.TextChanged, txtSecondNum.TextChanged txtOutput.Clear() If txtSecondNum.Text = "0" Then btnDivide.Enabled = False End If End Sub
Instructor Solutions Manual (Page 51 of 221)
EXERCISES 4.3 1. The price is $3.75 The price is $3.75
2. case 2 case 1 case 3
3. Mesozoic Era Paleozoic Era ?
4. Incorrect. At age 43, he was the youngest person elected president. Correct. He became president at age 42 when President McKinley was assassinated. 5. The equation has no real solutions. The equation has two solutions. The equation has exactly one solution. 6. Hi Hi
7. Should have a Case clause before the 4th line. 8. Both Case clauses are invalid. The first one should be Case 3 To 10. The second one should have a comma instead of a semicolon. 9. Case nom = "Bob" should be Case "Bob" 10. In Case clause, h should be "h". 11. Logic error: >= "Peach" should be >= "PEACH". Syntax error: "ORANGE TO PEACH" should be "ORANGE" To "PEACH". 12. First Case clause should be Is < 10000 Second Case clause should be Case 10000 To 30000 13. Valid
14. Valid
15. Invalid
16. Invalid
17. Valid
18. Valid
Instructor Solutions Manual (Page 52 of 221) 19. Select Case a Case 1 txtOutput.Text = "one" Case Is > 5 txtOutput.Text = "two" End Select 20. Select Case a Case 1 lstOutput.Items.Add("lambs") lstOutput.Items.Add("eat") Case Is < 4 lstOutput.Items.Add("eat") Case 5, Is > 7 lstOutput.Items.Add("ivy") End Select 21. Select Case a Case 2 txtOutput.Text = "yes" Case Is < 5 txtOutput.Text = "no" End Select
22. Select Case a Case 1, 3 a = 2 Case 2 a = 3 End Select
23. Private Sub btnDescribe_Click(...) Handles btnDescribe.Click Dim percent As Double percent = CDbl(txtPercent.Text) Select Case percent Case 0 To 30 txtOutput.Text = "Clear" Case 31 To 70 txtOutput.Text = "Partly cloudy" Case 71 To 99 txtOutput.Text = "Cloudy" Case 100 txtOutput.Text = "Overcast" Case Else txtOutput.Text = "Percentage must be between 0 and 100." End Select End Sub
Instructor Solutions Manual (Page 53 of 221) 24. Private Sub btnFind_Click(...) Handles btnFind.Click Dim callNumber As Integer callNumber = CInt(txtCallNum.Text) Select Case callNumber Case 100 To 199 txtLocation.Text = "basement" Case 200 To 500, Is > 900 txtLocation.Text = "main floor" Case 700 To 750 txtLocation.Text = "archives" Case 501 To 900 txtLocation.Text = "upper floor" Case Else MessageBox.Show("The call number must be greater than 100.", "Try Again") txtCallNum.Clear() txtCallNum.Focus() End Select End Sub 25. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim shapeNum As Integer Dim radius, length, height, width As Double shapeNum = CInt(mtbSelection.Text) 'Mask is 0 Select Case shapeNum Case 1 radius = CDbl(InputBox("Input the radius of the circle: ")) txtArea.Text = CStr(3.141593 * radius ^ 2) Case 2 length = CDbl(InputBox("Input the length of the parallelogram: ")) height = CDbl(InputBox("Input the height of the parallelogram: ")) txtArea.Text = CStr(length * height) Case 3 length = CDbl(InputBox("Input the length of the kite: ")) width = CDbl(InputBox("Input the width of the kite: ")) txtArea.Text = CStr((length * width) / 2) Case Else MessageBox.Show("Your choice is not valid.", "Try Again.") mtbSelection.Clear() End Select mtbSelection.Focus() End Sub
Instructor Solutions Manual (Page 54 of 221) 26. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim a, b, c, x, totalRev, totalCost As Double a = CDbl(txtMarRev.Text) b = CDbl(txtMarCost.Text) c = CDbl(txtFixedCost.Text) x = CDbl(txtNumUnits.Text) totalRev = a * x totalCost = (b * x) + c Select Case (totalRev - totalCost) Case Is > 0 txtStatus.Text = "PROFIT" Case Is < 0 txtStatus.Text = "LOSS" Case 0 txtStatus.Text = "BREAK EVEN" End Select End Sub 27. Private Sub btnAssign_Click(...) Handles btnAssign.Click Dim score As Integer, letterGrade As String score = CInt(txtNumericalGrade.Text) Select Case score Case 90 To 100 letterGrade = "A" Case 80 To 89 letterGrade = "B" Case 70 To 79 letterGrade = "C" Case 60 To 69 letterGrade = "D" Case 0 To 59 letterGrade = "F" Case Else letterGrade = "Invalid" End Select txtOutput.Text = "The letter grade is " & letterGrade & "." End Sub
28. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim num As Integer, totalCost As Double, cancelled As Boolean If IsNumeric(txtNumber.Text) Then num = CInt(txtNumber.Text) Select Case num Case Is < 10 cancelled = True Case Is < 21 totalCost = 500 * num
Instructor Solutions Manual (Page 55 of 221) Case Is < 31 totalCost = 450 * num Case Else totalCost = 400 * num End Select If cancelled Then txtTotalCost.Text = "Tour Cancelled" Else txtTotalCost.Text = totalCost.ToString("C") End If Else MessageBox.Show("You must enter a number.") End If End Sub 29. Private Sub btnDescribe_Click(...) Handles btnDetermine.Click Dim amountRecovered, payment As Double amountRecovered = CDbl(txtAmount.Text)) Select Case amountRecovered Case Is <= 75000 payment = 0.1 * amountRecovered Case Is <= 100000 payment = 7500 + 0.05 * (amountRecovered - 75000) Case Is > 100000 payment = 8750 + 0.01 * (amountRecovered - 100000) If payment > 50000 Then payment = 50000 End If End Select txtOutput.Text = payment.ToString("C") End Sub
Instructor Solutions Manual (Page 56 of 221) 30. Private Sub btnTranslate_Click(...) Handles btnTranslate.Click Dim abbrev As String 'Translate doctors' abbreviations abbrev = txtAbbreviation.Text 'Translate abbreviation into English Select Case abbrev Case "ac" txtOutput.Text = Chr(34) & abbrev & Chr(34) & " before meals" Case "ad lib" txtOutput.Text = Chr(34) & abbrev & Chr(34) & " freely as needed" Case "bid" txtOutput.Text = Chr(34) & abbrev & Chr(34) & " twice daily" Case "gtt" txtOutput.Text = Chr(34) & abbrev & Chr(34) & " a drop" Case "hs" txtOutput.Text = Chr(34) & abbrev & Chr(34) & " at bedtime" Case "qid" txtOutput.Text = Chr(34) & abbrev & Chr(34) & " four times a day" Case Else txtOutput.Text = "Abbreviation not known." End Select End Sub 31. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim tin As String = mtbTIN.Text Dim finalDigit As String = tin.Substring(3, 1) Dim suffix As String Select Case finalDigit Case "1" suffix = " st" Case "2" suffix = " nd" Case "3" suffix = " rd" Case Else suffix = " th" End Select txtYear.Text = "20" & tin.Substring(0, 2) txtWeek.Text = tin.Substring(2, 2) & suffix End Sub
32. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim income, tax As Double income = CDbl(txtIncome.Text) Select Case income Case Is < 8700 tax = 0.1 * income
Instructor Solutions Manual (Page 57 of 221) Case Is < 35350 tax = 870 + 0.15 * (income - 8700) Case Is < 85650 tax = 4867.5 + 0.25 * (income - 35350) Case Is < 178650 tax = 17442.5 + 0.28 * (income - 85650) Case Is < 388350 tax = 43482.5 + 0.33 * (income - 178650) Case Else tax = 112683.5 + 0.35 * (income - 388350) End Select txtTax.Text = tax.ToString("C") End Sub 33. Private Sub btnEvaluate_Click(...) Handles btnEvaluate.Click Dim amount, cost, costPerOzWithIncrease, costPerOzWithDiscount As Double Dim betterOFfer As String amount = 18 cost = 9 costPerOzWithIncrease = cost / (1.5 * amount) costPerOzWithDiscount = (0.65 * cost) / amount txt50percentMore.Text = costPerOzWithIncrease.ToString("C4") txt35percentDiscount.Text = costPerOzWithDiscount.ToString("C4") Select Case costPerOzWithIncrease - costPerOzWithDiscount Case Is > 0 betterOffer = "35% discount" Case Is < 0 betterOffer = "50% more" Case Else betterOffer = "same value" End Select txtBetterOffer.Text = betterOFfer End Sub
Instructor Solutions Manual (Page 58 of 221) 34. Private Sub btnEvaluate_Click(...) Handles btnEvaluate.Click Dim cost, costWithDoubleDiscount, costWithSingleDiscount As Double Dim betterOFfer As String cost = 100 costWithDoubleDiscount = cost * 0.8 * 0.75 costWithSingleDiscount = cost * 0.6 txt50percentMore.Text = costWithDoubleDiscount.ToString("C") txt35percentDiscount.Text = costWithSingleDiscount.ToString("C") Select Case costWithDoubleDiscount - costWithSingleDiscount Case Is > 0 betterOFfer = "single discount" Case Is < 0 betterOFfer = "double discount" Case Else betterOFfer = "same value" End Select txtBetterOffer.Text = betterOFfer End Sub 35. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim pres, state, trivia, whichBush As String pres = txtLastName.Text Select Case pres.ToUpper Case "CARTER" state = "Georgia" trivia = "The only soft drink served in the Carter " & "White House was Coca-Cola." Case "REAGAN" state = "California" trivia = "His secret service code name was Rawhide." Case "BUSH" state = "Texas" whichBush = InputBox("Are his middle initials HW or W?") Select Case whichBush.ToUpper Case "HW" trivia = "He celebrated his 85th birthday by parachuting " & "out of an airplane." Case "W" trivia = "He once owned the Texas Rangers baseball team." End Select Case "CLINTON" state = "Arkansas" trivia = "In college he did a good imitation of Elvis Presley." Case "OBAMA" state = "Illinois" trivia = "He was the eighth left-handed president." Case Else state = "" trivia = "" End Select If state <> "" Then lstOutput.Items.Clear() lstOutput.Items.Add("President " & pres & "'s" & " home state was " & state & ".") lstOutput.Items.Add(trivia) End If End Sub
Instructor Solutions Manual (Page 59 of 221)
36. Private Sub btnHumor_Click(...) Handles btnHumor.Click Dim num As Integer Dim sentence As String = "" num = CInt(mtbNumber.Text) If (num >= 1) And (num <= 3) Then Select Case num Case 1 sentence = "I can resist everything except temptation." Case 2 sentence = "I just heard from Bill Bailey. He's not coming home." Case 3 sentence = "I have enough money to last the rest of my life," & " unless I buy something." End Select txtOutput.Text = sentence End If mtbNumber.Clear() mtbNumber.Focus() End Sub Private Sub btnInsult_Click(...) Handles btnInsult.Click Dim num As Integer Dim sentence As String = "" num = CInt(mtbNumber.Text) If (num >= 1) And (num <= 3) Then Select Case num Case 1 sentence = "How much would you charge to haunt a house?" Case 2 sentence = "I bet you have no more friends than an alarm clock." Case 3 sentence = "When your IQ rises to 30, sell." End Select txtOutput.Text = sentence End If mtbNumber.Clear() mtbNumber.Focus() End Sub
Instructor Solutions Manual (Page 60 of 221)
Instructor Solutions Manual (Page 61 of 221)
EXERCISES 4.4 1. The word "Income" becomes the caption embedded in the top of GroupBox1. 2. The CheckBox1 check box becomes (or remains) checked. 3. The CheckBox1 check box becomes (or remains) unchecked. 4. The word "Vanilla" becomes the caption following the check box with V as the access key for toggling the check box. 5. The radio button becomes (or remains) unselected. 6. The selected item in the list box is placed into the text box. 7. The radio button’s caption becomes "Clear All" when the Alt key is pressed. 8. The radio button becomes (or remains) selected. 9. RadioButton1.Text = "Yes"
10. CheckBox1.Checked = False
11. CheckBox1.Checked = True
12. RadioButton2.Checked = False
13. RadioButton2 is on and RadioButton1 is off. 14. Neither RadioButton1 nor RadioButton2 are on. 15. Yes 17. Private Sub CheckedChanged(...) Handles _ radDeluxe.CheckedChanged, radSuper.CheckedChanged, chkUpgradedVideo.CheckedChanged, chkModem.CheckedChanged, chkMemory.CheckedChanged If radDeluxe.Checked Or radSuper.Checked Then Dim cost As Double = 0 'Add amounts to the cost based upon selections. If radDeluxe.Checked Then cost += 1000 Else 'Super model cost += 1500 End If If chkUpgradedVideo.Checked Then cost += 200 End If If chkModem.Checked Then cost += 30 End If If chkMemory.Checked Then cost += 120 End If txtTotalCost.Text = cost.ToString("C")
Instructor Solutions Manual (Page 62 of 221) Else MessageBox.Show("You must first select a model!") End If End Sub
18. Private Sub lstTo_SelectedIndexChanged(...) Handles lstTo.SelectedIndexChanged txtFlight.Clear() If lstFrom.Text = lstTo.Text Then MessageBox.Show("The arrival city must differ from the departure city.") lstTo.Text = Nothing End If End Sub Private Sub lstFrom_SelectedIndexChanged(...) Handles lstFrom.SelectedIndexChanged txtFlight.Clear() If lstFrom.Text = lstTo.Text Then MessageBox.Show("The departure city must differ from the arrival city.") lstFrom.Text = Nothing End If End Sub Private Sub btnBook_Click(...) Handles btnBook.Click txtFlight.Clear() If lstFrom.Text <> "" And lstTo.Text <> "" Then txtFlight.Text = "You are flying from " & lstFrom.Text & " to " & lstTo.Text & "." ElseIf lstFrom.Text = "" Then If lstTo.Text <> "" Then MessageBox.Show("You must select a departure city.") Else MessageBox.Show("You must select a departure city and an arrival city.") End If Else MessageBox.Show("You must select an arrival city.") End If End Sub
Instructor Solutions Manual (Page 63 of 221) 19. Private Sub btnVote_Click(...) Handles btnVote.Click If radCandidate1.Checked Then txtVote.Text = "You voted for Kennedy." ElseIf radCandidate2.Checked Then txtVote.Text = "You voted for Nixon." Else txtVote.Text = "You voted for neither." End If End Sub Private Sub btnClear_Click(...) Handles btnClear.Click radCandidate1.Checked = False radCandidate2.Checked = False End Sub
20. Const INAUGURATION_DAY As Date = #1/20/2017# Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim dateOfBirth As Date = CDate(mtbDOB.Text) Dim oldEnough As Boolean = False If dateOfBirth.AddYears(35) <= INAUGURATION_DAY Then oldEnough = True End If If radNbcYes.Checked And rad14YrsYes.Checked And oldEnough Then txtOutput.Text = "You are eligible to run for president in 2016." Else txtOutput.Text = "You are not eligible to run for president in 2016." End If End Sub
Instructor Solutions Manual (Page 64 of 221) 21. Private Sub btnRecord_Click(...) Handles btnRecord.Click Dim majorSelected As Boolean Dim yearSelected As Boolean If lstMajors.Text = "" Then majorSelected = False Else majorSelected = True End If If (radFrosh.Checked Or radSoph.Checked Or radJunior.Checked Or radSenior.Checked) Then yearSelected = True Else yearSelected = False End If If majorSelected And yearSelected Then MessageBox.Show("Information Processed") ElseIf Not majorSelected Then If Not yearSelected Then MessageBox.Show("You must select a Major and a Year.") Else MessageBox.Show("You must select a Major.") End If Else MessageBox.Show("You must select a Year.") End If End Sub 22.(a) Private Sub btnRecord_Click(...) Handles btnRecord.Click If chkOptIn.Checked Then txtOutput.Text = "You will be enrolled in the retirement plan." Else txtOutput.Text = "You have opted out of the retirement plan." End If End Sub
Instructor Solutions Manual (Page 65 of 221) 22.(b) Private Sub btnRecord_Click(...) Handles btnRecord.Click If radYes.Checked Or radNo.Checked Then If radYes.Checked Then txtOutput.Text = "You will be enrolled in the retirement plan." End If If radNo.Checked Then txtOutput.Text = "You have opted out of the retirement plan." End If Else MessageBox.Show("You must make a selection.") End If End Sub
23. Private Sub CheckedChanged(...) Handles _ chkSenior.CheckedChanged, chkBlind.CheckedChanged, chkSpouse.CheckedChanged, chkSpouseBlind.CheckedChanged Dim count As Integer = 0 If chkSenior.Checked Then count += 1 End If If chkBlind.Checked Then count += 1 End If If chkSpouse.Checked Then count += 1 End If If chkSpouseBlind.Checked Then count += 1 End If txtOutput.Text = CStr(count) End Sub
Instructor Solutions Manual (Page 66 of 221) 24. Private Sub btnApply_Click(...) Handles btnApply.Click If radFwhite.Checked Then lblVB.ForeColor = Color.White End If If radFyellow.Checked Then lblVB.ForeColor = Color.Yellow End If If radFred.Checked Then lblVB.ForeColor = Color.Red End If If radFblue.Checked Then lblVB.ForeColor = Color.Blue End If If radBwhite.Checked Then lblVB.BackColor = Color.White End If If radByellow.Checked Then lblVB.BackColor = Color.Yellow End If If radBred.Checked Then lblVB.BackColor = Color.Red End If If radBblue.Checked Then lblVB.BackColor = Color.Blue End If End Sub
Instructor Solutions Manual (Page 67 of 221) 25. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim fee As Double = 0 If radAdult.Checked Or radSenior.Checked Then Dim numExtras As Integer = 0 If chkTennis.Checked Then numExtras += 1 End If If chkLocker.Checked Then numExtras += 1 End If If chkLaundry.Checked Then numExtras += 1 End If If radAdult.Checked Then fee = 100 + numExtras * 25 Else fee = 75 + numExtras * 25 End If txtFee.Text = fee.ToString("C") Else MessageBox.Show("You must select a membership category.") End If End Sub
26. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Const COST_8GB As Double = 3.3 Const COST_16GB As Double = 5.2 Dim quantity As Integer = CInt(txtQuantity.Text) Dim cost, totalCost As Double If rad8GB.Checked Then cost = COST_8GB Else cost = COST_16GB End If Select Case quantity Case Is < 25 totalCost = quantity * cost Case 25 To 49 totalCost = quantity * (0.9 * cost) Case 50 To 99 totalCost = quantity * (0.85 * cost) Case Else totalCost = quantity * (0.8 * cost) End Select txtCost.Text = totalCost.ToString("C")
Instructor Solutions Manual (Page 68 of 221) End Sub 27. Private Sub btnCompute_Click() Handles btnCompute.Click Dim ageOnPlanet, ageInEarthDays, ageInEarthYears As Double Dim dt As Date = CDate(mtbDayOfBirth.Text) Dim nom As String, noResponse As Boolean = False txtToday.Text = Today.ToString("D") ageInEarthDays = DateDiff(DateInterval.Day, dt, Today) ageInEarthYears = ageInEarthDays / 365.26 If radMercury.Checked Then ageOnPlanet = ageInEarthDays / 88 nom = " Mercurian " ElseIf radVenus.Checked Then ageOnPlanet = ageInEarthDays / 224.7 nom = " Venusian " ElseIf radEarth.Checked Then ageOnPlanet = ageInEarthYears nom = " Earth " ElseIf radMars.Checked Then ageOnPlanet = ageInEarthDays / 687 nom = " Martian " ElseIf radJupiter.Checked Then ageOnPlanet = ageInEarthYears / 11.86 nom = " Jovian " ElseIf radSaturn.Checked Then ageOnPlanet = ageInEarthYears / 29.46 nom = " Saturian " ElseIf radUranus.Checked Then ageOnPlanet = ageInEarthYears / 84.07 nom = " Uranian " ElseIf radNeptune.Checked Then ageOnPlanet = ageInEarthYears / 164.8 nom = " Neptunian " Else noResponse = True End If If noResponse Then MessageBox.Show("You must select a planet.") Else txtAgeInDays.Text = ageOnPlanet.ToString("N1") & nom & "years" End If End Sub
Instructor Solutions Manual (Page 69 of 221)
28. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim state, category As String If radCalifornia.Checked Then state = "CALIFORNIA" End If If radIndiana.Checked Then state = "INDIANA" End If If radMississippi.Checked Then state = "MISSISSIPPI" End If If radNewYork.Checked Then state = "NEW YORK" End If If radFlower.Checked Then category = "FLOWER" End If If radNickname.Checked Then category = "NICKNAME" End If If radMotto.Checked Then category = "MOTTO" End If Select Case state Case "CALIFORNIA" Select Case category Case "FLOWER" txtOutput.Text = "Golden poppy" Case "NICKNAME" txtOutput.Text = "Golden State" Case "MOTTO" txtOutput.Text = "Eureka" Case Else txtOutput.Text = "No data for category" End Select Case "INDIANA" Select Case category Case "FLOWER" txtOutput.Text = "Peony" Case "NICKNAME" txtOutput.Text = "Hoosier State"
Instructor Solutions Manual (Page 70 of 221) Case "MOTTO" txtOutput.Text = "Crossroads of America" Case Else txtOutput.Text = "No data for category" End Select Case "MISSISSIPPI" Select Case category Case "FLOWER" txtOutput.Text = "Magnolia" Case "NICKNAME" txtOutput.Text = "Magnolia State" Case "MOTTO" txtOutput.Text = "By valor and arms" Case Else txtOutput.Text = "No data for category" End Select Case "NEW YORK" Select Case category Case "FLOWER" txtOutput.Text = "Rose" Case "NICKNAME" txtOutput.Text = "Empire State" Case "MOTTO" txtOutput.Text = "Ever upward" Case Else txtOutput.Text = "No data for category" End Select Case Else txtOutput.Text = "No data for state" End Select End Sub
Instructor Solutions Manual (Page 71 of 221)
CHAPTER 4 PROGRAMMING PROJECTS 1. Private Sub btnDisplayRates_Click(...) Handles btnDisplayRates.Click 'Display rental rates for Eddie's Equipment Rental lstRates.Items.Clear() lstRates.Items.Add("Price of Equipment Half-day Full-day") lstRates.Items.Add("1. Rug cleaner $16.00 $24.00") lstRates.Items.Add("2. Lawn mower $12.00 $18.00") lstRates.Items.Add("3. Paint sprayer $20.00 $30.00") End Sub Private Sub btnDispayBill_Click(...) Handles btnDispayBill.Click Dim num As Integer Dim duration = "", item = "" Dim cost As Double 'Display a bill for Eddie's Equipment Rental lstBill.Items.Clear() num = CInt(mtbItemNum.Text) duration = mtbDuration.Text 'Compute cost depending on item and duration Select Case num Case 1 item = "Rug cleaner" cost = 16 Case 2 item = "Lawn mower" cost = 12 Case 3 item = "Paint sprayer" cost = 20 Case Else item = "" MessageBox.Show("Not a valid item.") End Select Select Case duration Case "H", "h" duration = "(Half day rental)" Case "F", "f" duration = "(Full day rental)" cost = cost * 1.5 Case Else duration = "" MessageBox.Show("Not a valid duration.") End Select If (item <> "") And (duration <> "") Then 'Display the bill lstBill.Items.Clear() lstBill.Items.Add("Receipt from Eddie's Equipment Rental") lstBill.Items.Add("") lstBill.Items.Add(item & ": " & cost.ToString("C") & " " & duration) lstBill.Items.Add("Deposit: " & (30).ToString("C") lstBill.Items.Add("") lstBill.Items.Add("Total: " & (cost + 30)C End If End Sub
Instructor Solutions Manual (Page 72 of 221)
2. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim food, level As String Dim calories, fat, pct As Double 'Determine if food meets AHA requirement for fat '(less than 30% of calories from fat). lstOutput.Items.Clear() food = txtFood.Text calories = CDbl(txtCalories.Text) fat = CDbl(txtFat.Text) pct = fat * (9 / calories) lstOutput.Items.Add(food & " contains " & pct.ToString("P") & " calories from fat") If pct > 0.3 Then level = "exceeds" Else level = "meets" End If lstOutput.Items.Add(level & " AHA recommendation") End Sub
Instructor Solutions Manual (Page 73 of 221) 3. Private Sub btnAnalyze_Click(...) Handles btnAnalyze.Click Dim p, a As Double, n As Integer Dim r, payment, totalInterest As Double 'Analyze a Mortgage p = CDbl(txtAmount.Text) 'principal a = CDbl(txtIntRate.Text) 'annual interest rate (e.g. 6) n = CInt(txtduration.Text) 'duration of loan If p <= 0 Then MessageBox.Show("Loan amount must be greater than zero") txtAmount.Focus() ElseIf a <= 0 Then MessageBox.Show("Annual interest rate must be greater than zero") txtIntRate.Focus() ElseIf n <= 0 Then MessageBox.Show("Duration of loan must be greater than zero") Else If a < 1 Then 'Assume that the user has entered interest rate 'as a decimal value rather than a percent. 'Redisplay interest as a percentage txtIntRate.Text = Str(100 * a) Else 'Convert percentage to decimal value a = a / 100 End If r = a / 12 'monthly interest rate payment = p * r / (1 - (1 + r) ^ (-n)) totalInterest = n * payment - p txtPayment.Text = payment.ToString("C") txtTotalInt.Text = totalInterest.ToString("C") End If End Sub
Instructor Solutions Manual (Page 74 of 221) 4. Private Sub btnFind_Click(...) Handles btnFind.Click 'Determine roots of a quadratic equation Dim a, b, c As Double 'Input coefficients to quadratic equation. txtSolutions.Clear() a = CDbl(txtA.Text) b = CDbl(txtB.Text) c = CDbl(txtC.Text) If a = 0 Then MessageBox.Show("Give a non-zero value for 'a'.", "Error") txtA.Clear() Else Dim determinant As Double determinant = b ^ 2 - 4 * a * c Select Case determinant Case Is < 0 txtSolutions.Text = "No real solutions." Case Is = 0 txtSolutions.Text = CStr(-b / (2 * a)) Case Else txtSolutions.Text = (-b + Math.Sqrt(determinant)) / (2 * a) & " and " & (-b - Math.Sqrt(determinant)) / (2 * a) End Select End If End Sub
5. Private Sub chkBurgers_CheckedChanged(...) Handles chkBurgers.CheckedChanged If chkBurgers.Checked = True Then grpBurgers.Visible = True Else grpBurgers.Visible = False End If End Sub Private Sub chkFries_CheckedChanged(...) Handles chkFries.CheckedChanged If chkFries.Checked = True Then grpFries.Visible = True Else grpFries.Visible = False End If End Sub
Instructor Solutions Manual (Page 75 of 221) Private Sub chkDrinks_CheckedChanged(...) Handles chkDrinks.CheckedChanged If chkDrinks.Checked = True Then grpDrinks.Visible = True Else grpDrinks.Visible = False End If End Sub Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim totalCost As Double If chkBurgers.Checked Then 'Add cost of burger If radRegular.Checked Then totalCost += 4.19 End If If radCheese.Checked Then totalCost += 4.79 End If If radBacon.Checked Then totalCost += 4.79 End If If radBoth.Checked Then totalCost += 5.39 End If End If If chkFries.Checked Then 'Add cost of fries If radSmall.Checked Then totalCost += 2.39 End If If radMedium.Checked Then totalCost += 3.09 End If If radLarge.Checked Then totalCost += 4.99 End If End If If chkDrinks.Checked Then 'Add cost of drink If radSoda.Checked Then totalCost += 1.69 End If If radWater.Checked Then totalCost += 1.49 End If End If txtCost.Text = totalCost.ToString("C") End Sub
Instructor Solutions Manual (Page 76 of 221)
6. Private Sub txtGPA_Leave(...) Handles txtGPA.Leave txtGPAPoints.Text = "[" & Str(20 * CDbl(txtGPA.Text)) & "]" End Sub Private Sub btnCalculate_Click(...s) Handles btnCalculate.Click 'Calculate an applicants score based on the criteria shown in the form 'Display the score and whether student is admitted Dim sumOfTopHalf, sumOfBottomHalf As Double Dim gpaPoints, satPoints, hsQualityPoints, curriculumPoints As Double gpaPoints = 20 * CDbl(txtGPA.Text) 'Calculate satPoints If radSAT930.Checked Then
Instructor Solutions Manual (Page 77 of 221) satPoints = 6 ElseIf radSAT1010.Checked Then satPoints = 10 ElseIf radSAT1200.Checked Then satPoints = 11 ElseIf radSAT1360.Checked Then satPoints = 12 Else satPoints = 0 End If 'Calculate hsQualityPoints If radHS1.Checked Then hsQualityPoints = 2 ElseIf radHS2.Checked Then hsQualityPoints = 4 ElseIf radHS3.Checked Then hsQualityPoints = 6 ElseIf radHS4.Checked Then hsQualityPoints = 8 ElseIf radHS5.Checked Then hsQualityPoints = 10 Else hsQualityPoints = 0 End If 'Calculate curriculumPoints If radCurNeg2.Checked Then curriculumPoints = -4 ElseIf radCurNeg1.Checked Then curriculumPoints = -2 ElseIf radCur1.Checked Then curriculumPoints = 2 ElseIf radCur2.Checked Then curriculumPoints = 4 ElseIf radCur3.Checked Then curriculumPoints = 6 ElseIf radCur4.Checked Then curriculumPoints = 8 Else curriculumPoints = 0 End If sumOfTopHalf = gpaPoints + satPoints + hsQualityPoints + curriculumPoints 'Now for bottom half Dim geographyPoints, alumniPoints, essayPoints, leadershipPoints, miscPoints As Double 'Calculate geographyPoints Dim geoTotal As Integer geoTotal = 0 If chkGeoStateRes.Checked Then geoTotal = geoTotal + 10 End If If chkGeoUnderCounty.Checked Then geoTotal = geoTotal + 6 End If If chkGeoUnderState.Checked Then geoTotal = geoTotal + 2
Instructor Solutions Manual (Page 78 of 221) End If geographyPoints = geoTotal 'Calculate alumniPoints If chkAlumLegacy.Checked Then alumniPoints = 4 End If If chkAlumOther.Checked Then alumniPoints += 1 End If 'Calculate essayPoints If radEssayVG.Checked Then essayPoints = 1 ElseIf radEssayE.Checked Then essayPoints = 2 ElseIf radEssayO.Checked Then essayPoints = 3 Else essayPoints = 0 End If 'Calculate leadershipPoints leadershipPoints = 0 If chkLeaderState.Checked Then leadershipPoints += 1 End If If chkLeaderRegional.Checked Then leadershipPoints += 2 End If If chkLeaderNational.Checked Then leadershipPoints += 5 End If 'Calculate miscPoints If radMiscSocDisadv.Checked Or radMiscAthlete.Checked Or radMiscDiscretion.Checked Then miscPoints = 20 ElseIf radMiscMaleNurse.Checked Then miscPoints = 5 Else miscPoints = 0 End If 'Calculate the number of points for the bottom half; number at most 40 Dim bottomTotal As Double = geographyPoints + alumniPoints + essayPoints + leadershipPoints + miscPoints If bottomTotal < 40 Then sumOfBottomHalf = bottomTotal Else sumOfBottomHalf = 40 End If Dim score As Double = sumOfTopHalf + sumOfBottomHalf lstResults.Items.Clear() lstResults.Items.Add("Total Score: " & score) lstResults.Items.Add("") If (score >= 100) Then lstResults.Items.Add("Admitted") Else lstResults.Items.Add("Rejected")
Instructor Solutions Manual (Page 79 of 221) End If End Sub
Get complete Order files download link below htps://www.mediafire.com/file/�351cwx7zi5x55/SM+ An+Introduc�on+to+Programming+Using+Visual+Basic +2012,+9e+David+Schneider.zip/file
If this link does not work with a click, then copy the complete Download link and paste link in internet explorer/firefox/google chrome and get all files download successfully.
Instructor Solutions Manual (Page 80 of 221)
CHAPTER 5 EXERCISES 5.1 1. 59
2. You can park about 500 cars.
3. The population will double in 24 years. 5. 27 is an odd number. 8. 15 5
6. Dec
9. age before beauty
4. 3
7. Your state income tax is $150.00. 10. A average
11. The function header should end with "As String", not "As Integer". 12. "len =" should not appear in the Return statement. The last line inside the Function procedure should be Return 2 * w.Length. 13. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click radius = CDbl(txtRadius.Text) height = CDbl(txtHeight.Text) txtAmount.Text = TinArea(radius, height) & " square centimeters" End Sub Function TinArea(radius As Double, ht As Double) As Double 'Calculate surface area of a cylindrical can. Return 6.283 * (radius ^ 2 + radius * ht) End Function
14. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim weight As Double = CDbl(txtWeight.Text) Dim height As Double = CDbl(txtHeight.Text) txtBMI.Text = CStr(BMI(weight, height)) End Sub Function BMI(w As Double, h As Double) As Double Return Math.Round((703 * w) / (h ^ 2)) End Function
Instructor Solutions Manual (Page 81 of 221) 15. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim speed As Double = CDbl(txtSpeed.Text) If Category(speed) = "" Then txtOutcome.Text = "Not a hurricane." Else txtOutcome.Text = "Category " & Category(speed) & " hurricane." End If End Sub Function Category(speed As Double) As String If speed < 74 Then Return "" ElseIf speed <= 95 Then Return "One" ElseIf speed <= 110 Then Return "Two" ElseIf speed <= 130 Then Return "Three" ElseIf speed <= 155 Then Return "Four" Else Return "Five" End If End Function
16. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click 'Calculate exercise heart rate Dim age As Integer, restRate As Double age = CInt(txtAge.Text) restRate = CDbl(txtRestHR.Text) txtTHR.Text = CStr(THR(age, restRate)) End Sub Function THR(age As Integer, restRate As Double) As Double Return (((220 - age) - restRate) * 0.6) + restRate End Function
Instructor Solutions Manual (Page 82 of 221) 17. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim popcorn, butter, bucket, price As Double 'amount in dollars popcorn = CDbl(txtPopcorn.Text) bucket = CDbl(txtBucket.Text) butter = CDbl(txtButter.Text) price = CDbl(txtPrice.Text) txtProfit.Text = (Profit(popcorn, butter, bucket, price)).ToString("C") End Sub Function Profit(popcorn As Double, butter As Double, bucket As Double, price As Double) As Double 'Calculate the profit on a bucket of popcorn Return price - (popcorn + butter + bucket) End Function
18. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim midterm, final As Double midterm = CDbl(txtMidTerm.Text) final = CDbl(txtFinal.Text) txtSemesterGrade.Text = SemesterGrade(midterm, final) End Sub Function SemesterGrade(midTerm As Double, final As Double) As String Dim score As Double = (midTerm + 2 * final) / 3 score = Ceil(score) Select Case score Case Is >= 90 Return "A" Case Is >= 80 Return "B" Case Is >= 70 Return "C" Case Is >= 60 Return "D" Case Else Return "F" End Select End Function Function Ceil(num As Double) As Double Return -Int(-num) End Function
Instructor Solutions Manual (Page 83 of 221) 19. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim weight As Double weight = CDbl(txtWeight.Text) txtOutput.Text = "The cost of mailing the letter was " & (Cost(weight)).ToString("C") & "." End Sub Function Ceil(x As Double) As Double Return -Int(-x) End Function Function Cost(weight As Double) As Double Return 0.05 + 0.1 * Ceil(weight - 1) End Function
20. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim x, y, z As Double x = CDbl(txtNum1.Text) y = CDbl(txtNum2.Text) z = CDbl(txtNum3.Text) txtAverage.Text = CStr(Average(x, y, z)) End Sub Function Average(x As Double, y As Double, z As Double) As Double Return ((x + y + z) / 3) End Function
Instructor Solutions Manual (Page 84 of 221) 21. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim x, y, z As Double x = CDbl(txtNum1.Text) y = CDbl(txtNum2.Text) z = CDbl(txtNum3.Text) txtMaximum.Text = CStr(Maximum(x, y, z)) End Sub Function Maximum(x As Double, y As Double, z As Double) As Double Dim max As Double max = x If y > max Then max = y End If If z > max Then max = z End If Return max End Function
22. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim x, y, z As Double x = CDbl(txtNum1.Text) y = CDbl(txtNum2.Text) z = CDbl(txtNum3.Text) txtMinimum.Text = CStr(Minimum(x, y, z)) End Sub Function Minimum(x As Double, y As Double, z As Double) As Double Dim min As Double min = x If y < min Then min = y End If If z < min Then min = z End If Return min End Function
Instructor Solutions Manual (Page 85 of 221) 23. Private Sub btnAddressNGreet_Click(...) Handles btnAddressNGreet.Click Dim name As String name = txtName.Text lstOutput.Items.Add("The Honorable " & name) lstOutput.Items.Add("United States Senate") lstOutput.Items.Add("Washington, DC 20001") lstOutput.Items.Add("") lstOutput.Items.Add("Dear Senator " & LastName(name) & ",") End Sub Function LastName(name As String) As String Dim spacePos As Integer spacePos = name.IndexOf(" ") Return name.Substring(spacePos + 1) End Function
24. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display monthly savings account balances. Dim balance, amt As Double lstBalance.Items.Clear() amt = CDbl(txtAmount.Text) balance = amt lstBalance.Items.Add("Month 1: " & balance.ToString("C")) balance = NewBalance(balance, amt) lstBalance.Items.Add("Month 2: " & balance.ToString("C")) balance = NewBalance(balance, amt) lstBalance.Items.Add("Month 3: " & balance.ToString("C")) balance = NewBalance(balance, amt) lstBalance.Items.Add("Month 4: " & balance.ToString("C")) End Sub Function NewBalance(oldBal As Double, amt As Double) As Double 'Compute the monthly balance in a 6% interest acct. w/ amt added ea. mo. Return (1.005 * oldBal) + amt End Function
Instructor Solutions Manual (Page 86 of 221) 25. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click If IsLeapYear(CInt(mtbYear.Text)) Then 'mask is 0000 txtOutput.Text = mtbYear.Text & " is a leap year." Else txtOutput.Text = mtbYear.Text & " is not a leap year." End If End Sub Function IsLeapYear(yr As Integer) As Boolean Dim date1 As Date = CDate("#1/1/" & yr & "#") Dim date2 As Date = CDate("#1/1/" & (yr + 1) & "#") If DateDiff(DateInterval.Day, date1, date2) = 366 Then Return True Else Return False End If End Function
26. Private Sub btnDisplay_Click(...) Handles btnDetermine.Click Dim d As Date = CDate(mtbDate.Text) txtOutput.Text = DayOfWeek(d) End Sub Function DayOfWeek(d As Date) As String Dim str As String = FormatDateTime(d, DateFormat.LongDate) Dim n As Integer = str.IndexOf(","c) Return str.Substring(0, n) End Function
EXERCISES 5.2 1. 88 keys on a piano
2. Call me Ishmael.
3. You look dashing in blue.
4. 144 items in a gross
5. 1440 minutes in a day
6. The number of U.S. Senators is 100
7. Why do clocks run clockwise? Because they were invented in the northern hemisphere where sundials go clockwise. 8. The answer is 9W. What is the question? Do you spell your name with a V, Mr. Wagner?
Instructor Solutions Manual (Page 87 of 221)
9. It was the best of times. It was the worst of times. 11. divorced beheaded died divorced beheaded survived 13. 24 blackbirds baked in a pie
10. 168 hours in a week 76 trombones in the big parade
12. President Bush is a graduate of Yale. President Obama is a graduate of Columbia.
14. Keep cool, but don't freeze. Source: A jar of mayonnaise.
15. The first 6 letters are Visual.
16. Answers will vary.
17. Cost: $250.00 Shipping cost: $15.00 Total cost: $265.00
18. Visual Basic
19. You passed with a grade of 92.
20. twentieth century
21. There is a parameter in the Sub procedure, but no argument in the statement calling the Sub procedure. 22. The arguments of the Sub procedure call are out of order. The Double variable number should be first, since the Double parameter in the Sub procedure header is first. 23. Since Handles is a keyword, it cannot be used as the name of a Sub procedure. 24. The Sub procedure Tea() declaration has no parameter to match the argument num in the calling statement. 25. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim num As Integer = 7 Lucky(num) End Sub Sub Lucky(num As Integer) txtOutput.Text = num & " is a lucky number." End Sub 26. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Greet a friend Dim name As String = "Jack" Greet(name) End Sub Sub Greet(name As String) 'Display greeting txtOutput.Text = "Hi, " & name End Sub
Instructor Solutions Manual (Page 88 of 221) 27. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Tallest("redwood", 362) Tallest("pine", 223) End Sub Sub Tallest(tree As String, ht As Double) lstBox.Items.Add("The tallest " & tree & " tree in the U.S. is " & ht & " feet.") End Sub 28. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display information about cities. lstOutput.Items.Clear DisplayData("San Jose", 83089) DisplayData("Hartford", 46000) End Sub Sub DisplayData(city As String, salary As Double) 'Display city information lstOutput.Items.Add("In 2008, the average salary for " & city & " residents was " & salary.ToString("C0") & ".") End Sub 29. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click DisplayHeader() Majors(0.167, "business") Majors(0.01, "computer science") End Sub Sub DisplayHeader() Dim phrase As String phrase = "Intended majors of freshmen:" lstOutput.Items.Add(phrase) End Sub Sub Majors(percentOfStudents As Double, field As String) 'Display the information about the major lstOutput.Items.Add(field & ": " & percentOfStudents.ToString("P")) End Sub
Instructor Solutions Manual (Page 89 of 221) 30. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim dt As Date = CDate(mtbDOB.Text) lstOutput.Items.Clear() AgeInYears(dt) AgeInDays(dt) End Sub Sub AgeInYears(dt As Date) 'DateDiff(DateInterval.Year, d1, d2) uses only the year 'parts of the two dates in its computation. Dim numYears As Integer = CInt(DateDiff(DateInterval.Year, dt1, dt2)) If dt1.AddYears(numYears) > dt2 Then numYears = numYears - 1 End If lstOutput.Items.Add("You are " & numYears & " years old.") End Sub Sub AgeInDays(dt As Date) Dim numDays As Double = DateDiff(DateInterval.Day, dt, Today) lstOutput.Items.Add("You are " & numDays.ToString("N0") & " days old.") End Sub
Instructor Solutions Manual (Page 90 of 221) 31. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Favorite number Dim num As Double lstOutput.Items.Clear() num = CDbl(txtBox.Text) Sum(num) Product(num) End Sub Sub Sum(num As Double) Dim phrase As String phrase = "Sum of favorite number with itself: " lstOutput.Items.Add(phrase & (num + num) & ".") End Sub Sub Product(num As Double) Dim phrase As String phrase = "Product of favorite number with itself: " lstOutput.Items.Add(phrase & (num * num) & ".") End Sub
32. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Enrollments in course lstOutput.Items.Clear() lstOutput.Items.Add("In a recent year,") ShowEnrolled(823, "Spanish") ShowEnrolled(206, "French") End Sub Sub ShowEnrolled(ByVal students As Double, ByVal course As String) 'Display enrollment and course lstOutput.Items.Add(students & " thousand students took a " & course & " course.") End Sub
Instructor Solutions Manual (Page 91 of 221) 33. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click ShowVerse("lamb", "baa") ShowVerse("duck", "quack") ShowVerse("firefly", "blink") End Sub Sub ShowVerse(animal As String, sound As String) 'Display a verse from Old McDonald Had a Farm lstOutput.Items.Add("Old McDonald had a farm. Eyi eyi oh.") lstOutput.Items.Add("And on his farm he had a " & animal & ". Eyi eyi oh.") lstOutput.Items.Add("With a " & sound & " " & sound & " here, and a " & sound & " " & sound & " there.") lstOutput.Items.Add("Here a " & sound & ", there a " & sound & ", everywhere a " & sound & " " & sound & ".") lstOutput.Items.Add("Old McDonald had a farm. Eyi eyi oh.") lstOutput.Items.Add("") End Sub
34. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim occupation As String, amount As Double, percent As Double occupation = txtOccupation.Text amount = CDbl(txtAmount.Text) percent = CDbl(txtPercent.Text) Call DisplayOutput(occupation, amount, percent) End Sub Sub DisplayOutput(occupation As String, amount As Double, percent As Double) Dim tip As Double tip = amount * 0.01 * percent txtOutput.Text = "Tip the " & occupation & " " & tip.ToString("C") End Sub
Instructor Solutions Manual (Page 92 of 221) 35. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim grade1 As Double = CDbl(txtGrade1.Text) Dim grade2 As Double = CDbl(txtGrade2.Text) Dim grade3 As Double = CDbl(txtGrade3.Text) DisplayHighestTwo(grade1, grade2, grade3) End Sub Sub DisplayHighestTwo(grade1 As Double, grade2 As Double, grade3 As Double) Dim first, second As Double first = Max(grade1, grade2) If first = grade1 Then second = Max(grade2, grade3) Else second = Max(grade1, grade3) End If txtOutput.Text = "The highest two grades are " & first & " and " & second & "." End Sub Function Max(num1 As Double, num2 As Double) As Double If num1 <= num2 Then Return num2 Else Return num1 End If End Function
Instructor Solutions Manual (Page 93 of 221) 36. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim fullName = txtName.Text Dim grade1 = CDbl(txtGrade1.Text) Dim grade2 = CDbl(txtGrade2.Text) Dim grade3 = CDbl(txtGrade3.Text) DisplayGrade(fullName, grade1, grade2, grade3) End Sub Sub DisplayGrade(fullName As String, num1 As Double, num2 As Double, num3 As Double) txtOutput.Text = fullName & ": " & SemesterGrade(num1, num2, num3) End Sub Function SemesterGrade(num1 As Double, num2 As Double, num3 As Double) As String Dim average As Double If (num1 <= num2) And (num1 <= num3) Then average = Math.Round((num2 + num3) / 2) ElseIf (num2 <= num1) And (num2 <= num3) Then average = Math.Round((num1 + num3) / 2) Else average = Math.Round((num1 + num2) / 2) End If If average >= 90 Then Return "A" ElseIf average >= 80 Then Return "B" ElseIf average >= 70 Then Return "C" ElseIf average >= 60 Then Return "D" Else Return "F" End If End Function
Instructor Solutions Manual (Page 94 of 221) 37. Private Sub btnAlphabetize_Click(...) Handles btnAlphabetize.Click Dim word1 = txtWord1.Text Dim word2 = txtWord2.Text DisplayWords(word1, word2) End Sub Sub DisplayWords(word1 As String, word2 As String) Dim first, second As String If word1 <= word2 Then first = word1 second = word2 Else first = word2 second = word1 End If lstOutput.Items.Add(first) lstOutput.Items.Add(second) End Sub
EXERCISES 5.3 1. Gabriel was born in the year 1980. 2. The population of the United States is about 315,000,000. 3. The state flower of Alaska is the Forget Me Not. 4. The Artist won the award in 2012. 5. The first 3 letters of EDUCATION are EDU. 6. Original price: $126 Cost: $106
7. sum = 4 difference = 2
8. sales tax: $12.00 profit: $90.00
Instructor Solutions Manual (Page 95 of 221) 9.
Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim firstName As String = "" Dim lastName As String = "" Dim salary, newSalary As Double InputData(firstName, lastName, salary) newSalary = RaisedSalary(salary) DisplayOutput(firstName, lastName, newSalary) End Sub Sub InputData(ByRef firstName As String, ByRef lastName As String, ByRef salary As Double) firstName = txtFirstName.Text lastName = txtLastName.Text salary = CDbl(txtCurrentSalary.Text) End Sub Function RaisedSalary(salary As Double) As Double If salary <= 40000 Then Return 1.05 * salary Else Return salary + 2000 + 0.02 * (salary - 40000) End If End Function Sub DisplayOutput(firstName As String, lastName As String, newSalary As Double) txtOutput.Text = "New salary for " & firstName & " " & lastName & " is " & newSalary.ToString("C") & "." End Sub
Instructor Solutions Manual (Page 96 of 221) 10. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim oldBalance, charges, credits, newBalance, minPayment As Double InputData(oldBalance, charges, credits) CalculateNewValues(oldBalance, charges, credits, newBalance, minPayment) DisplayData(newBalance, minPayment) End Sub Sub InputData(ByRef oldBalance As Double, ByRef charges As Double, ByRef credits As Double) oldBalance = CDbl(txtOldBal.Text) charges = CDbl(txtCharges.Text) credits = CDbl(txtCredits.Text) End Sub Sub CalculateNewValues(oldBalance As Double, charges As Double, credits As Double, ByRef newBalance As Double, ByRef minPayment As Double) newBalance = (1.015) * oldBalance + charges - credits If newBalance <= 20 Then minPayment = newBalance Else minPayment = 20 + 0.1 * (newBalance - 20) End If End Sub Sub DisplayData(newBalance As Double, minPayment As Double) txtNewBal.Text = newBalance.ToString("C") txtMinPayment.Text = minPayment.ToString("C") End Sub
Instructor Solutions Manual (Page 97 of 221) 11. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim annualRateOfInterest, monthlyPayment, begBalance As Double Dim intForMonth, redOfPrincipal, endBalance As Double InputData(annualRateOfInterest, monthlyPayment, begBalance) Calculate(annualRateOfInterest, monthlyPayment, begBalance, intForMonth, redOfPrincipal, endBalance) DisplayData(intForMonth, redOfPrincipal, endBalance) End Sub Sub InputData(ByRef annualRateOfInterest As Double, ByRef monthlyPayment As Double, ByRef begBalance As Double) annualRateOfInterest = CDbl(txtAnnualRateOfInterest.Text) monthlyPayment = CDbl(txtMonthlyPayment.Text) begBalance = CDbl(txtBegBalance.Text) End Sub Sub Calculate(annualRateOfInterest As Double, monthlyPayment As Double, begBalance As Double, ByRef intForMonth As Double, ByRef redOfPrincipal As Double, ByRef endBalance As Double) Dim monthlyRateOfInterest As Double = annualRateOfInterest / 12 intForMonth = (monthlyRateOfInterest / 100) * begBalance redOfPrincipal = monthlyPayment - intForMonth endBalance = begBalance - redOfPrincipal End Sub Sub DisplayData(intForMonth As Double, redOfPrincipal As Double, endBalance As Double) txtIntForMonth.Text = intForMonth.ToString("C") txtRedOfPrincipal.Text = redOfPrincipal.ToString("C") txtEndBalance.Text = endBalance.ToString("C") End Sub
Instructor Solutions Manual (Page 98 of 221) 12. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim hours, payPerHour, overtimeHours, pay As Double InputData(hours, payPerHour) CalculateValues(hours, payPerHour, overtimeHours, pay) DisplayData(overtimeHours, pay) End Sub Sub InputData(ByRef hours As Double, ByRef payPerHour As Double) hours = CDbl(txtHours.Text) payPerHour = CDbl(txtPayPerHour.Text) End Sub Sub CalculateValues(hours As Double, payPerHour As Double, ByRef overtimeHours As Double, ByRef pay As Double) If hours <= 40 Then overtimeHours = 0 pay = hours * payPerHour Else overtimeHours = hours - 40 pay = (40 * payPerHour) + (1.5 * payPerHour * overtimeHours) End If End Sub Sub DisplayData(overtimeHours As Double, pay As Double) txtOvertimeHrs.Text = CStr(overtimeHours) txtPay.Text = pay.ToString("C") End Sub
Instructor Solutions Manual (Page 99 of 221)
CHAPTER 5 PROGRAMMING PROJECTS 1. Dim total As Double Dim numCredits As Integer Private Sub btnRecord_Click(...) Handles btnRecord.Click total += QualityPoints() numCredits += CInt(mtbCredits.Text) mtbGrade.Clear() mtbCredits.Clear() mtbGrade.Focus() End Sub Private Sub btnCalculate_Click(...) Handles btnCalculate.Click txtGPA.Text = (total / numCredits).ToString("N1") End Sub Function QualityPoints() As Integer Dim numericGrade As Integer Dim credits As Integer = CInt(mtbCredits.Text) Dim qualPoints As Integer Select Case mtbGrade.Text Case "A" numericGrade = 4 Case "B" numericGrade = 3 Case "C" numericGrade = 2 Case "D" numericGrade = 1 Case Else numericGrade = 0 End Select qualPoints = numericGrade * credits Return qualPoints End Function
Instructor Solutions Manual (Page 100 of 221) 2. Const PIZZA_PRICE As Double = 1.75 Const FRIES_PRICE As Double = 2 Const DRINKS_PRICE As Double = 1.25 Private Sub btnCompute_Click(...) Handles btnCompute.Click 'Compute a customer's bill Dim pizzaSlices As Double, fries As Double, softDrinks As Double lstOutput.Items.Clear() InputData(pizzaSlices, fries, softDrinks) DisplayBill(pizzaSlices, fries, softDrinks) End Sub Sub DisplayBill(pizzaSlices As Double, fries As Double, softDrinks As Double) 'Display an itemized bill Dim total As Double total = TotalCost(pizzaSlices, fries, softDrinks) lstOutput.Items.Add("ITEM" & " " & "QUANTITY" & " " & "PRICE") lstOutput.Items.Add("pizza slices" & " " & pizzaSlices & " " & (PIZZA_PRICE * pizzaSlices).ToString("C")) lstOutput.Items.Add("fries" & " " & fries & " " & (FRIES_PRICE * fries) .ToString("C")) lstOutput.Items.Add("soft drinks" & " " & softDrinks & " " & (DRINKS_PRICE * softDrinks) .ToString("C")) lstOutput.Items.Add("TOTAL" & " " & total.ToString("C")) End Sub Sub InputData(ByRef pizzaSlices As Double, ByRef fries As Double, ByRef softDrinks As Double) 'Input items pizzaSlices = CDbl(txtPizza.Text) fries = CDbl(txtFries.Text) softDrinks = CDbl(txtDrinks.Text) End Sub Function TotalCost(pizzaSlices As Double, fries As Double, softDrinks As Double) As Double Return (PIZZA_PRICE * pizzaSlices) + (FRIES_PRICE * fries) + (DRINKS_PRICE * softDrinks) End Function
Instructor Solutions Manual (Page 101 of 221) 3. Const COST_PER_CHAIR As Double = 350 Const COST_PER_SOFA As Double = 925 Const SALES_TAX_RATE As Double = 0.05 Private Sub bntProcess_Click(...) Handles bntProcess.Click Dim cost As Double Dim totalCost As Double 'cost + sales tax cost = COST_PER_CHAIR * CDbl(txtChairs.Text) + COST_PER_SOFA * CDbl(txtSofas.Text) totalCost = cost + SALES_TAX_RATE * cost lstInvoice.Items.Clear() lstInvoice.Items.Add("Invoice Number: " & InvoiceNumber()) lstInvoice.Items.Add("") lstInvoice.Items.Add("Name: " & NameInProperOrder()) lstInvoice.Items.Add("Address: " & txtAddress.Text) lstInvoice.Items.Add("City: " & txtCityState.Text) lstInvoice.Items.Add("") lstInvoice.Items.Add("Number of Chairs: " & txtChairs.Text) lstInvoice.Items.Add("Number of Sofas: " & txtSofas.Text) lstInvoice.Items.Add("") lstInvoice.Items.Add(" Cost:" & " " & cost.ToString("C"))) lstInvoice.Items.Add("Sales Tax:" & " " & (SALES_TAX_RATE * cost).ToString("C")) lstInvoice.Items.Add(" ------------") lstInvoice.Items.Add("Total Cost:" & " " & totalCost.ToString("C")) End Sub Private Sub btnClear_Click(...) Handles btnClear.Click txtName.Text = "" txtAddress.Text = "" txtCityState.Text = "" txtChairs.Text = "" txtSofas.Text = "" txtName.Focus() lstInvoice.Items.Clear() End Sub Private Sub btnQuit_Click(...) Handles btnQuit.Click Me.Close() End Sub Private Function InvoiceNumber() As String Dim endOfZip, str As String endOfZip = txtCityState.Text.Substring(txtCityState.Text.Length - 4) str = txtName.Text.Substring(0, 2).ToUpper & endOfZip Return str End Function
Instructor Solutions Manual (Page 102 of 221) Private Function NameInProperOrder() As String Dim name, firstName, lastName As String Dim comma As Integer name = txtName.Text comma = name.IndexOf(",") lastName = name.Substring(0, comma) firstName = name.Substring(comma + 2) Return firstName & " " & lastName End Function
Instructor Solutions Manual (Page 103 of 221) 4. Dim numCorrect As Integer Private Sub btnTakeQuiz_Click(...) Handles btnTakeQuiz.Click 'Test user's appraisals of common sayings numCorrect = 0 'Number of correct answers GiveTest(1) GiveTest(2) GiveTest(3) GiveTest(4) GiveTest(5) GiveTest(6) GiveTest(7) ShowMessage() End Sub Sub GiveTest(numProverb As Integer) 'Administer test and count correct replies Dim saying As String = "" Dim answer As String = "" Dim reply, question As String GetProverb(numProverb, saying, answer) question = "(" & numProverb & ") " & saying & " (T/F)" reply = InputBox(question) If reply.ToUpper = answer Then MessageBox.Show("You're right.", "Question " & numProverb) numCorrect += 1 Else MessageBox.Show("I'm sorry. You're wrong.", "Question " & numProverb) End If End Sub
Instructor Solutions Manual (Page 104 of 221) Sub GetProverb(which As Integer, ByRef proverb As String, ByRef truthVal As String) Select Case which Case 1 proverb = "The squeaky wheel gets the grease." truthVal = "T" Case 2 proverb = "Giving is better than receiving." truthVal = "T" Case 3 proverb = "Opposites attract." truthVal = "F" Case 4 proverb = "Spare the rod and spoil the child." truthVal = "F" Case 5 proverb = "Actions speak louder than words." truthVal = "T" Case 6 proverb = "Flattery will get you nowhere." truthVal = "F" Case 7 proverb = "Marry in haste, repent at leisure." truthVal = "T" End Select End Sub Sub ShowMessage() 'Comment on user's performance Select Case numCorrect Case 7 MessageBox.Show("Perfect. " & numCorrect & " correct") Case 5, 6 MessageBox.Show("Excellent. " & numCorrect & " correct") Case Else MessageBox.Show("You might consider taking Psychology 101. numCorrect & " correct") End Select End Sub
" &
Instructor Solutions Manual (Page 105 of 221) 5. Dim sticksRemaining As Integer Dim sticks As String Private Sub btnRules_Click(...) Handles btnRules.Click Dim message As String message = "You begin by deciding how many matchsticks (between 5 and 50) " & "to place on the pile. Then I will decide who goes first. At each turn, " & "a contestant must take 1, 2, or 3 matchsticks from the pile. " & "The one who takes the last matchstick loses." MessageBox.Show(message, "Rules of the Game") End Sub Private Sub btnBegin_Click(...) Handles btnBegin.Click Dim message As String sticks = "||||||||||||||||||||||||||||||||||||||||||||||||||" message = "How many matchsticks would you like to begin with? " & "Pick a number from 5 to 50." sticksRemaining = CInt(InputBox(message, "Begin the Game")) txtStatus.Text = sticks.Substring(0, sticksRemaining) If sticksRemaining Mod 4 = 1 Then MessageBox.Show("I have decided that you should go first.", "Whose Turn") Else MessageBox.Show("I have decided to go first.", "Whose Turn") ComputerTurn() End If End Sub Private Sub btnPickUpOne_Click(...) Handles btnPickUpOne.Click YourTurn(1) End Sub Private Sub btnPickUpTwo_Click(...) Handles btnPickUpTwo.Click YourTurn(2) End Sub Private Sub btnPickUpThree_Click(...) Handles btnPickUpThree.Click YourTurn(3) End Sub
(continued on next page)
Instructor Solutions Manual (Page 106 of 221) Private Sub ComputerTurn() Dim myPick As Integer Dim sticksRemMod4 As Integer sticksRemMod4 = sticksRemaining Mod 4 Select Case sticksRemMod4 Case 0 myPick = 3 Case 2 myPick = 1 Case 3 myPick = 2 End Select sticksRemaining = sticksRemaining - myPick If sticksRemaining = 1 Then MessageBox.Show("I select " & myPick & " matchsticks. " & "I win.", "Hooray") Else MessageBox.Show("I select " & myPick & " matchsticks. ") End If txtStatus.Text = sticks.Substring(0, sticksRemaining) End Sub Private Sub YourTurn(numberPicked As Integer) If sticksRemaining <> 1 Then sticksRemaining = sticksRemaining - numberPicked txtStatus.Text = sticks.Substring(0, sticksRemaining) If sticksRemaining = 1 Then MessageBox.Show("You win.", "Congratulations") Else ComputerTurn() End If Else Me.Close() End If End Sub
Instructor Solutions Manual (Page 107 of 221) 6. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click If radAmount.Checked And GiveOk(txtRate.Text, txtDuration.Text, txtPayment.Text) Then txtAmount.Text = (PV(CDbl(txtRate.Text) / 1200, CDbl(txtDuration.Text), -CDbl(txtPayment.Text))).ToString("C") ElseIf radRate.Checked And GiveOk(txtAmount.Text, txtDuration.Text, txtPayment.Text) Then txtRate.Text = (1200 * Rate(CDbl(txtDuration.Text), CDbl(txtPayment.Text), -CDbl(txtAmount.Text))).ToString("P") ElseIf radDuration.Checked And GiveOk(txtRate.Text, txtAmount.Text, txtPayment.Text) Then txtDuration.Text = (NPer(CDbl(txtRate.Text) / 1200, CDbl(txtPayment.Text), -CDbl(txtAmount.Text))).ToString("N0") ElseIf radPayment.Checked And GiveOk(txtRate.Text, txtDuration.Text, txtAmount.Text) Then txtPayment.Text = (Pmt(CDbl(txtRate.Text) / 1200, CDbl(txtDuration.Text), -CDbl(txtAmount.Text))).ToString("C") Else MessageBox.Show("No item is checked, a required value is missing or is not numeric.", "Error") End If End Sub Function GiveOk(value1 As String, value2 As String, value3 As String) As Boolean If value1 <> "" And value2 <> "" And value3 <> "" Then If IsNumeric(value1) And IsNumeric(value2) And IsNumeric(value3) Then Return True End If End If End Function
Instructor Solutions Manual (Page 108 of 221)
CHAPTER 6 EXERCISES 6.1 1. 18
2. 24
3. 10
4. 10
5. Maximum number: 7
6. Later than 1950. Earlier than 1970. They appeared on the Ed Sullivan show in February 1964. You answered the question correctly in 3 tries.
7. Infinite loop. (To end the program, click on the Stop Debugging button on the Toolbar.) 8. Loop never terminates. The line n = 1 should appear before the Do loop. 9. Do and Loop are interchanged 11. While num >= 7
12. While name <> "Bob"
13. Until response <> "Y" 15. Until name = ""
14. Until total <> 10 16. While balance < 100
17. Until (a <= 1) Or (a >= 3) 19. While n = 0
10. The keyword Loop is missing.
18. While (ans <> "") And (n <> 0)
20. Until (ans <> "Y") Or (n >= 7)
21. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Request and display three names. Dim name As String, num As Integer = 0 Do While num < 3 name = InputBox("Enter a name:") lstOutput.Items.Add(name) num +=1 Loop End Sub 22. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display number of times question is asked. Dim loopNum As Integer, answer As String = "Y" Do While answer = "Y" loopNum += 1 txtOutput.Text = CStr(loopNum) answer = (InputBox ("Do you want to continue (Y/N)?")).ToUpper Loop End Sub
Instructor Solutions Manual (Page 109 of 221) 23. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim celsius As Double = 10 lstOutput.Items.Add("Celsius Fahrenheit") Do While celsius <= 40 lstOutput.Items.Add(" " & celsius & " " & Fahrenheit(celsius)) celsius += 5 Loop End Sub Function Fahrenheit(celsius As Double) As Double 'Convert Celsius to Fahrenheit Return (9 / 5) * celsius + 32 End Function
24. Private Sub btnBounceBall_Click(...) Handles btnBounceBall.Click 'Drop a ball, and find number of bounces and total distance traveled Dim height, bounceFactor, distance As Double Dim bounces As Integer InputData(height, bounceFactor) BounceBall(height, bounceFactor, bounces, distance) ShowData(bounces, distance) End Sub Sub InputData(ByRef height As Double, ByRef bounceFactor As Double) bounceFactor = CDbl(txtCoefficient.Text) height = CDbl(txtHeight.Text) height = 100 * height 'Convert to centimeters End Sub Sub BounceBall(hght As Double, bFactor As Double, ByRef bounces As Integer, ByRef dist As Double) bounces = 1 'First bounce dist = hght Do While hght * bFactor >= 10 bounces += 1 hght = bFactor * hght dist += 2 * hght 'Up then down again Loop End Sub
Instructor Solutions Manual (Page 110 of 221) Sub ShowData(bounces As Integer, distance As Double) txtBounces.Text = CStr(bounces) txtDistance.Text = (distance / 100).ToString("N") End Sub 25. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim num, max, min As Double Dim count As Double = 0 Dim prompt As String = "Enter a nonnegative number. " & "Enter -1 to terminate entering numbers." num = CDbl(InputBox(prompt)) max = num min = num Do While num >= 0 count += 1 num = CDbl(InputBox(prompt)) If (num <> -1) Then If num < min Then min = num End If If num > max Then max = num End If End If Loop If count > 0 Then txtRange.Text = CStr(max - min) Else MessageBox.Show("No numbers were entered.") End If End Sub
Instructor Solutions Manual (Page 111 of 221) 26. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim num, min As Double Dim count As Double = 0 Dim prompt As String = "Enter a nonnegative number. " & "Enter -1 to terminate entering numbers." num = CDbl(InputBox(prompt)) min = num Do While num >= 0 count += 1 num = CDbl(InputBox(prompt)) If (num <> -1) And (num < min) Then min = num End If Loop If count > 0 Then MessageBox.Show("Smallest number: " & min) Else MessageBox.Show("No numbers were entered.") End If End Sub 27. Private Sub btnFind_Click(...) Handles btnFind.Click Dim m, n, t As Integer InputIntegers(m, n) Do While n <> 0 t = n n = m Mod n 'Remainder after m is divided by n m = t Loop txtOutput.Text = CStr(m) End Sub Sub InputIntegers(ByRef m As Integer, ByRef n As Integer) m = CInt(txtM.Text) n = CInt(txtN.Text) End Sub
Instructor Solutions Manual (Page 112 of 221) 28. Private Sub btnFind_Click(...) Handles btnFind.Click 'Prime factorization Dim n, f As Double lstFactors.Items.Clear() n = CInt(txtNumber.Text) lstFactors.Items.Add("The prime factors of " & n & " are:") f = 2 Do While n > 1 If Int(n / f) = n / f Then 'true if f divides n lstFactors.Items.Add(f) n = n / f Else f += 1 End If Loop End Sub 29. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim dt As Date dt = CDate(txtMonth.Text & "/1/" & txtYear.Text) Do Until dt.ToString("D").StartsWith("Tuesday") dt = dt.AddDays(1) Loop txtDate.Text = dt.ToString("D") End Sub
Instructor Solutions Manual (Page 113 of 221) 30.
Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim amount, annualRate As Double amount = CDbl(txtAmount.Text) annualRate = CDbl(txtRate.Text) If (amount > 0) And (annualRate > 0) Then txtDouble.Text = CStr(DoubleYears(amount, annualRate)) End If End Sub Function DoubleYears(a As Double, r As Double) As Integer Dim bal As Double = a Dim years As Integer = 0 Do While bal < 2 * a bal = (1 + r) * bal years += 1 Loop Return years End Function
Instructor Solutions Manual (Page 114 of 221) 31. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim age As Integer = 1 Do While 1980 + age <> age ^ 2 age += 1 Loop txtOutput.Text = age & " years old" End Sub
32. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click 'Determine the year that the world population will exceed '10 billion, assuming a 1.14% rate of increase Dim yr As Integer, pop As Double yr = 2011 'Start at 2011 pop = 7 'Population of 7 billion Do While pop <= 10 pop = (1.0114) * pop yr += 1 Loop txtOutput.Text = "The world population will reach 10 billion in " & yr & "." End Sub 33. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim amount As Double = 100 Dim yrs As Integer = 0 Do Until amount < 1 amount = 0.5 * amount yrs += 28 Loop txtOutput.Text = yrs & " years" End Sub
Instructor Solutions Manual (Page 115 of 221) 34. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Const CURRENT_CPI As Double = 215.35 Dim cpi As Double = CURRENT_CPI Dim yrs As Integer Do Until cpi >= 2 * CURRENT_CPI cpi = 1.025 * cpi yrs += 1 Loop txtOutput.Text = yrs & " years" End Sub 35. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Const INTEREST_PER_MONTH As Double = 0.005 Const MONTHLY_PAYMENT As Double = 290 Dim loanAmount As Double = 15000 Dim months As Integer = 0 Dim balance As Double = loanAmount Do Until balance < loanAmount / 2 balance = (1 + INTEREST_PER_MONTH) * balance - MONTHLY_PAYMENT months += 1 Loop txtOutput.Text = months & " months" End Sub
36. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim months As Integer = 0 Dim balance As Double = 0 Do Until balance > 3000 balance = 1.0025 * balance + 100 months += 1 Loop txtOutput.Text = months & " months" End Sub 37. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim months As Integer = 0 Dim balance As Double = 10000 Do Until balance < 600 balance = 1.003 * balance - 600 months += 1 Loop txtOutput.Text = months & " months; " & balance.ToString("C") End Sub
Instructor Solutions Manual (Page 116 of 221)
38. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim months As Integer = 0 Dim balance As Double = CDbl(txtInitialDeposit.Text) Do Until balance < 600 balance = 1.003 * balance - 600 months += 1 Loop txtOutput.Text = months & " months" End Sub
Instructor Solutions Manual (Page 117 of 221)
EXERCISES 6.2 1. Pass #1 Pass #2 Pass #3 Pass #4
5. 5 6 7
2. 6 8 10 12
6. -9 -6 -3
3. 2 4 6 8 Who do we appreciate?
7. ••••••••••
8. 6
4. 10 9 8 7 6 5 4 3 2 1 Blastoff 9. 4
10. 4
11. The loop is never executed since 25 is greater than 1 and the step is negative. 12. Next statement is missing. 13. The For ... Next loop will not execute since 20 is greater than 0. You must add Step -1 to the end of the For statement. 14. Since step size is 0.5, the variable j must assume noninteger values such as 1.5. However, j is of type Integer. The word Integer should be replaced with Double. 15. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click For num As Integer = 1 To 9 Step 2 lstBox.Items.Add(num) Next End Sub 16. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click For num As Integer = 1 To 4 lstBox.Items.Add("hello") Next End Sub
Instructor Solutions Manual (Page 118 of 221) 17. Private Sub btnAnalyze_Click(...) Handles btnAnalyze.Click Const DECAY_RATE As Double = 0.12 Dim grams As Double grams = 10 For yearNum As Integer = 1 To 5 grams = (1 - DECAY_RATE) * grams Next lstOutput.Items.Add("Beginning with 10 grams of cobalt 60,") lstOutput.Items.Add(grams.ToString("N") & " grams remain after 5 years.") End Sub
18. Private Sub btnFind_Click(...) Handles btnFind.Click Dim sum As Double = 0 For i As Integer = 1 To 100 sum += i Next txtSum.Text = CStr(sum) End Sub 19. Private Sub btnFind_Click(...) Handles btnFind.Click Dim sum As Double = 0, num as Double = 0 For i As Integer = 1 To 5 num = CDbl(InputBox("Enter #" & i)) sum += num Next txtAverage.Text = (sum / 5).ToString("N") End Sub
20. Private Sub btnFind_Click(...) Handles btnFind.Click Dim num, max As Double num = CDbl(InputBox("Enter #1")) max = num For i As Integer = 2 To 5 num = CDbl(InputBox("Enter #" & i)) If num > max Then max = num End If Next txtAverage.Text = CStr(max) End Sub
Instructor Solutions Manual (Page 119 of 221)
21. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim sum As Double = 0 For denominator As Double = 1 To 100 sum += 1 / denominator Next txtOutput.Text = sum.ToString("N5") End Sub
22. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim n As Integer = CInt(txtDots.Text) Dim row As String = "" For i As Integer = 1 To n row &= Chr(149) Next txtOutput.Text = row End Sub 23. Private Sub btnAnalyze_Click(...) Handles btnAnalyze.Click Dim word As String = txtWord.Text Dim firstLetter, secondLetter As String Dim flag As Boolean = True For i As Integer = 0 To word.Length - 2 firstLetter = word.Substring(i, 1) secondLetter = word.Substring(i + 1, 1) If firstLetter > secondLetter Then txtOutput.Text = "No" Exit For End If If i = word.Length - 2 Then txtOutput.Text = "Yes" End If Next End Sub
Instructor Solutions Manual (Page 120 of 221) 24. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim value As Double = 20000 For i As Integer = 1 To 5 value = 0.85 * value lstOutput.Items.Add(i & ": " & value.ToString("C")) Next End Sub
25. Private Sub btnCompute_Click(...) Handles btnCompute.Click Const PERCENT_RAISE As Double = 0.05 Dim name As String, age As Integer, salary As Double Dim earnings As Double = 0 name = txtName.Text age = CInt(txtAge.Text) salary = CDbl(txtSalary.Text) For i As Integer = age To 64 earnings += salary salary = salary + (PERCENT_RAISE * salary) Next txtOutput.Text = name & " will earn about " & earnings.ToString("C0") & "." End Sub 26. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim amount As Double = 1000 Dim simple, compound As Double lstOutput.Items.Clear() lstOutput.Items.Add(" " & "AMOUNT" & " " & "AMOUNT") lstOutput.Items.Add(" " & "SIMPLE" & " " & "COMPOUND") lstOutput.Items.Add("YEAR " & "INTEREST" & " " & "INTEREST") simple = amount compound = amount For i As Integer = 1 To 9 simple += 0.05 * amount compound = 1.05 * compound lstOutput.Items.Add(i & " " & simple.ToString("C") & " " & compound.ToString("C")) Next End Sub
Instructor Solutions Manual (Page 121 of 221)
27. Private Sub btnComputeIdealWeights_Click(...) Handles _ btnComputeIdealWeights.Click Dim lower, upper As Integer lstWeightTable.Items.Clear() InputBounds(lower, upper) ShowWeights(lower, upper) End Sub Function IdealMan(height As Integer) As Double 'Compute the ideal weight of a man given his height Return 4 * height - 128 End Function Function IdealWoman(height As Integer) As Double 'Compute the ideal weight of a woman given her height Return 3.5 * height - 108 End Function Sub InputBounds(ByRef lower As Integer, ByRef upper As Integer) lower = CInt(InputBox("Enter lower bound on height in inches:")) upper = CInt(InputBox("Enter upper bound on height in inches:")) End Sub Sub ShowWeights(lower As Integer, upper As Integer) lstWeightTable.Items.Add(" " & "WEIGHT " & " " & "WEIGHT") lstWeightTable.Items.Add("HEIGHT" & " " & "WOMEN " & " " & "MEN") For height As Integer = lower To upper lstWeightTable.Items.Add(height & " " & (IdealWoman(height)).ToString("N1") & " " & (IdealMan(height)).ToString("N1")) Next End Sub
Instructor Solutions Manual (Page 122 of 221) 28. Private Sub btnAnalyze_Click(...) Handles btnAnalyze.Click 'Determine number of sibilants in sentence txtOutput.Text = "There are " & Sibilants(txtSentence.Text) & " sibilants in the sentence." End Sub Function Sibilants(sentence As String) As Integer 'Count the number of sibilants (i.e., the letters S and Z) Dim numSibs As Integer Dim letter As String numSibs = 0 For i As Integer = 0 To sentence.Length - 1 letter = sentence.Substring(i, 1).ToUpper If (letter = "S") Or (letter = "Z") Then numSibs += 1 End If Next Return numSibs End Function
29. Private Sub btnAnalyzeOptions_Click(...) Handles btnAnalyzeOptions.Click 'Compare salaries Dim opt1, opt2 As Double opt1 = Option1() opt2 = Option2() lstOutput.Items.Add("Option 1 = " & opt1.ToString("C")) lstOutput.Items.Add("Option 2 = " & opt2.ToString("C")) If opt1 > opt2 Then lstOutput.Items.Add("Option 1 pays better.") ElseIf opt1 = opt2 lstOutput.Items.Add("Options pay the same. Else lstOutput.Items.Add("Option 2 pays better.") End If End Sub Function Option1() As Double 'Compute the total salary for 10 days, 'with a flat salary of $100/day Dim sum As Integer = 0 For i As Integer = 1 To 10 sum += 100 Next Return sum End Function
Instructor Solutions Manual (Page 123 of 221) Function Option2() As Double 'Compute the total salary for 10 days, 'starting at $1 and doubling each day Dim sum As Integer = 0, daySalary As Integer = 1 For i As Integer = 1 To 10 sum += daySalary daySalary = 2 * daySalary Next Return sum End Function 30. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim balance As Double = 15000 Dim yr As Integer = 2010 For i As Integer = 1 To 60 balance = (1.005) * balance - 290 If i Mod 12 = 0 Then If balance < 0 Then balance = 0 End If lstOutput.Items.Add(yr & " " & balance.ToString("C")) yr += 1 End If Next End Sub
31. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim balance As Double = 0 Dim yr As Integer = 2013 For i As Integer = 1 To 120 balance = (1.0025 * balance) + 100 If i Mod 12 = 0 Then lstOutput.Items.Add(yr & " " & balance.ToString("C")) yr += 1 End If Next End Sub
Instructor Solutions Manual (Page 124 of 221) 32. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim word As String = txtWord.Text If IsQwerty(word) Then txtOutput.Text = "Yes" Else txtOutput.Text = "No" End If End Sub Function IsQwerty(word As String) As Boolean Dim n As Integer = word.Length - 1 word = word.ToUpper For i As Integer = 0 To n If Not (word.Substring(i, 1) = "Q" Or word.Substring(i, 1) = "W" Or word.Substring(i, 1) = "E" Or word.Substring(i, 1) = "R" Or word.Substring(i, 1) = "T" Or word.Substring(i, 1) = "Y" Or word.Substring(i, 1) = "U" Or word.Substring(i, 1) = "I" Or word.Substring(i, 1) = "O" Or word.Substring(i, 1) = "P") Then Return False End If Next Return True End Function
33. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click txtNfactorial.Text = CStr(Factorial(CInt(txtN.Text)).ToString("N0")) End Sub Function Factorial(n As Integer) As Double Dim product As Double = 1 For i As Integer = 2 To n product = product * i Next Return product End Function
Instructor Solutions Manual (Page 125 of 221) 34. Private Sub btnGrades_Click(...) Handles btnGrades.Click Dim grade As Integer Dim sum As Integer = 0 Dim lowestGrade As Integer = 100 Dim average As Double For i As Integer = 1 To 5 grade = CInt(InputBox("Enter grade:", "Grade #" & i)) sum += grade If grade < lowestGrade Then lowestGrade = grade End If Next average = (sum - lowestGrade) / 4 txtAverage.Text = average.ToString("N") End Sub
35. Private Sub btnRemove_Click(...) Handles btnRemove.Click Dim phoneNum As String Dim phoneNum2 As String = "" phoneNum = txtPhone.Text For i As Integer = 0 To phoneNum.Length - 1 Dim character As String character = phoneNum.Substring(i, 1) If character <> "-" Then phoneNum2 &= character End If Next txtStrippedPhone.Text = phoneNum2 End Sub
Instructor Solutions Manual (Page 126 of 221) 36. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim numberOfFridays As Integer Dim dt As Date For i As Integer = 1 To 12 dt = CDate(i & "/" & "13/" & mtbYear.Text) If IsFriday(dt) Then numberOfFridays += 1 End If Next txtNumberOfFridays.Text = CStr(numberOfFridays) End Sub Function IsFriday(x As Date) As Boolean Dim dt As String = x.ToString("D") If dt.StartsWith("Friday") Then Return True Else Return False End If End Function
37. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim numberOfFridays As Integer Dim dt As Date For i As Integer = 2000 To 2999 For j As Integer = 1 To 12 dt = CDate(j & "/" & "13/" & i) If IsFriday(dt) Then numberOfFridays += 1 End If Next Next txtNumberOfFridays.Text = CStr(numberOfFridays) End Sub Function IsFriday(x As Date) As Boolean Dim dt As String = x.ToString("D") If dt.StartsWith("Friday") Then Return True Else Return False End If End Function
Instructor Solutions Manual (Page 127 of 221) 38. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim msg As String = "Enter sales for year " Dim sales As Double Dim sum As Double Dim numYears As Integer = CInt(txtEndYr.Text) - CInt(txtBegYr.Text) + 1 lstOutput.Items.Add("Sales in Millions") For yr As Integer = CInt(txtBegYr.Text) To CInt(txtEndYr.Text) sales = CDbl(InputBox(msg & yr & ".")) sum += sales lstOutput.Items.Add(yr & " " & ProduceBar(CInt(sales)) & " " & sales) Next txtAverage.Text = (sum / numYears).ToSTring("C") & " million" End Sub Function ProduceBar(num As Integer) As String Dim bar As String = "" For i As Integer = 1 To num bar &= Chr(149) Next Return bar End Function
39. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim price, quantity As Double lstOutput.Items.Clear() quantity = 80 'current crop of soybeans in millions of bushels lstOutput.Items.Add("YEAR" & " " & "QUANTITY" & " " & "PRICE") For yr As Integer = 2012 To 2022 price = 20 - 0.1 * quantity lstOutput.Items.Add(yr & " " & quantity.ToString("N") & " " & price.ToString("C")) quantity = 5 * price - 10 Next End Sub
Instructor Solutions Manual (Page 128 of 221)
EXERCISES 6.3 1. Mozart 5. 3 11. 300
2. chopin 6. 2
7. 80
3. Tchaikovsky 8. 70
9. 70
4. Mozart 10. 1
12. 60
13. Private Sub btnCount_Click(...) Handles btnCount.Click Dim numWon As Integer = 0 For i As Integer = 0 To lstBox.Items.Count - 1 If CStr(lstBox.Items(i)) = "USC" Then numWon += 1 End If Next txtOutput.Text = CStr(numWon) End Sub
14. Private Sub lstBox_SelectedIndexChanged(...) Handles lstBox.SelectedIndexChanged Dim college As String = lstBox.Text Dim numWon As Integer = 0 For i As Integer = 0 To lstBox.Items.Count - 1 If CStr(lstBox.Items(i)) = college Then numWon += 1 End If Next txtOutput.Text = CStr(numWon) End Sub 15. Private Sub btnCount_Click(...) Handles btnDetermine.Click Dim college As String = txtCollege.Text txtOutput.Clear() For i As Integer = 0 To lstBox.Items.Count - 1 If CStr(lstBox.Items(i)) = college Then txtOutput.Text = "YES" Exit For End If Next If txtOutput.Text = "" Then txtOutput.Text = "NO" End If End Sub
Instructor Solutions Manual (Page 129 of 221) or Private Sub btnCount_Click(...) Handles btnDetermine.Click Dim college As String = txtCollege.Text Dim i As Integer = 0 Dim found As Boolean = False Do Until (found = True) Or (i = lstBox.Items.Count) If CStr(lstBox.Items(i)) = college Then found = True End If i += 1 Loop If found Then txtOutput.Text = "YES" Else txtOutput.Text = "NO" End If End Sub
16. Private Sub btnCount_Click(...) Handles btnDetermine.Click Dim college As String = txtCollege.Text Dim i As Integer = 0 Dim found As Boolean = False Do Until (college <= CStr(lstBox.Items(i))) Or (i = lstBox.Items.Count - 1) i += 1 Loop If CStr(lstBox.Items(i)) = college Then found = True End If If found Then txtOutput.Text = "YES" Else txtOutput.Text = "NO" End If End Sub
Instructor Solutions Manual (Page 130 of 221) 17. Private Sub btnReverse_Click(...) Handles btnReverse.Click Dim highestIndex As Integer = lstBox.Items.Count - 1 For i As Integer = highestIndex To 0 Step -1 lstBox2.Items.Add(lstBox.Items(i)) Next End Sub
18. Private Sub btnRemove_Click(...) Handles btnRemove.Click Dim highestIndex As Integer = lstBox.Items.Count - 1 Dim college As String lstBox2.Sorted = True For i As Integer = 0 To highestIndex college = CStr(lstBox.Items(i)) If lstBox2.Items.IndexOf(college) = -1 Then lstBox2.Items.Add(college) End If Next End Sub 19. Private Sub btnAlphabetize_Click(...) Handles btnAlphabetize.Click lstBox2.Sorted = True Dim highestIndex As Integer = lstBox.Items.Count - 1 For i As Integer = 0 To highestIndex lstBox2.Items.Add(lstBox.Items(i)) Next End Sub
20. Private Sub btnAlphabetize_Click(...) Handles btnAlphabetize.Click lstBox.Sorted = True Dim highestIndex As Integer = lstBox.Items.Count - 1 For i As Integer = highestIndex To 0 Step -1 lstBox2.Items.Add(lstBox.Items(i)) Next End Sub
Instructor Solutions Manual (Page 131 of 221)
21. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim highestIndex As Integer = lstBox.Items.Count - 1 Dim state As String For i As Integer = 0 To highestIndex state = CStr(lstBox.Items(i)) If state.Length = 7 Then lstBox2.Items.Add(state) End If Next End Sub
22. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim numberOfStates As Integer = lstBox.Items.Count Dim i As Integer Dim foundFlag As Boolean = False Dim state As String Do Until (i = numberOfStates) Or (foundFlag = True) state = CStr(lstBox.Items(i)) If state.Length = 7 Then txtOutput.Text = state foundFlag = True End If i += 1 Loop End Sub
Instructor Solutions Manual (Page 132 of 221) 23. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim highestIndex As Integer = lstBox.Items.Count - 1 Dim state As String For i As Integer = 0 To highestIndex state = CStr(lstBox.Items(i)) If state.StartsWith("New") Then txtOutput.Text = state Exit For End If Next End Sub
24. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim highestIndex As Integer = lstBox.Items.Count - 1 Dim state As String For i As Integer = 0 To highestIndex state = CStr(lstBox.Items(i)) If state.StartsWith("New") Then lstBox2.Items.Add(state) End If Next End Sub
Instructor Solutions Manual (Page 133 of 221) 25. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim highestIndex As Integer = lstBox.Items.Count - 1 Dim maxLength As Integer = 0 Dim state As String For i As Integer = 0 To highestIndex state = CStr(lstBox.Items(i)) If state.Length > maxLength Then maxLength = state.Length End If Next For i As Integer = 0 To highestIndex state = CStr(lstBox.Items(i)) If state.Length = maxLength Then lstBox2.Items.Add(state) End If Next End Sub
26. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim highestIndex As Integer = lstBox.Items.Count - 1 Dim minLength As Integer = 100 Dim state As String For i As Integer = 0 To highestIndex state = CStr(lstBox.Items(i)) If state.Length < minLength Then minLength = state.Length End If Next For i As Integer = 0 To highestIndex state = CStr(lstBox.Items(i)) If state.Length = minLength Then lstBox2.Items.Add(state) End If Next End Sub
Instructor Solutions Manual (Page 134 of 221) 27. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim highestIndex As Integer = lstBox.Items.Count - 1 Dim state As String For i As Integer = 0 To highestIndex state = CStr(lstBox.Items(i)) If NumberOfVowels(state) = 4 Then lstBox2.Items.Add(state) End If Next End Sub Function NumberOfVowels(word As String) As Integer Dim numVowels As Integer = 0 word = word.ToUpper Dim letter As String Dim numLetters As Integer = word.Length For i As Integer = 0 To (numLetters - 1) letter = word.Substring(i, 1) If (letter = "A") Or (letter = "E") Or (letter = "I") Or (letter = "O") Or (letter = "U") Then numVowels += 1 End If Next Return numVowels End Function
28. Private Sub lstBox_SelectedIndexChanged(...) Handles lstBox.SelectedIndexChanged Dim state As String = lstBox.Text txtOutput.Text = NumberOfVowels(state) & " letters are vowels" End Sub Function NumberOfVowels(word As String) As Integer Dim numVowels As Integer = 0 word = word.ToUpper Dim letter As String Dim numLetters As Integer = word.Length For i As Integer = 0 To (numLetters - 1) letter = word.Substring(i, 1) If (letter = "A") Or (letter = "E") Or (letter = "I") Or (letter = "O") Or (letter = "U") Then numVowels += 1 End If Next Return numVowels End Function
Instructor Solutions Manual (Page 135 of 221) 29. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim highestIndex As Integer = lstBox.Items.Count - 1 Dim state As String Dim maxNumOfVowels = 0 For i As Integer = 0 To highestIndex state = CStr(lstBox.Items(i)) If NumberOfVowels(state) > maxNumOfVowels Then maxNumOfVowels = NumberOfVowels(state) End If Next txtOutput.Text = CStr(maxNumOfVowels) End Sub Function NumberOfVowels(word As String) As Integer Dim numVowels As Integer = 0 word = word.ToUpper Dim letter As String Dim numLetters As Integer = word.Length For i As Integer = 0 To (numLetters - 1) letter = word.Substring(i, 1) If (letter = "A") Or (letter = "E") Or (letter = "I") Or (letter = "O") Or (letter = "U") Then numVowels += 1 End If Next Return numVowels End Function
30. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim highestIndex As Integer = lstBox.Items.Count - 1 Dim state As String Dim numStates As Integer = 0 For i As Integer = 0 To highestIndex state = CStr(lstBox.Items(i)) If state.IndexOf(" ") <> -1 Then numStates += 1 End If Next txtOutput.Text = CStr(numStates) End Sub
Instructor Solutions Manual (Page 136 of 221) 31. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click txtOutput.Text = CStr(lstBox.Items(0)) End Sub
32. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim numStates As Integer = lstBox.Items.Count txtOutput.Text = CStr(lstBox.Items(numStates - 1)) End Sub 33. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click txtOutput.Text = CStr(lstBox.Items(4)) End Sub
34. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click For i As Integer = 0 To 12 lstBox2.Items.Add(lstBox.Items(i)) Next End Sub
Instructor Solutions Manual (Page 137 of 221) 35. Private Sub btnRecord_Click(...) Handles btnRecord.Click lstGrades.Items.Add(txtGrade.Text) txtGrade.Clear() txtGrade.Focus() End Sub Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim sum As Double = 0 Dim minGrade As Double = 100 If lstGrades.Items.Count > 0 Then For i As Integer = 0 To lstGrades.Items.Count - 1 sum += CDbl(lstGrades.Items(i)) If CDbl(lstGrades.Items(i)) < minGrade Then minGrade = CDbl(lstGrades.Items(i)) End If Next Else MessageBox.Show("You must first enter some grades.") End If txtAverage.Text = (sum / lstGrades.Items.Count).ToString("N") txtLowest.Text = CStr(minGrade) End Sub
Instructor Solutions Manual (Page 138 of 221) 36. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim sum As Double = 0 Dim sum2 As Double = 0 Dim maxGrade As Double = 0 Dim aveGrade As Double Dim numGrades As Integer = lstGrades.Items.Count If lstGrades.Items.Count > 0 Then 'condition is True when ' the list box is nonempty For i As Integer = 0 To numGrades - 1 sum += CDbl(lstGrades.Items(i)) If CDbl(lstGrades.Items(i)) > maxGrade Then maxGrade = CDbl(lstGrades.Items(i)) End If Next Else MessageBox.Show("You must first enter some grades.") End If aveGrade = sum / numGrades For i As Integer = 0 To (numGrades - 1) sum2 += (CDbl(lstGrades.Items(i)) - aveGrade) ^ 2 Next txtAverage.Text = aveGrade.ToString("N") txtHighest.Text = CStr(maxGrade) txtStandardDev.Text = CStr(Math.Sqrt(sum2 / numGrades)) End Sub
Instructor Solutions Manual (Page 139 of 221) 37. Private Sub btnRecord_Click(...) Handles btnRecord.Click lstGrades.Items.Add(txtGrade.Text) txtGrade.Clear() txtGrade.Focus() End Sub Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim sum As Double = 0 Dim maxGrade As Double = 0 Dim minGrade As Double = 100 If lstGrades.Items.Count > 0 Then For i As Integer = 0 To lstGrades.Items.Count - 1 sum += CDbl(lstGrades.Items(i)) If CDbl(lstGrades.Items(i)) > maxGrade Then maxGrade = CDbl(lstGrades.Items(i)) End If If CDbl(lstGrades.Items(i)) < minGrade Then minGrade = CDbl(lstGrades.Items(i)) End If Next Else MessageBox.Show("You must first enter some grades.") End If txtAverage.Text = (sum / lstGrades.Items.Count).ToString("N") txtRange.Text = CStr(maxGrade - minGrade) End Sub
Instructor Solutions Manual (Page 140 of 221) 38. Private Sub btnRecord_Click(...) Handles btnRecord.Click lstGrades.Items.Add(txtGrade.Text) txtGrade.Clear() txtGrade.Focus() End Sub Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim sum As Double = 0 Dim averageGrade As Double = 0 Dim numAboveAverage As Integer = 0 If lstGrades.Items.Count > 0 Then 'condition is True when 'the list box is nonempty For i As Integer = 0 To lstGrades.Items.Count - 1 sum += CDbl(lstGrades.Items(i)) Next Else MessageBox.Show("You must first enter some grades.") End If averageGrade = sum / lstGrades.Items.Count For i As Integer = 0 To lstGrades.Items.Count - 1 If CDbl(lstGrades.Items(i)) > averageGrade Then numAboveAverage += 1 End If Next txtAverage.Text = CStr(averageGrade) txtAboveAverage.Text = CStr(numAboveAverage) End Sub
Instructor Solutions Manual (Page 141 of 221) 39. Private Sub btnSearch_Click(...) Handles btnSearch.Click Dim letters As String = mtbFirstTwoLetters.Text.ToUpper Dim i As Integer = 49 'index of the state currently considered Do Until (CStr(lstStates.Items(i)).ToUpper <= letters) Or (i = 0) i = i - 1 Loop If CStr(lstStates.Items(i + 1)).ToUpper.StartsWith(letters) Then txtOutput.Text = CStr(lstStates.Items(i + 1)) & " begins with " & mtbFirstTwoLetters.Text & "." ElseIf CStr(lstStates.Items(0)).ToUpper.StartsWith(letters) Then txtOutput.Text = CStr(lstStates.Items(0)) & " begins with " & mtbFirstTwoLetters.Text & "." Else txtOutput.Text = "No state begins with " & mtbFirstTwoLetters.Text & "." End If End Sub
Instructor Solutions Manual (Page 142 of 221)
CHAPTER 6 PROGRAMMING PROJECTS 1. Const CAFFEINE_PER_CUP As Double = 130 Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim amount As Double = CAFFEINE_PER_CUP Dim hrs As Integer Do Until amount <= CAFFEINE_PER_CUP / 2 amount = 0.87 * amount hrs += 1 Loop txt65.Text = hrs & " hours" amount = CAFFEINE_PER_CUP For i As Integer = 1 To 24 amount = 0.87 * amount Next txtOne24.Text = amount.ToString("N") & " mg." amount = CAFFEINE_PER_CUP For i As Integer = 1 To 24 amount = 0.87 * amount + CAFFEINE_PER_CUP Next txtMany24.Text = amount.ToString("N") & " mg." End Sub
2. Private Sub btnEvaluate_Click(...) Handles btnEvaluate.Click 'Evaluate Rule of 72 Dim years As Integer Dim amt As Double lstOutput.Items.Clear() For intRate As Integer = 1 To 20 amt = 100 years = 0 Do While amt < 200 years += 1 amt = (1 + intRate / 100) * amt Loop lstOutput.Items.Add("Interest rate: " & (intRate / 100).ToString("P0")) lstOutput.Items.Add("Rule of 72 doubling time: " & Math.Round(72 / intRate)) lstOutput.Items.Add("Actual doubling time: " & years) lstOutput.Items.Add("") Next End Sub
Instructor Solutions Manual (Page 143 of 221) 3. Private Sub btnMaxHeight_Click(...) Handles btnMaxHeight.Click Dim h0, v0 As Double lstOutput.Items.Clear() InputData(h0, v0) lstOutput.Items.Add("The maximum height is ") lstOutput.Items.Add(HeightOfBall(h0, v0, v0 / 32) & " feet") End Sub Private Sub btnApproxTime_Click(...) Handles btnApproxTime.Click Dim h0, v0 As Double lstOutput.Items.Clear() InputData(h0, v0) lstOutput.Items.Add("The ball will hit the ground after") lstOutput.Items.Add("approximately " & TimeToHit(h0, v0) & " seconds.") End Sub Private Sub btnTable_Click(...) Handles btnTable.Click Dim h0, v0 As Double lstOutput.Items.Clear() InputData(h0, v0) ShowHeights(h0, v0) End Sub Private Sub btnQuit_Click(...) Handles btnQuit.Click Me.Close() End Sub Function HeightOfBall(h0 As Double, v0 As Double, t As Double) As Double 'Return height at time t Return h0 + v0 * t - 16 * t * t End Function Sub InputData(ByRef h0 As Double, ByRef v0 As Double) 'Input the initial height and velocity h0 = CDbl(txtInitialHeight.Text) v0 = CDbl(txtInitialVelocity.Text) End Sub Sub ShowHeights(h0 As Double, v0 As Double) 'Create table of heights Dim t, height As Double lstOutput.Items.Add(" " & "TIME" & " " & "HEIGHT") t = 0 height = HeightOfBall(h0, v0, t) Do lstOutput.Items.Add(" " & t.ToString("N") & " " & height.ToString("N1")) t += 0.25 height = HeightOfBall(h0, v0, t) Loop Until (t > 5) Or (height < 0) End Sub
Instructor Solutions Manual (Page 144 of 221) Function TimeToHit(h0 As Double, v0 As Double) As Double 'Determine seconds until ball hits ground Dim t As Double = 0.01 Do While HeightOfBall(h0, v0, t) > 0 t += 0.1 Loop Return t End Function
4. Private Sub btnStrLine_Click(...) Handles btnStrLine.Click Dim item As String = "" Dim purchYear As Integer Dim cost As Double, numYears As Integer InputData(item, purchYear, cost, numYears) ShowDepSchedule(item, purchYear, cost, numYears, 1) End Sub Private Sub btnDoubleDecl_Click(...) Handles btnDoubleDecl.Click Dim item As String = "" Dim purchYear As Integer Dim cost As Double, numYears As Integer InputData(item, purchYear, cost, numYears) ShowDepSchedule(item, purchYear, cost, numYears, 2) End Sub Sub InputData(ByRef item As String, ByRef purchYear As Integer, ByRef cost As Double, ByRef numYears As Integer) item = txtDesc.Text purchYear = CInt(txtYear.Text) cost = Val(txtCost.Text) numYears = CInt(txtNumYears.Text) End Sub Sub ShowHeading(item As String, purchYear As Integer, cost As Double, numYears As Integer, depType As Integer) Dim method As String lstOutput.Items.Add("Description: " & item)
Instructor Solutions Manual (Page 145 of 221) lstOutput.Items.Add("Year of purchase: " & purchYear) lstOutput.Items.Add("Cost: " & cost.ToString("C")) lstOutput.Items.Add("Estimated life: " & numYears) If depType = 1 Then method = "straight-line" Else method = "double-declining balance" End If lstOutput.Items.Add("Method of depreciation: " & method) lstOutput.Items.Add("") End Sub Sub ShowDepSchedule(item As String, purchYear As Integer, cost As Double, numYears As Integer, depType As Integer) Dim depreciation As Double, straightLineDep As Double, totalDeprec As Double Dim value As Double 'Display a depreciation schedule 'If using the "straight-line" method of depreciation, ' the depreciation will be constant (1/nth of original cost) 'If using the "double-declining" method of depreciation, the item will 'depreciate each year by 2/nths of its value at the beginning of the year lstOutput.Items.Clear() ShowHeading(item, purchYear, cost, numYears, depType) 'Initialize value = cost 'value will hold the current value of the item 'For the straight-line method, the depreciation will ' be constant, so we set it here outside the loop If depType = 1 Then straightLineDep = (1 / numYears) * value End If totalDeprec = 0 For yr As Integer = 1 To numYears 'Loop through n years 'Calculate the amount the item will depreciate this year If yr <> numYears Then If depType = 1 Then 'Straight-line -- constant depreciation; 'calculated before entering loop depreciation = straightLineDep Else 'Double declining -' --- 2/nths of value at beginning of year depreciation = 2 / numYears * value End If Else 'In last year, depreciation is the remaining value depreciation = value End If totalDeprec += depreciation 'Show the status before and after taking depreciation lstOutput.Items.Add("Value at beginning of " & purchYear + yr - 1 & ": " & value.ToString("C")) lstOutput.Items.Add("Amount of depreciation during " & purchYear + yr - 1 & ": " & depreciation.ToString("C")) lstOutput.Items.Add("Total depreciation at end of " & purchYear + yr - 1 & ": " & totalDeprec.ToString("C")) lstOutput.Items.Add("") 'Apply the depreciation and move to next year value = value - depreciation Next yr End Sub
Instructor Solutions Manual (Page 146 of 221) 5. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim word As String = txtWord.Text.ToUpper If IsTripleConsecutive(word) Then txtOutput.Text = "YES" Else txtOutput.Text = "NO" End If End Sub Function IsTripleConsecutive(word As String) As Boolean Dim n As Integer = word.Length For i As Integer = 0 To n - 3 Dim threeLetters As String = word.Substring(i, 3) If Asc(threeLetters.Substring(0, 1)) + 1 = Asc(threeLetters.Substring(1, 1)) And Asc(threeLetters.Substring(1, 1)) + 1 = Asc(threeLetters.Substring(2, 1)) Then Return True End If Next Return False End Function
Instructor Solutions Manual (Page 147 of 221) 6. Private Sub btnRemoveParens_Click(...) Handles btnRemoveParens.Click 'Remove parentheses and their contents from a sentence Dim sentence, letter, newSentence As String Dim parensFlag As Boolean, position As Integer sentence = txtSentence.Text newSentence = "" parensFlag = False position = 0 Do Until position > sentence.Length - 1 letter = sentence.Substring(position, 1) Select Case letter Case "(" parensFlag = True Case ")" parensFlag = False position = position + 1 Case Else If parensFlag = False Then newSentence &= letter End If End Select position += 1 Loop txtOutput.Text = newSentence End Sub
Instructor Solutions Manual (Page 148 of 221) 7. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim phrase As String phrase = txtPhrase.Text If IsPalindrome(phrase) Then txtResult.Text = "YES" Else txtResult.Text = "NO" End If End Sub Function IsPalindrome(phrase As String) As Boolean Dim strippedPhrase As String = "", letter As String = "" Dim revStrippedPhrase As String = "" phrase = phrase.ToUpper For i As Integer = 0 To phrase.Length - 1 letter = phrase.Substring(i, 1) If ((letter <> " ") And (letter <> "?")) And ((letter <> Chr(34)) And (letter <> "'") And (letter <> ",") And (letter <> "!") And (letter <> ";") And (letter <> ":") And (letter <> ".")) Then strippedPhrase &= letter End If Next For i As Integer = strippedPhrase.Length - 1 To 0 Step -1 letter = strippedPhrase.Substring(i, 1) revStrippedPhrase &= letter Next If revStrippedPhrase = strippedPhrase Then Return True Else Return False End If End Function
Instructor Solutions Manual (Page 149 of 221) 8. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim balance, earlBalanceAfter15Years, earlBalanceUponRetirement, larryBalanceUponRetirement As Double txtDepositedEarl.Text = (15 * 5000).ToString("C") txtDepositedLarry.Text = (33 * 5000).ToString("C") 'Earl's IRA Amount balance = 0 For i As Integer = 1 To 15 balance = 1.04 * balance + 5000 Next earlBalanceAfter15Years = balance earlBalanceUponRetirement = earlBalanceAfter15Years * (1.04) ^ 33 txtEarlAtRetirement.Text = earlBalanceUponRetirement.ToString("C") 'Larry's IRA Amount balance = 0 For i As Integer = 1 To 33 balance = 1.04 * balance + 5000 Next larryBalanceUponRetirement = balance txtLarryAtRetirement.Text = larryBalanceUponRetirement.ToString("C") End Sub
Instructor Solutions Manual (Page 150 of 221) 9. Private Sub btnSearch_Click(...) Handles btnSearch.Click Dim letters As String = mtbFirstTwoLetters.Text.ToUpper Dim flag As Boolean = False Dim state As String Dim first, middle, last As Integer first = 0 last = lstStates.Items.Count - 1 Do While (Not flag) And (first <= last) middle = CInt((first + last) / 2) Select Case CStr(lstStates.Items(middle)).Substring(0, 2).ToUpper Case letters state = CStr(lstStates.Items(middle)) flag = True Case Is > letters last = middle - 1 Case Is < letters first = middle + 1 End Select Loop If flag Then txtOutput.Text = state & " begins with " & mtbFirstTwoLetters.Text & "." Else txtOutput.Text = "No state begins with " & mtbFirstTwoLetters.Text & "." End If End Sub
Instructor Solutions Manual (Page 151 of 221)
CHAPTER 7 EXERCISES 7.1 1. 101
2. 99
3. Have a dessert spoon.
4. Leaf 1: sunshine Leaf 2: rain Leaf 3: the roses that bloom in the lane Leaf 4: somebody I adore 5. Yes
6. Age of United States: 237
8. Ken
9. You have a trio.
11. Your average is 80
(age will vary; was 237 in 2013)
7. 12
10. A rook is worth more than a bishop
12. Al Gore Gore Vidal Vidal Sassoon
13. Slumdog Millionaire won in 2009
14. 33
15. one,two,three
16. 1,2,3
17. 2 even numbers
18. at least one five-letter word
19. Pearl Harbor: 1941
20. Bicentennial Year: 1976
21. contains a 19th-century date
22. 2 20th-century dates
23. 6 words begin with a vowel
24. 92 100 97
25. 4 6 2
26. SEVEN
27. (a) Superior (last name in alphabetical order) (b) Erie (first name in alphabetical order) (c) Huron (first name in the array) (d) Superior (last name in the array) (e) 5 (number of names in the array) (f) Ontario (second name in the array) (g) 3 (first array subscript whose element is Erie) 28. (a) 32000 (greatest surface area of one of the Great Lakes) (b) 8000 (smallest surface area of one of the Great Lakes) (c) 23000 (first surface area in the array) (d) 32000 (last surface area in the array) (e) 5 (number of surface areas in the array) (f) 95000 (sum of the surface areas of the five Great Lakes) (g) 19000 (average surface area of the five Great Lakes) (h) 22000 (third surface area in the array) (i) 1 (first array subscript whose element is 8000)
Instructor Solutions Manual (Page 152 of 221)
29. (a) 6.5 (greatest population of a New England state) (b) 0.7 (least population of a New England state) (c) 3.5 (first population in the array) (d) 1.3 (last population in the array) (e) 6 (number of numbers in the array) (f) 1.1 (fourth population in the array) (g) 3 (first array subscript whose element is 1.1) 30. (a) Vermont (last name in alphabetical order) (b) Connecticut (first name in alphabetical order) (c) Connecticut (first New England state to join the union) (d) Maine (last New England state to join the union) (e) 6 (number of New England states) (f) Connecticut (first New England state to join the union) (g) 5 (Maine was the sixth NE state to join the union) 31. (a) lstOutput.Items.Add(states.First) or lstOutput.Items.Add(states(0)) (b) For i As Integer = 0 To 12 lstOutput.Items.Add(states(i)) Next (c) lstOutput.Items.Add(states.Last) or lstOutput.Items.Add(states(49)) (d) lstOutput.Items.Add(CStr(Array.IndexOf(states, "Ohio") + 1)) (e) lstOutput.Items.Add(states(1)) (f) lstOutput.Items.Add(states(19)) (g) For i As Integer = (states.Count - 9) To (states.Count) lstOutput.Items.Add(states(i - 1)) Next 32. (a) txtOutput.Text = pres.First 'or txtOutput.Text = pres(0) (b) For i As Integer = 0 To 5 lstoutput.Items.Add(pres(i)) Next (c) txtOutput.Text = pres.Last 'or txtOutput.Text = pres(43) (d) txtOutput.Text = CStr(Array.IndexOf(pres, "James Monroe") + 1) (e) txtOutput.Text = pres(1) (f) txtOutput.Text = pres(9) (g) For i As Integer = (pres.Count - 4) To pres.Count lstoutput.Items.Add(pres(i - 1)) Next 33. Function Task(nums() As Integer) As Integer Dim sum As Integer = 0 For Each num As Integer In nums sum += num Next Return sum End Function
Instructor Solutions Manual (Page 153 of 221) 34. Function Task(nums() As Integer) As Double Dim sum As Integer = 0 For Each As Integer In nums sum += num Next Return sum / nums.Count End Function 35. Function Task(nums() As Integer) As Integer Dim maxEven As Integer = 0 For Each num As Integer In nums If (num Mod 2 = 0) And (num > maxEven) Then maxEven = num End If Next Return maxEven End Function 36. Function Task(nums() As Integer) As Integer Dim min As Integer = nums(0) For Each num As Integer In nums If num < min Then min = num End If Next Return min End Function 37. Function Task(nums() As Integer) As Integer Dim twoDigits As Integer = 0 For Each num As Integer In nums If (num > 9) And (num < 100) Then twoDigits += 1 End If Next Return twoDigits End Function 38. Function Task(nums() As Integer) As Integer Dim numEvens As Integer = 0 For Each num As Integer In nums If (num Mod 2 = 0) Then numEvens += 1 End If Next Return numEvens End Function 39. nums(3) should be changed to nums() 40. Will produce an IndexOutOfRange exception since nums.Count is greater than the upper bound of nums
Instructor Solutions Manual (Page 154 of 221)
41. Logic error. The values of the array elements cannot be altered inside a For Each loop. The
output will be 6. 42. Integer should be changed to String. 43. lstBox.Items.Add(line.Split(" "c).Count) 44. lstBox.Items.Add(IO.File.ReadAllLines("Names.txt").Count) 45. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim numStr() As String = IO.File.ReadAllLines("Numbers.txt") Dim nums(numStr.Count - 1) As Integer For i As Integer = 1 To (nums.Count – 1) nums(i) = CInt(numStr(i)) Next lstOutput.Items.Add("Number of integers in the file: " & nums.Count) lstOutput.Items.Add("Sum of integers in the file: " & nums.Sum) End Sub
46. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim states() As String = IO.File.ReadAllLines("SomeStates.txt") Dim orderedFlag As Boolean = True For i As Integer = 0 To states.Count - 2 If states(i + 1) < states(i) Then orderedFlag = False End If Next If orderedFlag Then txtOutput.Text = "YES" Else txtOutput.Text = "NO" End If End Sub
Instructor Solutions Manual (Page 155 of 221) 47. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim names() As String = IO.File.ReadAllLines("Names2.txt") Dim dups(names.Count - 1) As String Dim n As Integer = 0 'index for dups For i As Integer = 0 To names.Count - 2 If (names(i + 1) = names(i)) And (Array.IndexOf(dups, names(i)) = -1) Then dups(n) = names(i) n += 1 End If Next If n = 0 Then lstOutput.Items.Add("No duplicates.") Else For i As Integer = 0 To n - 1 lstOutput.Items.Add(dups(i)) Next End If End Sub
48. Private Sub btnEvaluate_Click(...) Handles btnEvaluate.Click Dim strGrades() As String = IO.File.ReadAllLines("Final.txt") Dim grades(strGrades.Count - 1) As Double Dim ave As Double Dim counter As Integer For i As Integer = 0 To grades.Count - 1 grades(i) = CDbl(strGrades(i)) Next ave = grades.Average txtAverage.Text = ave.ToString("N") For i As Integer = 0 To grades.Count - 1 If grades(i) > ave Then counter += 1 End If Next txtAboveAve.Text = (counter / grades.Count).ToString("P") End Sub 49. Function Sum(nums() As Integer) As Integer Dim total As Integer = 0 For i As Integer = 1 To nums.Count - 1 Step 2 total += nums(i) Next Return total End Function
Instructor Solutions Manual (Page 156 of 221)
50. Function AreSame(a() As Integer, b() As Integer) As Boolean If a.Count <> b.Count Then Return False Else For i As Integer = 0 To a.Count - 1 If a(i) <> b(i) Then Return False End If Next End If Return True End Function 51. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim lines() As String = IO.File.ReadAllLines("Sonnet.txt") Dim n = lines.Count - 1 Dim numWords(n) As Integer For i As Integer = 0 To n numWords(i) = lines(i).Split(" "c).Count Next lstOutput.Items.Add("Average number of words per line: " & (numWords.Average).ToString("N2")) lstOutput.Items.Add("Total number of words: " & numWords.Sum) End Sub
52. Private Sub btnDisplay_Click( ...) Handles btnDisplay.Click Dim states() As String = IO.File.ReadAllLines("States.txt") Dim newStates(50) As String Dim n As Integer = 0 For Each state As String In states If state.StartsWith("New") Then newStates(n) = state n += 1 End If Next If n > 0 Then ReDim Preserve newStates(n - 1) End If For Each state As String In newStates lstOutput.Items.Add(state) Next End Sub
Instructor Solutions Manual (Page 157 of 221) 53. Private Sub btnProcessEggs_Click(...) Handles btnProcessEggs.Click Dim heaviest, lightest, ounces As Double Dim jumbo, xLarge, large, med, small As Integer heaviest = 0 'can be any number lower than lightest egg lightest = 100 'can be any number greater than heaviest egg Dim strEggs() As String = IO.File.ReadAllLines("Eggs.txt") Dim eggs(strEggs.Count - 1) As Double For i As Integer = 0 To (eggs.Count – 1) eggs(i) = CDbl(strEggs(i)) Next For i As Integer = 0 To (eggs.Count – 1) ounces = eggs(i) If ounces > heaviest Then heaviest = ounces End if If ounces < lightest Then lightest = ounces End If Select Case ounces Case Is < 1.5 'too small & cannot be sold Case Is < 1.75 small += 1 Case Is < 2 med += 1 Case Is < 2.25 large += 1 Case Is < 2.5 xLarge += 1 Case Else jumbo += 1 End Select Next lstOutput.Items.Clear() lstOutput.Items.Add(jumbo & " Jumbo eggs") lstOutput.Items.Add(xLarge & " Extra Large eggs") lstOutput.Items.Add(large & " Large eggs") lstOutput.Items.Add(med & " Medium eggs") lstOutput.Items.Add(small & " Small eggs") If lightest <> 100 Then lstOutput.Items.Add("Lightest egg: " & lightest & " ounces") lstOutput.Items.Add("Heaviest egg: " & heaviest & " ounces") Else lstOutput.Items.Add("File is empty") End If End Sub
Get complete Order files download link below htps://www.mediafire.com/file/�351cwx7zi5x55/SM+ An+Introduc�on+to+Programming+Using+Visual+Basic +2012,+9e+David+Schneider.zip/file
If this link does not work with a click, then copy the complete Download link and paste link in internet explorer/firefox/google chrome and get all files download successfully.
Instructor Solutions Manual (Page 158 of 221)
54. Private Sub btnCalculate_Click( ...) Handles btnCalculate.Click Dim numbers() As String = IO.File.ReadAllLines("Data.txt") Dim nums(numbers.Count - 1) As Double For i As Integer = 0 To nums.Count - 1 nums(i) = CDbl(numbers(i)) Next Dim max As Double = nums(0) Dim min As Double = nums(0) For Each num As Double In nums If num > max Then max = num End If If num < min Then min = num End If txtRange.Text = CStr(max - min) Dim m As Double = nums.Average 'mean txtMean.Text = m.ToString("N3") Dim devs(nums.Count - 1) As Double For i As Integer = 0 To nums.Count - 1 devs(i) = (nums(i) - m) ^ 2 Next txtStDev.Text = (Math.Sqrt(devs.Average)).ToString("N3") Next End Sub
Instructor Solutions Manual (Page 159 of 221) 55. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim strDigits() As String = IO.File.ReadAllLines("Digits.txt") Dim freq(9) As Integer For i As Integer = 0 To strDigits.Count - 1 freq(CInt(strDigits(i))) += 1 Next lstOutput.Items.Add("Digit Frequency") For i As Integer = 0 To 9 lstOutput.Items.Add(" " & i & " " & freq(i)) Next End Sub
56. Dim pres() As String = IO.File.ReadAllLines("USPres.txt") 'Holds pres. names Private Sub btnDisplayPres_Click( ...) Handles btnDisplayPres.Click 'Display the presidents between two numbers, inclusive lstPres.Items.Clear() 'Loop from the lower number to the higher number For i As Integer = CInt(txtLowerNum.Text) To CInt(txtUpperNum.Text) lstPres.Items.Add(i & ". " & pres(i - 1)) Next End Sub
Instructor Solutions Manual (Page 160 of 221) 57. Dim colors() As String = IO.File.ReadAllLines("Colors.txt") Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim letter As String = mtbLetter.Text.ToUpper 'mask is L lstColors.Items.Clear() For Each hue As String In colors If hue.StartsWith(letter) Then lstColors.Items.Add(hue) End If Next End Sub
58. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim colors() As String = IO.File.ReadAllLines("Colors.txt") Dim n As Integer = colors.Count - 1 For i As Integer = n To 0 Step -1 lstOutput.Items.Add(colors(i)) Next End Sub
Instructor Solutions Manual (Page 161 of 221) 59. Dim colors() As String = IO.File.ReadAllLines("Colors.txt") Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim letter As String = mtbLetter.Text.ToUpper 'mask L lstColors.Items.Clear() For Each hue As String In SmallerArray(letter) lstColors.Items.Add(hue) Next End Sub Function SmallerArray(letter As String) As String() Dim smArray(colors.Count - 1) As String Dim counter As Integer = 0 For Each hue As String In colors If hue.StartsWith(letter) Then smArray(counter) = hue counter += 1 End If Next ReDim Preserve smArray(counter - 1) Return smArray End Function
60. Dim colors() As String = IO.File.ReadAllLines("Colors.txt") Private Sub frmColors_Load( ...) Handles MyBase.Load For i As Integer = 0 To colors.Count - 1 colors(i) = colors(i).ToUpper Next End Sub Private Sub btnDetermine_Click( ...) Handles btnDetermine.Click Dim color As String = txtColor.Text.ToUpper If IsCrayola(color) Then txtOutcome.Text = "YES" Else txtOutcome.Text = "NO" End If End Sub
Instructor Solutions Manual (Page 162 of 221) Function IsCrayola(color As String) As Boolean If Array.IndexOf(colors, color) = -1 Then Return False Else Return True End If End Function 61. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim ages(43), numPres As Integer Dim temp() As String = IO.File.ReadAllLines("AgesAtInaugural.txt") For i As Integer = 0 To 43 ages(i) = CInt(temp(i)) If ages(i) < 50 Then numPres += 1 End If Next txtNumber.Text = CStr(numPres) End Sub
62. Private Sub btnScores_Click( ...) Handles btnScores.Click 'Read data from a file and display their frequencies Dim scores() As String = IO.File.ReadAllLines("Scores.txt") Dim frequencies(4) As Integer 'Stores the results For i As Integer = 0 To scores.Count - 1 'Increment the frequency element that belongs to the number 'Divide by 10, and get the integer part. frequencies(CInt(Int(CInt(scores(i)) / 10))) += 1 Next lstOutput.Items.Add("Interval" & " " & "Frequency") lstOutput.Items.Add("0 to 9" & " " & frequencies(0)) For i As Integer = 1 To 4 lstOutput.Items.Add((i * 10) & " to " & ((i + 1) * 10) - 1 & " " & frequencies(i)) Next End Sub
Instructor Solutions Manual (Page 163 of 221) 63. Dim grades(99) As Integer Dim numGrades As Integer
'stores grades 'number of grades stored
Private Sub btnRecord_Click(...) Handles btnRecord.Click 'Add a score to the array 'If no more room, then display error message. If numGrades >= 100 Then MessageBox.Show("100 scores have been entered.", "No more room.") Else grades(numGrades) = CInt(txtScore.Text) numGrades += 1 lstOutput.Items.Clear() txtScore.Clear() txtScore.Focus() End If End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display average of grades and the number of above average grades Dim temp() As Integer = grades ReDim Preserve temp(numGrades - 1) lstOutput.Items.Clear() lstOutput.Items.Add("The average grade is " & (temp.Average).ToString("N2") & ".") lstOutput.Items.Add(NumAboveAverage(temp) & " students scored above the average.") End Sub Function NumAboveAverage(temp() As Integer) As Integer 'Count the number of scores above the average grade Dim avg As Double = temp.Average Dim num As Integer = 0 For Each grade In temp If grade > avg Then num += 1 End If Next Return num End Function
Instructor Solutions Manual (Page 164 of 221) 64. Private Sub btnAnalyze_Click(...) Handles btnAnalyze.Click 'Determine whether the sentence is a word palindrome Dim sentence = txtSentence.Text.ToUpper sentence = sentence.Replace(".", "") 'Delete any periods sentence = sentence.Replace(",", "") 'Delete any commas sentence = sentence.Replace(";", "") 'Delete any semicolons sentence = sentence.Replace(":", "") 'Delete any colons Dim words() As String = sentence.Split(" "c) If WordPalindrome(words) Then txtResult.Text = "Word palindrome" Else txtResult.Text = "Not a word palindrome." End If End Sub Function WordPalindrome(words() As String) As Boolean 'Analyze an array of words to see if it came from a word palindrome Dim numWords As Integer = words.Count Dim ub As Integer = words.Count - 1 For i As Integer = 0 To ((numWords \ 2) - 1) If words(i).ToUpper <> words(ub - i).ToUpper Then Return False End If Next Return True End Function
Instructor Solutions Manual (Page 165 of 221) 65. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click If IsChainLink(txtSentence.Text) Then txtOutput.Text = "This sentence is a chain-link sentence." Else txtOutput.Text = "This sentence is not a chain-link sentence." End If End Sub Function IsChainLink(sentence As String) As Boolean 'Analyze a sentence to see whether it is a chain-link sentence. Dim words(), ending As String 'Split the sentence into words, removing commas first words = sentence.Replace(",", "").Split(" "c) For i As Integer = 0 To words.Count - 2 If (words(i).Length < 2) Or (words(i + 1).Length < 2) Then Return False 'If any word has is less than two letters. End If ending = words(i).Substring(words(i).Length - 2).ToUpper If ending <> words(i + 1).Substring(0, 2).ToUpper Then Return False 'If ending does not match beginning of next word. End If Next Return True 'If all words are ok, then it is a chain-link sentence. End Function
EXERCISES 7.2 1. 5
7. 103
2. Houston have 8. RACECAR KAYAK
3. going offer can't 9. 8
11. 3 students have a grade of 100 13. 15 12
4. 1492 1776
5. 6
6. 9
10. Upscale 12. UNSAVORY
14. events Course
15. The average after dropping the lowest grade is 80 16. 274 278 279
Ramera Funk McNulty
17. 37 is a prime number
18. New York is not in New England.
Instructor Solutions Manual (Page 166 of 221)
19. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim nums() As Integer = {3, 5, 8, 10, 21} Dim query = From num In nums Where num Mod 2 = 0 Select num txtOutput.Text = query.count & " even numbers" End Sub
20. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim words() As String = {"When", "in", "the", "course", "of", "human", "events"} Dim query = From word In words Where word.Length = 5 Select word If query.Count > 0 Then txtOutput.Text = "at least one five-letter word" Else txtOutput.Text = "no five-letter words" End If End Sub 21. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim dates() As String = IO.File.ReadAllLines("Dates.txt") Dim query = From yr In dates Where (CInt(yr) >= 1800) And (CInt(yr) <= 1899) Select yr If query.Count > 0 Then txtOutput.Text = "contains a 19th century date" Else txtOutput.Text = "does not contains a 19th century date" End If End Sub
Instructor Solutions Manual (Page 167 of 221) 22. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim dates() As String = IO.File.ReadAllLines("Dates.txt") Dim query = From yr In dates Where (CInt(yr) >= 1900) Select yr txtOutput.Text = query.Count & " twentieth century dates" End Sub 23. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim nums() As Integer = {2, 6, 4} Dim query = From num In nums Order By Array.IndexOf(nums, num) Descending For Each num As Integer In query lstOutput.Items.Add(num) Next End Sub
24. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim speech() As String = {"Four", "score", "and", "seven", "years", "ago"} Dim query = From word In speech Select word.ToUpper speech = query.ToArray txtOutput.Text = speech(3) End Sub 25. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim teams() As String = IO.File.ReadAllLines("SBWinners.txt") Dim query = From team In teams Order By team Ascending Distinct For Each team As String In query lstOutput.Items.Add(team) Next End Sub
Instructor Solutions Manual (Page 168 of 221)
26. Dim teams() As String = IO.File.ReadAllLines("SBWinners.txt") Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From team In teams Order By NumberOfWins(team) Descending, team Ascending Select NumberOfWins(team) & " " & team Distinct For Each result As String In query lstOutput.Items.Add(result) Next End Sub Function NumberOfWins(club As String) As Integer Dim query = From team In teams Where team = club Select team Return query.Count End Function
27. Dim teamNames() As String = IO.File.ReadAllLines("SBWinners.txt") Private Sub btnDetermine_Click(...) Handles btnDetermine.Click 'Display the number of Super Bowls won by the team in the text box Dim query = From team In teamNames Where team.ToUpper = txtName.Text.ToUpper Select team txtNumWon.Text = CStr(query.Count) End Sub
Instructor Solutions Manual (Page 169 of 221)
28. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim teams() As String = IO.File.ReadAllLines("SBWinners.txt") Dim query = From team In teams Where team.StartsWith("B") Order By team Ascending Distinct For Each team As String In query lstOutput.Items.Add(team) Next End Sub
Instructor Solutions Manual (Page 170 of 221) 29. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim word1 As String = txtFirstWord.Text Dim word2 As String = txtSecondWord.Text If AreAnagrams(word1, word2) Then txtOutput.Text = "ARE ANAGRAMS" Else txtOutput.Text = "NOT ANAGRAMS" End If End Sub Function AreAnagrams(word1 As String, word2 As String) As Boolean If word1.Length <> word2.Length Then Return False Else Dim n = word1.Length - 1 Dim w1(n), w2(n) As String For i As Integer = 0 To n w1(i) = word1.Substring(i, 1) w2(i) = word2.Substring(i, 1) Next Dim query1 = From letter In w1 Order By letter Select letter.ToUpper Dim query2 = From letter In w2 Order By letter Select letter.ToUpper For i As Integer = 0 To n If query1.ToArray(i) <> query2.ToArray(i) Then Return False End If Return True Next End If End Function
30. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query1 = From grade In IO.File.ReadAllLines("Final.txt") Select CInt(grade) Dim avg As Double = query1.Average Dim query2 = From grade In IO.File.ReadAllLines("Final.txt") Where CInt(grade) > avg Select grade txtAverage.Text = avg.ToString("N") txtAboveAve.Text = (query2.Count / query1.Count).ToString("P") End Sub
Instructor Solutions Manual (Page 171 of 221)
31. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim grades(4) As Integer For i As Integer = 0 To 4 grades(i) = CInt(InputBox("Enter grade #" & (i + 1), "Grades")) Next Dim query = From grade In grades Order By grade Descending Select grade grades = query.ToArray ReDim Preserve grades(2) 'lop off lowest two grades txtOutput.Text = CStr(grades.Average) End Sub
32. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim n As Integer = CInt(InputBox("Enter a positive integer.")) Dim nums(n - 1) As Double For i As Integer = 0 To (n – 1) nums(i) = CDbl(InputBox("Enter a measurement.")) Next txtMedian.Text = CStr(Median(nums)) End Sub Function Median(grades() As Double) As Double 'Use LINQ to sort the grades Dim query = From grade In grades Order By grade Ascending Select grade grades = query.ToArray 'grades have been sorted Dim n As Integer If (grades.Count Mod 2 <> 0) Then 'case where grades.Count is odd n = CInt((grades.Count - 1) / 2) Return grades(n) Else 'case where grades.count is even n = CInt((grades.Count / 2) - 1) Return (grades(n) + grades(n + 1)) / 2 End If End Function
Instructor Solutions Manual (Page 172 of 221) 33. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim states() As String = IO.File.ReadAllLines("States.txt") ReDim Preserve states(12) Dim query = From state In states Order By state Select state For Each state As String In query lstOutput.Items.Add(state) Next End Sub
34. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From pres In IO.File.ReadAllLines("USPres.txt") Let lastName = pres.Split(" "c).Last Order By lastName Select pres For Each pres As String In query lstOutput.Items.Add(pres) Next Distinct End Sub
Instructor Solutions Manual (Page 173 of 221) 35. Dim nations() As String = IO.File.ReadAllLines("Nations.txt") Private Sub frmNations_Load(...) Handles MyBase.Load lstNations.DataSource = nations lstNations.SelectedItem = Nothing End Sub Private Sub txtNations_TextChanged(...) Handles txtNation.TextChanged Dim query = From nation In nations Where nation.StartsWith(txtNation.Text) Select nation lstNations.DataSource = query.ToList lstNations.SelectedItem = Nothing End Sub Private Sub lstNations_Click(...) Handles lstNations.Click txtNation.Text = lstNations.Text End Sub
Instructor Solutions Manual (Page 174 of 221) 36. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From word In IO.File.ReadAllLines("Words.txt") Let vowels = NumberOfVowels(word.ToUpper) Order By vowels Descending, word.Length Descending,word Ascending Select vowels & " " & word For Each item As String In query lstOutput.Items.Add(item) Next End Sub Function NumberOfVowels(word As String) As Integer 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 Private Sub lstNations_Click(...) Handles lstNations.Click txtNation.Text = lstNations.Text End Sub
Instructor Solutions Manual (Page 175 of 221)
EXERCISES 7.3 1. The area of a football field is 19200 square yards. 2. USC is 133 years old.
(answers will vary; age in 2013 was 133)
3. Duke was founded in NC in 1838. 4. Stanford was founded in CA in 1885. 5. heights are same 170 6. Wage for John Q. Public: $1,100.00 7. Joe: 88 Moe: 90 Roe: 95
8. Not eligible to participate in the health plan.
9. Mr. President lives in Washington, DC 10. Hannah Jones earned $800.00
11. In the event procedure, peace should be prize.peace and yr should be prize.yr. 12. The statement lstOutput.Items.Add(minimum) should be replaced with either lstOutput.Items.Add(minimum.a) or lstOutput.Items.Add(minimum.b), or both. 13. The condition (game1 > game2) is not valid. Structures can only be compared one field at a time. 14. person1.name = "Michael" person1.stats.height = 71 person1.stats.weight = 190 person2.name = "Jacob" person2.stats.height = 70 person2.stats.weight = 175 If (person1.stats.height > person2.stats.height) And (person1.stats.weight > person2.stats.weight) Then txtOutput.Text = person1.name & " is bigger than " & person2.name End If
15. The cities in Texas, along with their populations. The cities are ordered by the sizes of their populations beginning with the most populous city. 16. The cities in Texas, along with their population growth from 2000 2010. The cities are ordered by the magnitude of their growths beginning with the city experiencing the greatest growth. Then the greatest population growth of these cites is displayed. 17. The population growth of Phoenix from 2000 to 2010. 18. The sum of the populations of the ten largest cities.
Instructor Solutions Manual (Page 176 of 221) 19. Structure State Dim name As String Dim abbreviation As String Dim area As Double Dim pop As Double End Structure Dim states() As State Private Sub frmStates_Load(...) Handles MyBase.Load Dim stateRecords() As String = IO.File.ReadAllLines("USStates.txt") Dim n As Integer = stateRecords.Count - 1 ReDim states(n) Dim line As String Dim data() As String For i As Integer = 0 To n line = stateRecords(i) data = line.Split(","c) states(i).name = data(0) states(i).abbreviation = data(1) states(i).area = CDbl(data(2)) states(i).pop = CDbl(data(3)) Next End Sub Private Sub btnFind_Click(...) Handles btnFind.Click Dim stateAbbr As String = mtbAbbrev.Text.ToUpper Dim query = From state In states Where state.abbreviation = stateAbbr Select state.name, state.area txtOutput.Text = "The area of " & query.First.name & " is " & (query.First.area).ToString("N0") & " square miles." End Sub
20. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From line In IO.File.ReadAllLines("USStates.txt") 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
Instructor Solutions Manual (Page 177 of 221) 21. Structure State Dim name As String Dim abbreviation As String Dim area As Double Dim pop As Double End Structure Dim states() As State Private Sub frmStates_Load(...) Handles MyBase.Load Dim stateRecords() As String = IO.File.ReadAllLines("USStates.txt") Dim n As Integer = stateRecords.Count - 1 ReDim states(n) Dim line As String Dim data() As String For i As Integer = 0 To n line = stateRecords(i) data = line.Split(","c) states(i).name = data(0) states(i).abbreviation = data(1) states(i).area = CDbl(data(2)) states(i).pop = CDbl(data(3)) Next End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From state In states Let density = state.pop / state.area Let formattedDensity = density.ToString("N2") Order By density Descending Select state.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 178 of 221) 22. 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
Instructor Solutions Manual (Page 179 of 221) 23. Structure Player Dim name As String Dim team As String Dim atBats As Double Dim hits As Double End Structure Dim players() As Player Private Sub frmBaseball_Load(...) Handles MyBase.Load Dim playerStats() As String = IO.File.ReadAllLines("Baseball.txt") Dim n As Integer = playerStats.Count - 1 ReDim players(n) Dim line As String Dim data() As String For i As Integer = 0 To n line = playerStats(i) data = line.Split(","c) players(i).name = data(0) players(i).team = data(1) players(i).atBats = CDbl(data(2)) players(i).hits = CDbl(data(3)) Next Dim query = From person In players Order By person.team Ascending Select person.team Distinct lstTeams.DataSource = query.ToList End Sub Private Sub lstTeams_SelectedIndexChanged(...) Handles _ lstTeams.SelectedIndexChanged Dim selectedTeam = lstTeams.Text Dim query = From person In players Where person.team = selectedTeam Order By person.hits Descending Select person.name, person.hits dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "Player" dgvOutput.Columns("hits").HeaderText = "Hits" End Sub
Instructor Solutions Manual (Page 180 of 221) 24. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From line In IO.File.ReadAllLines("Baseball.txt") Let team = line.Split(","c)(1) Order By team Ascending Select team Distinct lstOutput.DataSource = query.ToList lstOutput.SelectedItem = Nothing End Sub
25. Structure Player Dim name As String Dim team As String Dim atBats As Double Dim hits As Double End Structure Dim players() As Player Private Sub frmBaseball_Load(...) Handles MyBase.Load Dim playerStats() As String = IO.File.ReadAllLines("Baseball.txt") Dim n As Integer = playerStats.Count - 1 ReDim players(n) Dim line As String Dim data() As String For i As Integer = 0 To n line = playerStats(i) data = line.Split(","c) players(i).name = data(0) players(i).team = data(1) players(i).atBats = CDbl(data(2)) players(i).hits = CDbl(data(3)) Next End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From person In players Let ave = person.hits / person.atBats Select ave Dim best As Double = query.Max txtBestAverage.Text = best.ToString("N3") Dim query2 = From person In players Where person.hits / person.atBats = best Select person.name, person.team dgvOutput.DataSource = query2.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "Player" dgvOutput.Columns("team").HeaderText = "Team" End Sub
Instructor Solutions Manual (Page 181 of 221) 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").Substring(1, 4) 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
27. Structure Pioneer Dim name As String Dim accomplishment As String End Structure Dim pioneers() As Pioneer Private Sub frmPioneers_Load() Handles MyBase.Load 'Place the data for each college into the array schools. Dim people() = IO.File.ReadAllLines("Pioneers.txt") Dim n As Integer = people.Count - 1 ReDim pioneers(n) Dim line As String 'holds data for a single college Dim data() As String For i As Integer = 0 To n line = people(i) data = line.Split(","c) pioneers(i).name = data(0) pioneers(i).accomplishment = data(1) lstPioneers.Items.Add(pioneers(i).name) Next End Sub Private Sub lstPioneers_SelectedIndexChanged(...) Handles _ lstPioneers.SelectedIndexChanged txtAccomplishment.Text = pioneers(lstPioneers.SelectedIndex).accomplishment End Sub
Instructor Solutions Manual (Page 182 of 221) 28. Dim justices() As String = IO.File.ReadAllLines("Justices.txt") Private Sub frmJustices_Load(...) Handles MyBase.Load Dim query = From pres In IO.File.ReadAllLines("USPres.txt") Select pres For Each president In query lstPres.Items.Add(president) Next End Sub Private Sub lstPres_SelectedIndexChanged(...) Handles _ lstPres.SelectedIndexChanged Dim query = From line In justices Let firstName = line.Split(","c)(0) Let lastName = line.Split(","c)(1) Let pres = line.Split(","c)(2) Let yrAppointed = CInt(line.Split(","c)(4)) Let yrLeft = CInt(line.Split(","c)(5)) Let yrs = YearsServed(yrAppointed, yrLeft) Where pres = lstPres.Text Order By yrs Descending Select firstName & " " & lastName lstOutput.DataSource = query.ToList lstOutput.SelectedItem = Nothing End Sub Function YearsServed(enter As Integer,leave As Integer) As Integer If leave = 0 Then Return (Now.Year - enter) Else Return (leave - enter) End If End Function
Instructor Solutions Manual (Page 183 of 221) 29. Structure Justice Dim firstName As String Dim lastName As String Dim apptPres As String Dim state As String 'state abbreviation Dim yrAppointed As Double Dim yrLeft As Double End Structure Dim justices() As Justice Private Sub frmJustices_Load(...) Handles MyBase.Load Dim justiceRecords() As String = IO.File.ReadAllLines("Justices.txt") Dim n As Integer = justiceRecords.Count - 1 ReDim justices(n) Dim line As String Dim data() As String For i As Integer = 0 To n line = justiceRecords(i) data = line.Split(","c) justices(i).firstName = data(0) justices(i).lastName = data(1) justices(i).apptPres = data(2) justices(i).state = data(3) justices(i).yrAppointed = CDbl(data(4)) justices(i).yrLeft = CDbl(data(5)) Next End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From person In justices Where person.yrLeft = 0 Order By person.yrAppointed Select person.firstName & " " & person.lastName lstOutput.DataSource = query.ToList lstOutput.SelectedItem = Nothing End Sub
Instructor Solutions Manual (Page 184 of 221) 30. Private Sub btnDisolay_Click(...) Handles btnDisolay.Click 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 yrAppointed = CInt(data(4)) Let yrLeft = CInt(data(5)) Let fullName = firstName & " " & lastName Where (yrLeft >= 1980) And (yrAppointed < 1980) Order By yrAppointed Select fullName, pres dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("fullName").HeaderText = "Justice" dgvOutput.Columns("pres").HeaderText = "Appointing President" End Sub
31. Structure Justice Dim firstName As String Dim lastName As String Dim apptPres As String Dim state As String 'state abbreviation Dim yrAppointed As Double Dim yrLeft As Double End Structure Dim justices() As Justice
Instructor Solutions Manual (Page 185 of 221) Private Sub frmJustices_Load(...) Handles MyBase.Load Dim justiceRecords() As String = IO.File.ReadAllLines("Justices.txt") Dim n As Integer = justiceRecords.Count - 1 ReDim justices(n) Dim line As String Dim data() As String For i As Integer = 0 To n line = justiceRecords(i) data = line.Split(","c) justices(i).firstName = data(0) justices(i).lastName = data(1) justices(i).apptPres = data(2) justices(i).state = data(3) justices(i).yrAppointed = CDbl(data(4)) justices(i).yrLeft = CDbl(data(5)) Next End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From person In justices Where person.state = mtbState.Text Let fullName = person.firstName & " " & person.lastName Let yrs = YearsServed(person.yrAppointed, person.yrLeft) Let presLastName = person.apptPres.Split(" "c).Last Select fullName, presLastName, yrs If query.Count = 0 Then MessageBox.Show("No justices appointed from that state.", "NONE") mtbState.Focus() Else dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("fullName").HeaderText = "Justice" dgvOutput.Columns("presLastName").HeaderText = "Appointing President" dgvOutput.Columns("yrs").HeaderText = "Years Served" End If End Sub Function YearsServed(enter As Double, leave As Double) As Double If leave = 0 Then Return (Now.Year - enter) Else Return (leave - enter) End If End Function
Instructor Solutions Manual (Page 186 of 221) 32. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim people() As String = IO.File.ReadAllLines("Famous.txt") Dim query = From person In people Let data = person.Split(","c) Let name = data(0) Let d = CDate(data(1)) Where d.ToString("D").StartsWith("Tuesday") Select name lstOutput.DataSource = query.ToList lstOutput.SelectedItem = Nothing End Sub
33. Structure FamousPerson Dim name As String Dim dateOfBirth As Date End Structure Dim famousPersons() As FamousPerson Private Sub frmFamous_Load(...) Handles MyBase.Load Dim people() As String = IO.File.ReadAllLines("Famous.txt") Dim n As Integer = people.Count - 1 ReDim famousPersons(n) Dim line As String Dim data() As String For i As Integer = 0 To n line = people(i) data = line.Split(","c) famousPersons(i).name = data(0) famousPersons(i).dateOfBirth = CDate(data(1)) Next End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From person In famousPersons Where (person.dateOfBirth >= #1/1/1970#) And (person.dateOfBirth < #1/1/1980#) Select person.name lstOutput.DataSource = query.ToList lstOutput.SelectedItem = Nothing End Sub
Instructor Solutions Manual (Page 187 of 221) 34. Structure FamousPerson Dim name As String Dim dateOfBirth As Date End Structure Dim people() As FamousPerson Private Sub frmFamous_Load(...) Handles MyBase.Load 'Place the data for each person into the array people. Dim group() As String = IO.File.ReadAllLines("Famous.txt") Dim n As Integer = group.Count - 1 ReDim people(n) Dim data() As String For i As Integer = 0 To n data = group(i).Split(","c) people(i).name = data(0) people(i).dateOfBirth = CDate(data(1)) Next End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From individual In people Order By individual.dateOfBirth Ascending Select individual.name, individual.dateOfBirth dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing End Sub
Instructor Solutions Manual (Page 188 of 221) 35. Structure FamousPerson Dim name As String Dim dateOfBirth As Date End Structure Dim people() As FamousPerson Private Sub frmFamous_Load(...) Handles MyBase.Load 'Place the data for each person into the array people. Dim group() As String = IO.File.ReadAllLines("Famous.txt") Dim n As Integer = group.Count - 1 ReDim people(n) Dim data() As String For i As Integer = 0 To n data = group(i).Split(","c) people(i).name = data(0) people(i).dateOfBirth = CDate(data(1)) Next End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From individual In people Let ageInDays = (DateDiff(DateInterval.Day, individual.dateOfBirth, Today)).ToString("N0") Let dayOfBirth = DayOfWeek(individual.dateOfBirth) Where individual.dateOfBirth.AddYears(40) <= Today And individual.dateOfBirth.AddYears(50) > Today Select individual.name, ageInDays, dayOfBirth dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing End Sub Function DayOfWeek(d As Date) As String Dim d1 As String = d.ToString("D") Dim d2() As String = d1.Split(","c) Return First End Function
Instructor Solutions Manual (Page 189 of 221) 36. Structure Day
Dim num As Integer Dim present As String Dim price As Double End Structure Dim days() As Day Private Sub frmXmas_Load(...) Handles MyBase.Load Dim gifts() As String = IO.File.ReadAllLines("Gifts.txt") Dim n As Integer = gifts.Count - 1 ReDim days(n) Dim data() As String For i As Integer = 0 To n data = gifts(i).Split(","c) days(i).num = CInt(data(0)) days(i).present = data(1) days(i).price = CDbl(data(2)) Next End Sub Private Sub btnDisplayGifts_Click(...) Handles btnDisplayGifts.Click Dim dayNum = CInt(txtDayNum.Text) Dim cost As Double = 0 Dim totalCost As Double = 0 lstOutput.Items.Clear() lstOutput.Items.Add("The gifts for day " & dayNum & " are") For i As Integer = 0 To (dayNum - 1) lstOutput.Items.Add(days(i).num & " " & days(i).present) cost += days(i).num * days(i).price totalCost += days(i).num * days(i).price * (dayNum + 1 - days(i).num) Next lstOutput.Items.Add("") lstOutput.Items.Add("Cost for day " & dayNum & ": " & cost.ToString("C")) lstOutput.Items.Add("Total cost for the first " & dayNum & " days: " & totalCost.ToString("C")) End Sub
Instructor Solutions Manual (Page 190 of 221) 37. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click lstOutput.Items.Clear() For i As Integer = 0 To club.Count - 1 lstOutput.Items.Add(club(i).name) Next End Sub 38. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click lstOutput.Items.Clear() For i As Integer = 0 To (club.Count – 1) If club(i).courses.Count = 3 Then lstOutput.Items.Add(club(i).name) End If Next End Sub 39. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Displays the students who are enrolled in CMSC 100 Dim subject = "CMSC 100" 'Loop over all students in the club For i As Integer = 0 To (club.Count – 1) 'Loop over all courses for that student For j As Integer = 0 To (club(i).courses.Count – 1) 'If a course matches, display the student's name. If club(i).courses(j) = subject Then lstOutput.Items.Add(club(i).name) End If Next Next End Sub 40. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Displays the students who are not enrolled in CMSC 100 Dim subject = "CMSC 100" Dim ub = club.Count - 1 Dim checkList(ub) As Boolean For i As Integer = 0 To ub For j As Integer = 0 To (club(i).courses.Count – 1) If club(i).courses(j) = subject Then checkList(i) = True End If Next Next For i As Integer = 0 To ub If Not checkList(i) Then lstOutput.Items.Add(club(i).name) End If Next End Sub
EXERCISES 7.4 1. 1
2. 6
3. 3
4. 2
5. 55
6. 20
Instructor Solutions Manual (Page 191 of 221) 7. 14
8. 55
9. 2
10. 10
11. 55
13. Dim twice(2, 3) As Double For r As Integer = 0 To 2 For c As Integer = 0 To 3 twice(r, c) = 2 * nums(r, c) Next Next 14. Dim total As Double = 0 Dim counter As Integer = 0 For Each num In nums total += num counter += 1 Next lstOutput.Items.Add(total / counter) 15. 'use a For Each loop Dim total As Double = 0 For Each num As Double In nums If num Mod 2 = 0 Then total += num End If Next lstOutput.Items.Add(total) 'use LINQ Dim query = From num In nums.Cast(Of Double)() Where (num Mod 2 = 0) Select num lstOutput.Items.Add(query.Sum) 16. 'use a For Each loop Dim total As Double = 0 Dim counter As Integer = 0 For Each num As Double In nums If num Mod 2 <> 0 Then total += num counter += 1 End If Next lstOutput.Items.Add(total / counter) 'use LINQ Dim query = From num In nums.Cast(Of Double)() Where (num Mod 2 <> 0) Select num lstOutput.Items.Add(query.Average) 17. 12
18. James Madison
12. 0 1 2 3 4 5
Instructor Solutions Manual (Page 192 of 221) 19. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim inventory(,) As Integer = {{25, 64, 23}, {30, 82, 19}} Dim sales(,) As Integer = {{7, 45, 11}, {4, 24, 8}} Dim total(2) As Integer 'Adjust the inventory values to reflect today's sales For store As Integer = 1 To 2 For item As Integer = 1 To 3 inventory(store - 1, item - 1) = inventory(store - 1, item - 1) - sales(store - 1, item - 1) 'Accumulate the total inventory per store total(store) += inventory(store - 1, item - 1) Next Next lstOutput.Items.Add(" 1 2 3 TOTAL") For store As Integer = 1 To 2 lstOutput.Items.Add(store & " " & inventory(store - 1, 0) & " " & inventory(store - 1, 1) & " " & inventory(store - 1, 2) & " " & total(store)) Next End Sub
20. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click 'Determine average of percentages in Spreadsheets column Dim percentUse(5, 4) As Double ReadData(percentUse) ShowAveragePercentage(percentUse) End Sub Sub ReadData(ByRef percentUse(,) As Double) 'Read percentages for each age group Dim table() As String = IO.File.ReadAllLines("WORKERS.TXT") Dim data() As String For age As Integer = 0 To 5 data = table(age).Split(","c) For use As Integer = 0 To 4 percentUse(age, use) = CDbl(data(use)) Next Next End Sub Sub ShowAveragePercentage(percentUse(,) As Double) 'Determine average of percentages in Spreadsheets column '(i.e., column corresponding to 1) Dim sum As Double = 0 For age As Integer = 0 To 5 sum += percentUse(age, 1) Next txtAverage.Text = (sum / 6).ToString("P1") End Sub
Instructor Solutions Manual (Page 193 of 221) 21. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim ranking(2, 4) As String Dim disciplines(2) As String Dim table() As String = IO.File.ReadAllLines("Ranking.txt") Dim data() As String For field As Integer = 0 To 2 data = table(field).Split(","c) disciplines(field) = data(0) For rank As Integer = 0 To 4 ranking(field, rank) = data(rank + 1) Next Next Dim result As String = "" For category As Integer = 0 To 2 For rank As Integer = 0 To 4 If txtName.Text.ToUpper = ranking(category, rank).ToUpper Then 'Append category name to result result &= disciplines(category) & " " End If Next Next If result = "" Then txtOutput.Text = "None." Else txtOutput.Text = result End If End Sub
Instructor Solutions Manual (Page 194 of 221) 22. Private Sub btnDisplay_Click() Handles btnDisplay.Click 'Calculate total change in sales for the 'five leading restaurant chains Dim units(4, 1) As Integer ReadData(units) ShowChange(units) End Sub Sub ReadData(ByVal units(,) As Integer) 'Read sales for each restaurant Dim table() As String = IO.File.ReadAllLines("Restaurants.txt") Dim data() As String For company As Integer = 0 To 4 data = table(company).Split(","c) For yr As Integer = 0 To 1 units(company, yr) = CInt(data(yr + 1)) Next Next End Sub Sub ShowChange(units(,) As Integer) 'Compute and show change in units Dim total As Integer = 0 For company As Integer = 0 To 4 total += units(company, 1) - units(company, 0) Next txtChange.Text = total.ToString("N0") End Sub
Instructor Solutions Manual (Page 195 of 221) 23. Private Sub btnDisplay_Click() Handles btnDisplay.Click Dim scores(3, 3) As Integer Dim golfers(3) As String Dim table() As String = IO.File.ReadAllLines("Golf.txt") Dim data() As String Dim golferTotal(3) As Integer, roundTotal(3) As Integer For i As Integer = 0 To 3 data = table(i).Split(","c) golfers(i) = data(0) For j As Integer = 0 To 3 scores(i, j) = CInt(data(j + 1)) Next Next For golfer As Integer = 0 To 3 For round As Integer = 0 To 3 golferTotal(golfer) += scores(golfer, round) roundTotal(round) += scores(golfer, round) Next Next 'Display golfer's totals lstOutput.Items.Add("GOLFER TOTALS") For golfer As Integer = 0 To 3 lstOutput.Items.Add(golfers(golfer) & ": " & golferTotal(golfer)) Next lstOutput.Items.Add("") 'Display average per round lstOutput.Items.Add("ROUND AVERAGE") For round As Integer = 0 To 3 lstOutput.Items.Add(round + 1 & ": " & (roundTotal(round) / 4).ToString("N")) Next End Sub
24. Dim scores(14, 2) As Integer Dim count As Integer Dim names(14) As String Dim grades() As Integer
'Stores students' exam scores 'Current number of students stored 'Stores students' names
Instructor Solutions Manual (Page 196 of 221) Private Sub btnAdd_Click(...) Handles btnAdd.Click If (count = 15) Then MessageBox.Show("Fifteen students already stored.", "Warning") Else count += 1 names(count - 1) = txtName.Text scores(count - 1, 0) = CInt(txtExam1.Text) scores(count - 1, 1) = CInt(txtExam2.Text) scores(count - 1, 2) = CInt(txtExam3.Text) txtName.Clear() txtExam1.Clear() txtExam2.Clear() txtExam3.Clear() txtName.Focus() End If End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim sum As Integer 'Display student's semester grades lstOutput.Items.Clear() lstOutput.Items.Add("Students' Semester Average") For i As Integer = 0 To count - 1 'Accumulate sum of scores for each student sum = 0 For exam As Integer = 0 To 2 sum += scores(i, exam) Next 'Display the student's name and semester average lstOutput.Items.Add(names(i) & ": " & (sum / 3).ToString("N")) Next 'Display median on the exams lstOutput.Items.Add("Exam Medians") For exam As Integer = 0 To 2 ReDim grades(count - 1) For i As Integer = 0 To count - 1 grades(i) = scores(i, exam) Next lstOutput.Items.Add(exam + 1 & ": " & Median(grades)) Next End Sub Function Median(grades() As Integer) As Double Dim query = From grade In grades Order By grade Ascending Select grade grades = query.ToArray 'grades have been sorted Dim n As Integer If (grades.Count Mod 2 <> 0) Then 'case where grades.Count is odd n = CInt((grades.Count - 1) / 2) Return grades(n) Else 'case where grades.count is even n = CInt((grades.Count / 2) - 1) Return (grades(n) + grades(n + 1)) / 2 End If End Function
Instructor Solutions Manual (Page 197 of 221) 25. Structure Month Dim name As String Dim avePrecip As Double End Structure Structure Year Dim name As Integer Dim totalPrecip As Double End Structure Dim months(11) As Month Dim monthNames() As String = IO.File.ReadAllLines("MONTHS.TXT") Dim precipData(4, 12) As Double Dim years(4) As Year Private Sub frmRain_Load(...) Handles MyBase.Load Dim rowOfNums() As String = IO.File.ReadAllLines("RAIN.TXT") For i As Integer = 0 To precipData.GetUpperBound(0) Dim line() As String = rowOfNums(i).Split(","c) For j As Integer = 0 To precipData.GetUpperBound(1) precipData(i, j) = CDbl(line(j)) Next Next End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click For j As Integer = 0 To 11 months(j).name = monthNames(j) Dim sum As Double = 0 For i As Integer = 0 To 4 sum += precipData(i, j) Next months(j).avePrecip = sum / 5 Next Dim query = From mnth In months Let ave = (mnth.avePrecip).ToString("N") Select mnth.name, ave dgvOutputMonths.DataSource = query.ToList dgvOutputMonths.CurrentCell = Nothing dgvOutputMonths.Columns("name").HeaderText = "Month" dgvOutputMonths.Columns("ave").HeaderText = "Average Precipitation" For i As Integer = 0 To 4 years(i).name = CInt(precipData(i, 12)) Dim sum As Double = 0 For j As Integer = 0 To 11 sum += precipData(i, j) Next years(i).totalPrecip = sum Next Dim query2 = From yr In years Let totPrec = (yr.totalPrecip).ToString("N") Select yr.name, totPrec dgvOutputYrs.DataSource = query2.ToList dgvOutputYrs.CurrentCell = Nothing dgvOutputYrs.Columns("name").HeaderText = "Year" dgvOutputYrs.Columns("totPrec").HeaderText = "Total Precipitation for the Year" End Sub
Instructor Solutions Manual (Page 198 of 221)
26. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Load data into an array, cumulate totals, and display a report Dim totalSales As Double Dim sales(,) As Integer = {{25, 64, 23, 45, 14},{12, 82, 19, 34, 63}, {54, 22, 17, 43, 35}} Dim price() As Double = {12, 17.95, 95, 86.5, 78} Dim totals(2) As Double For store As Integer = 0 To 2 For item As Integer = 0 To 4 totals(store) += sales(store, item) * price(item) Next Next lstOutput.Items.Add("Sales per store") For store As Integer = 0 To 2 lstOutput.Items.Add(store + 1 & ": " & (totals(store)).ToString("C")) totalSales += totals(store) Next lstOutput.Items.Add("Total sales: " & totalSales.ToString("C")) End Sub
Instructor Solutions Manual (Page 199 of 221) 27. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display the course and campus enrollments 'enrollment array named er Dim er(,) As Integer = {{5, 15, 22, 21, 12, 25, 16, 11, 17, 23}, {11, 23, 51, 25, 32, 35, 32, 52, 25, 21}, {2, 12, 32, 32, 25, 26, 29, 12, 15, 11}} 'Define the arrays to accumulate the information Dim campusTotal(2), courseTotal(9) As Integer For campus As Integer = 0 To 2 For course As Integer = 0 To 9 campusTotal(campus) += er(campus, course) courseTotal(course) += er(campus, course) Next Next 'Display the campus enrollment lstOutput.Items.Add("CAMPUS ENROLLMENT") For campus As Integer = 0 To 2 lstOutput.Items.Add((campus + 1) & ": " & campusTotal(campus)) Next 'Display the course enrollment lstOutput.Items.Add("COURSE ENROLLMENT") For course As Integer = 0 To 9 lstOutput.Items.Add((course + 1) & ": " & courseTotal(course)) Next End Sub
Instructor Solutions Manual (Page 200 of 221) 28. Private Sub btnCompute_Click(...) Handles btnCompute.Click 'Compute total amount spent on salaries Dim salary(6, 3) As Double 'first 7 categories of federal pay scale Dim employees(6, 3) As Integer 'number of employees of each classification ReadData(salary, employees) ShowTotalPay(salary, employees) End Sub Sub ReadData(ByRef salary(,) As Double, ByRef employees(,) As Integer) 'Get salaries and number of employees. Dim filePaySched As String = "GS-PAY.TXT" Dim fileEmployees As String = "GS-EMPLOYEES.TXT" Dim table() As String = IO.File.ReadAllLines(filePaySched) Dim data() As String For category As Integer = 0 To 6 data = table(category).Split(","c) For stp As Integer = 0 To 3 salary(category, stp) = CDbl(data(stp)) Next Next table = IO.File.ReadAllLines(fileEmployees) For category As Integer = 0 To 6 data = table(category).Split(","c) For stp As Integer = 0 To 3 employees(category, stp) = CInt(data(stp)) Next Next End Sub Sub ShowTotalPay(salary(,) As Double, employees(,) As Integer) 'Compute total pay to all employees. Dim total As Double = 0 For category As Integer = 0 To 6 For stp As Integer = 0 To 3 total += salary(category, stp) * employees(category, stp) Next Next txtTotalOfSalaries.Text = total.ToString("C0") End Sub
Instructor Solutions Manual (Page 201 of 221) 29. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim n As Integer = CInt(InputBox("How many elements are in each row" & " and column of the array?")) Dim a(n - 1, n - 1) As Integer For i As Integer = 0 To n - 1 For j As Integer = 0 To n - 1 a(i, j) = CInt(InputBox("What is the entry in Row " & i + 1 & ", Column " & j + 1)) Next Next If TestMagic(n, a) Then txtAnswer.Text = "Yes" Else txtAnswer.Text = "No" End If End Sub Function TestMagic(n As Integer, a(,) As Integer) As Boolean Dim sum, total As Integer 'sum of numbers in first row 'Find sum of elements in first row\sum = 0 For j As Integer = 0 To n - 1 sum += a(0, j) Next 'Test row totals For i As Integer = 1 To n - 1 total = 0 For j As Integer = 0 To n - 1 total += a(i, j) Next If total <> sum Then Return False End If Next 'Test column totals For j As Integer = 0 To n - 1 total = 0 For i As Integer = 0 To n - 1 total += a(i, j) Next If total <> sum Then Return False End If Next 'Test first diagonal total = 0 For i As Integer = 0 To n - 1 total += a(i, i) Next If total <> sum Then Return False End If
Instructor Solutions Manual (Page 202 of 221) 'Test second diagonal total = 0 For i As Integer = 0 To n - 1 total += a(i, n - i - 1) Next If total <> sum Then Return False End If Return True End Function
Instructor Solutions Manual (Page 203 of 221)
CHAPTER 7 PROGRAMMING PROJECTS 1. 'Unit Conversion Dim unitName(8) As String Dim inFeet(8) As Double Dim numUnits As Double = 8 Dim units() As String = IO.File.ReadAllLines("Units.txt") Private Sub frmConvert_Load(...) Handles MyBase.Load 'Load conversion into array For i As Integer = 0 To 8 unitName(i) = units(i).Split(","c)(0) inFeet(i) = CDbl(units(i).Split(","c)(1)) lstUnits.Items.Add((i + 1) & ". " & unitName(i)) Next End Sub Private Sub btnConvert_Click(...) Handles btnConvert.Click 'Program to convert units of measure Dim length As Double, fromUnit As Integer, toUnit As Integer InputData(fromUnit, toUnit, length) If (fromUnit >= 1) And (fromUnit <= numUnits) And (toUnit >= 1) And (toUnit <= numUnits) Then ConvertUnits(inFeet, fromUnit, toUnit, length) Else MessageBox.Show("Only pick a unit from 1 to 9.") End If End Sub Sub InputData(ByRef fromUnit As Integer, ByRef toUnit As Integer, ByRef length As Double) 'Input source, destination, and length length = CDbl(mtxtLength.Text) fromUnit = CInt(mtxtFrom.Text) toUnit = CInt(mtxtTo.Text) End Sub Sub ConvertUnits(inFeet() As Double, fromUnit As Integer, toUnit As Integer, length As Double) 'Perform conversion and display result Dim result As Double = inFeet(fromUnit - 1) / inFeet(toUnit - 1) * length txtOutput.Text = result.ToString("N") End Sub
Instructor Solutions Manual (Page 204 of 221) 2. Private Sub btnCheckValidity_Click() Handles btnCheckValidity.Click If checkFormat(txtISBN.Text) Then If isValidISBN(txtISBN.Text) Then txtResult.Text = "YES" 'lstDisplay.Items.Add(txtISBN.Text & " is a valid ISBN.") Else txtResult.Text = "NO" 'lstDisplay.Items.Add(txtISBN.Text & " is not a valid ISBN.") End If Else 'Improperly formatted ISBN string MessageBox.Show("ISBN is not properly formatted.") 'lstDisplay.Items.Add("ISBN is not properly formatted.") End If End Sub Function checkFormat(ByVal isbn As String) As Boolean 'Checks the format of the input string 'to make sure that the last character is an X or a digit, 'and the remaining characters are digits or hyphens Dim digitCount As Integer Dim hasInvalidCharacter As Boolean Dim i As Integer = 1 digitCount = 0 Do While i < isbn.Length And hasInvalidCharacter = False If isDigit(isbn.Substring(i - 1, 1)) Then digitCount = digitCount + 1 ElseIf isbn.Substring(i - 1, 1) <> "-" Then hasInvalidCharacter = True End If i = i + 1 Loop 'Check last digit individually to allow for an X If Not (isDigit(isbn.Substring(i - 1, 1)) Or (isbn.Substring(i - 1, 1) = "X")) Then hasInvalidCharacter = True Else digitCount = digitCount + 1 End If If hasInvalidCharacter Or (digitCount <> 10) Then Return False Else Return True End If End Function Function isDigit(ByVal digit As String) As Boolean If (digit.Length = 1) And (digit >= "0") And (digit <= "9") Then Return True Else Return False End If End Function
Instructor Solutions Manual (Page 205 of 221) Function isValidISBN(ByVal isbn As String) As Boolean Dim isbnDigits(9) As Integer Dim i, j As Integer 'array index/loop variable Dim strPos As Integer 'position in string Dim checksum As Integer 'Checks a properly formatted ISBN string to see if the number is valid 'according to checksum formula i = 1 strPos = 1 Do While i <= 9 If (isbn.Substring(strPos - 1, 1) <> "-") Then isbnDigits(i - 1) = CInt(isbn.Substring(strPos - 1, 1)) i = i + 1 End If strPos = strPos + 1 Loop If isbn.Substring(isbn.Length - 1, 1) = "X" Then isbnDigits(9) = 10 Else isbnDigits(9) = CInt(isbn.Substring(isbn.Length - 1, 1)) End If checksum = 0 For j = 0 To 9 checksum = checksum + (10 - j) * isbnDigits(j) Next If checksum Mod 11 = 0 Then Return True Else Return False End If End Function
Instructor Solutions Manual (Page 206 of 221) 3. Dim scores() As Double Private Sub frmGrades_Load(...) Handles MyBase.Load 'Read exam scores into the scores array Dim temp() As String = IO.File.ReadAllLines("Scores.txt") Dim query1 = From str In temp Select CDbl(str) scores = query1.ToArray End Sub Private Sub btnAnalyze_Click(...) Handles btnAnalyze.Click Dim m = scores.Average Dim query2 = From num In scores Select (num - m) ^ 2 Dim sd = Math.Sqrt(query2.Sum / scores.Count) txtNum.Text = CStr(scores.Count) txtMean.Text = m.ToString("N") txtStDev.Text = sd.ToString("N") Dim query3 = From num In scores Let grade = GetGrade(num, m, sd) Select num, grade dgvOutput.DataSource = query3.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("num").HeaderText = "Score" dgvOutput.Columns("grade").HeaderText = "Grade" End Sub Function GetGrade(score As Double, m As Double, sd As Double) As String Select Case score Case Is >= m + 1.5 * sd Return "A" Case Is >= m + 0.5 * sd Return "B" Case Is >= m - 0.5 * sd Return "C" Case Is >= m - 1.5 * sd Return "D" Case Else Return "F" End Select End Function
Instructor Solutions Manual (Page 207 of 221) 4. Dim degrees() As String = IO.File.ReadAllLines("Degrees.txt") Private Sub btnDegrees_Click(...) Handles btnDegrees.Click 'Show table of degrees conferred in 1980 and 2010 Dim query = From line In degrees _ Let field = line.Split(","c)(0) Let deg1981 = (CInt(line.Split(","c)(1))).ToString("N0") Let deg2010 = (CInt(line.Split(","c)(2))).ToString("N0") Order By field Ascending Select field, deg1981, deg2010 dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("field").HeaderText = "Field of Study" dgvOutput.Columns("deg1981").HeaderText = "1981" dgvOutput.Columns("deg2010").HeaderText = "2010" End Sub Private Sub btnChanges_Click(...) Handles btnChanges.Click 'Show table of percentage changes in degrees from 1981 to 2006 Dim query = From line In degrees Let field = line.Split(","c)(0) Let deg1981 = CInt(line.Split(","c)(1)) Let deg2010 = CInt(line.Split(","c)(2)) Let perGrowth = (deg2010 - deg1981) / deg1981 Order By perGrowth Descending Let formattedPerGrowth = perGrowth.ToString("P1") Select field, formattedPerGrowth dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("field").HeaderText = "Field of Study" dgvOutput.Columns("formattedPerGrowth").HeaderText = "Change (1981-2010)" End Sub Private Sub btnHistogram_Click(...) Handles btnHistogram.Click 'Histogram of degrees in 2010 Dim query = From line In degrees Let field = line.Split(","c)(0) Let deg1981 = CInt(line.Split(","c)(1)) Let deg2010 = CInt(line.Split(","c)(2)) Order By deg2010 Ascending _ Let bar = Stars(deg2010 / 10000) Let formatteddeg2010 = deg2010.ToString("N0") Select field, bar, formatteddeg2010 dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("field").HeaderText = "Field of Study" dgvOutput.Columns("bar").HeaderText = "" dgvOutput.Columns("formatteddeg2010").HeaderText = "Degrees in 2010" End Sub Private Sub btnQuit_Click(...) Handles btnQuit.Click Me.Close() End Sub
Instructor Solutions Manual (Page 208 of 221) Function Stars(numStars As Double) As String 'Display a row of stars Dim row As String = "" For i As Integer = 1 To CInt(numStars) row &= Chr(149) Next Return row End Function
Instructor Solutions Manual (Page 209 of 221) 5. 'Rudimentary translator Dim dictionary() As String = IO.File.ReadAllLines("DICTIONARY.TXT") Private Sub btnTranslate_Click(...) Handles btnTranslate.Click 'Translate English sentence to French and German. Dim sentence As String = txtSentence.Text If sentence.EndsWith(".") Then sentence = sentence.Substring(0, sentence.Length - 1) 'delete period End If Dim engWords() As String = sentence.Split(" "c) Dim frWords(engWords.GetUpperBound(0)) As String Dim gerWords(engWords.GetUpperBound(0)) As String Dim i As Integer = 0 For Each word In engWords Dim query = From line In dictionary Let english = line.Split(","c)(0) Let french = line.Split(","c)(1) Let german = line.Split(","c)(2) Where english = word.ToUpper Select french, german If query.Count = 0 Then frWords(i) = engWords(i).ToUpper gerWords(i) = engWords(i).ToUpper Else frWords(i) = query.First.french gerWords(i) = query.First.german End If i += 1 Next txtFrench.Text = Join(frWords, " "c) & "." txtGerman.Text = Join(gerWords, " "c) & "." End Sub
Instructor Solutions Manual (Page 210 of 221) 6. Structure Team Dim name As String Dim wins As Integer End Structure Dim teams(5) As Team 'Holds the league data Dim winners(5, 5) As Boolean 'True if the first team won Private Sub frmSoccer_Load(...) Handles MyBase.Load teams(0).name = "Jazz" teams(1).name = "Jets" teams(2).name = "Owls" teams(3).name = "Rams" teams(4).name = "Cubs" teams(5).name = "Zips" winners(0, 1) = True 'True means team (#0) won winners(0, 2) = True winners(0, 3) = False 'False means second team (#3) won winners(0, 4) = False winners(0, 5) = True winners(1, 2) = True winners(1, 3) = True winners(1, 4) = False winners(1, 5) = False winners(2, 3) = False winners(2, 4) = True winners(2, 5) = True winners(3, 4) = True winners(3, 5) = True winners(4, 5) = True For i As Integer = 0 To 4 For j As Integer = (i + 1) To 5 If winners(i, j) Then teams(i).wins += 1 'First team won Else teams(j).wins += 1 'Second team won End If Next Next End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From team In teams Let name = team.name Let wins = team.wins Order By team.wins Descending Select name, wins dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "Team" dgvOutput.Columns("wins").HeaderText = "Wins" End Sub
Instructor Solutions Manual (Page 211 of 221) 7. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim hand(3, 12), suits(3), denoms(12) As Integer InputCard(hand, suits, denoms, txtDenomination1.Text, mtxtSuit1.Text) InputCard(hand, suits, denoms, txtDenomination2.Text, mtxtSuit2.Text) InputCard(hand, suits, denoms, txtDenomination3.Text, mtxtSuit3.Text) InputCard(hand, suits, denoms, txtDenomination4.Text, mtxtSuit4.Text) InputCard(hand, suits, denoms, txtDenomination5.Text, mtxtSuit5.Text) 'Determine and display score txtOutput.Text = "The hand is " & GetScore(hand, suits, denoms) & "." End Sub Sub InputCard(ByRef hand(,) As Integer, ByRef suits() As Integer, ByRef denoms() As Integer, denomStr As String,suitStr As String) 'Store the card into the array Dim denom As Integer = CInt(denomStr) - 1 Dim suit As Integer Select Case suitStr.ToUpper 'Determine suit Case "C" 'Clubs suit = 0 Case "D" 'Diamonds suit = 1 Case "H" suit = 2 'Hearts Case Else suit = 3 'All other input means Spades End Select hand(suit, denom) = 1 'Set indicies for card to 1 suits(suit) += 1 'Increment counter for suit denoms(denom) += 1 'Increment counter for denomination End Sub Function GetScore(hand(,) As Integer, suits() As Integer, denoms() As Integer) As String 'Determine score of the hand, starting with highest type If IsFlush(suits) And IsStraight(hand) Then If IsAnySuit(hand, 0) And IsAnySuit(hand, 12) Then Return "a royal straight flush" Else Return "a straight flush" End If End If If IsFlush(suits) Then Return "a flush" End If If IsFullHouse(denoms) Then Return "a full house" End If If IsFourOfAKind(denoms) Then Return "four of a kind" End If If IsStraight(hand) Then Return "a straight" End If If IsThreeOfAKind(denoms) Then Return "three of a kind" End If If IsTwoPair(denoms) Then Return "two pairs" End If If IsOnePair(denoms) Then Return "one pair" End If Return "nothing" 'No result End Function
Instructor Solutions Manual (Page 212 of 221)
Function IsFlush(suits() As Integer) As Boolean 'Test for a flush in each suit For suit As Integer = 0 To 3 If suits(suit) = 5 Then Return True End If Next Return False End Function Function IsStraight(hand(,) As Integer) As Boolean 'Test for a straight Dim denom As Integer = 13 Do 'Find highest denomination denom = denom - 1 Loop Until IsAnySuit(hand, denom) 'If highest denomination is less than a 4 then there is no straight If denom < 4 Then Return False End If For length As Integer = 1 To 3 'Test three earlier denominations If Not IsAnySuit(hand, denom - length) Then Return False End If Next If denom = 12 Then 'If highest is a king, check for nine or ace If IsAnySuit(hand, 8) Or IsAnySuit(hand, 0) Then Return True Else Return False End If Else 'If highest is not a king, test for the fifth card Return IsAnySuit(hand, denom - 4) End If End Function Function IsAnySuit(hand(,) As Integer, denom As Integer) As Boolean 'Test for a 1 for any suit of the given denomination For suit As Integer = 0 To 3 If hand(suit, denom) = 1 Then Return True End If Next Return False End Function Function IsFullHouse(denoms() As Integer) As Boolean 'Test for a full house in any suit For denom As Integer = 0 To 12 'If any denomination is 1, 4 or 5, then no If (denoms(denom) = 1) Or (denoms(denom) > 3) Then Return False End If Next Return True 'That is, all denominations are either 0, 2 or 3. End Function
Instructor Solutions Manual (Page 213 of 221) Function IsFourOfAKind(denoms() As Integer) As Boolean 'True if any suit has a four-of-a-kind For denom As Integer = 0 To 12 If denoms(denom) = 4 Then 'If four cards with this denomination Return True End If Next Return False End Function Function IsThreeOfAKind(denoms() As Integer) As Boolean 'Test for three of a kind in any suit For denom As Integer = 0 To 12 If denoms(denom) = 3 Then 'If three cards with this denomination Return True End If Next Return False End Function Function IsTwoPair(denoms() As Integer) As Boolean 'Test for two pairs Dim count As Integer = 0 For denom As Integer = 0 To 12 If denoms(denom) = 2 Then 'If two cards with this denomination count += 1 End If Next If count = 2 Then Return True Else Return False End If End Function Function IsOnePair(denoms() As Integer) As Boolean 'Test for one pair in any suit For denom As Integer = 0 To 12 'If any denomination is 2, then yes If denoms(denom) = 2 Then Return True End If Next Return False End Function
Instructor Solutions Manual (Page 214 of 221) 8. Dim seats(9, 3) As String Dim waiting(99) As String Dim wait As Integer = 0
'Holds passenger's name in each seat 'Max 100 persons on waiting list 'Number of persons on waiting list
Private Sub frmAirplane_Load(...) Handles MyBase.Load 'Displays the seating chart DisplaySeats() End Sub Sub DisplaySeats() 'Display the seating chart Dim rowStr As String lstOutput.Items.Clear() For row As Integer = 0 To 9 rowStr = "" For seat As Integer = 0 To 3 If seats(row, seat) <> "" Then rowStr &= " X" Else rowStr &= " ." End If If seat = 1 Then 'Display spaces for aisle rowStr &= " " End If Next lstOutput.Items.Add(rowStr) Next End Sub Sub DisplayWaiting() 'Display the waiting list lstWaiting.Items.Clear() For i As Integer = 0 To wait - 1 lstWaiting.Items.Add(waiting(i)) Next End Sub Private Sub btnAdd_Click(...) Handles btnAdd.Click 'Add a passenger to the flight, either chart or waiting list Dim seat As Integer 'Count number of empty seats Dim count As Integer = 0 For rw As Integer = 0 To 9 For st As Integer = 0 To 3 If seats(rw, st) = "" Then count += 1 End If Next Next If count = 0 Then 'If no empty seats then add name to waiting list. wait += 1 waiting(wait - 1) = txtName.Text DisplayWaiting() Else 'Otherwise get the seat and add name to array Select Case txtSeat.Text.Substring(txtSeat.Text.Length - 1).ToUpper Case "A" seat = 0 Case "B" seat = 1
Instructor Solutions Manual (Page 215 of 221) Case "C" seat = 2 Case Else seat = 3 End Select Dim row As Integer = CInt(txtSeat.Text.Substring(0,txtSeat.Text.Length - 1)) - 1 If seats(row, seat) <> "" Then 'If seat is taken MessageBox.Show("The seat is taken.", "Taken") Else seats(row, seat) = txtName.Text 'Add the name to the array txtName.Clear() 'Reset input txtSeat.Clear() txtName.Focus() DisplaySeats() 'Display seating chart End If End If End Sub Private Sub btnDelete_Click(...) Handles btnDelete.Click For rw As Integer = 0 To 9 For st As Integer = 0 To 3 If seats(rw, st) = txtName.Text Then If wait > 0 Then seats(rw, st) = waiting(0) 'Add first person from list wait = wait - 1 'Decrement counter and shift waiting list For i As Integer = 0 To wait - 1 waiting(i) = waiting(i + 1) Next DisplayWaiting() 'Display the new waiting list Else seats(rw, st) = "" 'Clear the seat DisplaySeats() 'Display the seating chart End If txtName.Clear() End If Next Next If txtName.Text <> "" Then 'If name not found then display message MessageBox.Show("Name not found in reservation.") End If End Sub Private Sub btnQuit_Click(...) Handles btnQuit.Click End End Sub
Instructor Solutions Manual (Page 216 of 221) 9. Dim current(1, 1) As Boolean Dim generation As Integer = 1 Private Sub frmLife_Load(...) Handles MyBase.Load NewGame() End Sub Private Sub btnNew_Click(...) Handles btnNew.Click 'When the New button is pressed, start a new game NewGame() End Sub Sub NewGame() Dim input As String 'Get the size of the new game Dim size As Integer = CInt(InputBox("Enter the size of the grid", "Size of grid")) 'Redimension the current generation to the size ReDim current(size, size) 'Set the default row to all dashes 'Get the initial generation For row As Integer = 1 To size input = InputBox("Enter the row #" & row & " of " & size & " with 1s and dashes:", "Enter row #" & row) 'Parse the input into the array For column As Integer = 1 To size current(row, column) = (input.Substring(column - 1, 1) = "1") Next Next generation = 1 Display() End Sub Sub Display() 'Display the current generation in the list box Dim output As String Dim size As Integer = current.GetUpperBound(0) 'Build each row of output lstGeneration.Items.Clear() Dim count As Integer = 0 For row As Integer = 1 To size 'Bulid the output string from each column output = "" For column As Integer = 1 To size If current(row, column) Then output = output & "1" count += 1 Else output = output & "-" End If Next 'Display the output string lstGeneration.Items.Add(output) Next 'Display the number of individuals txtIndividuals.Text = CStr(count) 'Update the generation button for the next one btnGeneration.Text = "Generation #" & generation End Sub
Instructor Solutions Manual (Page 217 of 221) Private Sub btnGeneration_Click(...) Handles btnGeneration.Click Dim size As Integer = current.GetUpperBound(0) 'Create a new array for the future generation Dim future(size, size) As Boolean 'Populate the future using the current For row As Integer = 1 To size For column As Integer = 1 To size future(row, column) = Survives(row, column) Next Next 'Update the current generation with the future current = future generation += 1 'Display the current generation Display() End Sub Function Survives(row As Integer, column As Integer) As Boolean 'Determine whether the individual at row, column survives Dim size As Integer = current.GetUpperBound(0) Dim count As Integer = 0 'Loop over all neighbors of the individual from the row above to the row below For r As Integer = row - 1 To row + 1 'Loop from the column before to the column after For c As Integer = (column – 1) To (column + 1) 'If the neighbor exists and is not the individual If ((r <> row) Or (c <> column)) And (r >= 1) And (r <= size) And (c >= 1) And (c <= size) Then 'If the neighbor is alive then count it If current(r, c) Then count += 1 End If End If Next Next If current(row, column) Then 'Return the result 'If individual exists then neighbors must be 2 or 3 to survive Return (count = 2) Or (count = 3) Else Return (count = 3) End If End Function
Instructor Solutions Manual (Page 218 of 221) 10. 'User-operated directory assistance Dim workers() As String = IO.File.ReadAllLines("Employees.txt") Private Sub btnInstructions_Click(...) Handles btnInstructions.Click MessageBox.Show("Enter the first three letters of the person's last " & "name followed by the first letter of " & "the person's first name. ", "Instructions") End Sub Private Sub btnAnother_Click(...) Handles btnAnother.Click lstDisplay.Items.Clear() txtCode.Text = "" End Sub Private Function GetCode(last As String, first As String) As String Dim word, code As String word = (last.Substring(0, 3) & first.Substring(0, 1)).ToUpper code = "" For i As Integer = 0 To 3 code &= Translate(word.Substring(i, 1)) Next i Return code End Function Private Function Translate(letter As String) As Integer Select Case letter Case "A", "B", "C" Return 2 Case "D", "E", "F" Return 3 Case "G", "H", "I" Return 4 Case "J", "K", "L" Return 5 Case "M", "N", "O" Return 6 Case "P", "Q", "R", "S" Return 7 Case "T", "U", "V" Return 8 Case "W", "X", "Y", "Z" Return 9 End Select End Function Private Sub Button2_Click(...) Handles Button2.Click If txtCode.Text.Length < 4 Then txtCode.Text &= "2" If txtCode.Text.Length = 4 Then DisplayNames() End If End If End Sub
Instructor Solutions Manual (Page 219 of 221) Private Sub Button3_Click(...) Handles Button3.Click If txtCode.Text.Length < 4 Then txtCode.Text &= "3" If txtCode.Text.Length = 4 Then DisplayNames() End If End If End Sub Private Sub Button4_Click(...) Handles Button4.Click If txtCode.Text.Length < 4 Then txtCode.Text &= "4" If txtCode.Text.Length = 4 Then DisplayNames() End If End If End Sub Private Sub Button5_Click(...) Handles Button5.Click If txtCode.Text.Length < 4 Then txtCode.Text &= "5" If txtCode.Text.Length = 4 Then DisplayNames() End If End If End Sub Private Sub Button6_Click(...) Handles Button6.Click If txtCode.Text.Length < 4 Then txtCode.Text &= "6" If txtCode.Text.Length = 4 Then DisplayNames() End If End If End Sub Private Sub Button7_Click(...) Handles Button7.Click If txtCode.Text.Length < 4 Then txtCode.Text &= "7" If txtCode.Text.Length = 4 Then DisplayNames() End If End If End Sub Private Sub Button8_Click(...) Handles Button8.Click If txtCode.Text.Length < 4 Then txtCode.Text &= "8" If txtCode.Text.Length = 4 Then DisplayNames() End If End If End Sub
Instructor Solutions Manual (Page 220 of 221) Private Sub Button9_Click(...) Handles Button9.Click If txtCode.Text.Length < 4 Then txtCode.Text &= "9" If txtCode.Text.Length = 4 Then DisplayNames() End If End If End Sub Private Sub DisplayNames() Dim query = From line In workers Let lastName = line.Split(","c)(0) Let firstName = line.Split(","c)(1) Let ext = line.Split(","c)(2) Let code = GetCode(lastName, firstName) Where code = txtCode.Text Select firstName, lastName, ext If query.Count = 0 Then lstDisplay.Items.Add("Could not find a matching name.") lstDisplay.Items.Add("Please try again.") Else For Each worker In query lstDisplay.Items.Add(worker.firstName & " " & worker.lastName & " x" & worker.ext) Next End If End Sub
Instructor Solutions Manual (Page 221 of 221) 11. Structure Auto Dim model As String Dim count As Integer Dim gallons As Double End Structure
'Name of the model 'Number of cars tested 'Total number of gallons used
Dim cars(4) As Auto 'Holds data Dim vehicles() As String = IO.File.ReadAllLines("Mileage.txt") Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim query1 = From line In vehicles Let make = line.Split(","c)(0) Select make Dim temp() = query1.ToArray For i As Integer = 0 To 4 cars(i).model = temp(i) cars(i).count = NumCars(temp(i)) cars(i).gallons = NumGals(temp(i)) Next Dim query2 = From car In cars Let mpg = 100 * car.count / car.gallons Order By mpg Descending Let formattedMPG = mpg.ToString("N") Select car.model, formattedMPG dgvOutput.DataSource = query2.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("model").HeaderText = "Model" dgvOutput.Columns("formattedMPG").HeaderText = "MPG" End Sub Function NumCars(make As String) As Integer Dim query = From line In vehicles Let brand = line.Split(","c)(0) Where brand = make Select brand Return query.Count End Function Function NumGals(make As String) As Double Dim query = From line In vehicles Let brand = line.Split(","c)(0) Let gallons = CDbl(line.Split(","c)(1)) Where brand = make Select gallons Return query.Sum End Function
Get complete Order files download link below htps://www.mediafire.com/file/�351cwx7zi5x55/SM+ An+Introduc�on+to+Programming+Using+Visual+Basic +2012,+9e+David+Schneider.zip/file
If this link does not work with a click, then copy the complete Download link and paste link in internet explorer/firefox/google chrome and get all files download successfully.
Part 2 SOLUTIONS MANUAL For An Introduction to Programming Using Visual Basic 2012, 9th Edition by David I. Schneider Part B Chapters 8 through 11
Instructor Solutions Manual (Page 3 of 196)
CONTENTS Chapter 8 Text Files Exercises 8.1 Managing Text Files 4 Exercises 8.2 StreamReaders, StreamWriters, Structured Exception Handling 13 Exercises 8.3 XML 21 Programming Projects 29 Chapter 9 Additional Controls and Objects Exercises 9.1 List Boxes and Combo Boxes 39 Exercises 9.2 Eight Additional Controls and Objects 44 Exercises 9.3 Multiple-Form Programs 56 Exercises 9.4 Graphics 73 Programming Projects 90 Chapter 10 Databases Exercises 10.1 An Introduction to Databases 106 Exercises 10.2 Editing and Designing Databases 131 Programming Projects 134 Chapter 11 Object-Oriented Programming Exercises 11.1 Classes and Objects 136 Exercises 11.2 Working with Objects 148 Exercises 11.3 Inheritance 171 Programming Projects 184
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
Instructor Solutions Manual (Page 64 of 196) Else 'INIT_FILE does not exist, so get initial data from user Dim sw As IO.StreamWriter nameOnChk = InputBox("Name to appear on checks:") Try curBal = CDbl(InputBox("Starting Balance:")) 'Get numbers of last check and deposit slip lastCkNum = CInt(InputBox("Number of first check:")) - 1 lastDpNum = CInt(InputBox("Number of first deposit slip:")) - 1 'The single record in the text file records the name to 'appear on checks plus the initial data for account Dim outputLine As String = nameOnChk & "," & curBal & "," & lastCkNum & "," & lastDpNum sw = IO.File.CreateText(INIT_FILE) sw.WriteLine(outputLine) Catch 'If a number cannot be converted then display message and quit MessageBox.Show("Invalid number. Program terminating.", "Error") Me.Close() Finally 'Close the writer no matter what happens above sw.Close() End Try End If End Sub Private Sub btnRecord_Click(...) Handles btnRecord.Click 'Store the input into the transactions file Dim amt As Double Dim transType As String 'Only store if all required fields are filled and valid If DataValid() Then amt = CDbl(txtAmount.Text) 'Adjust balance by amount depending on check or deposit slip mode If isCheck Then curBal = curBal - amt lastCkNum = CInt(txtNum.Text) transType = "Check" Else curBal += amt lastDpNum = CInt(txtNum.Text) transType = "Deposit" End If txtBalance.Text = curBal.ToString("C") 'String array contains info to be stored Dim transOutput() As String = {transType, txtToFrom.Text, CStr(curBal), CStr(lastCkNum), CStr(lastDpNum), CStr(amt), txtMemo.Text, txtDate.Text} Dim sw As IO.StreamWriter = IO.File.AppendText(TRANS_FILE) 'Append the info to the text file, separated by the separator sw.WriteLine(Join(transOutput, ",")) sw.Close() 'Reset input text boxes to blank for next entry ResetInput() End If End Sub
Instructor Solutions Manual (Page 65 of 196) Function DataValid() As Boolean 'Returns True if all data are valid, or displays a message if not Dim errorMessage As String = "" 'If one of the two essential pieces of information 'is missing, assign its name to errorMessage If txtToFrom.Text.Trim = "" Then If isCheck Then errorMessage = "Pay To" Else errorMessage = "Source" End If txtToFrom.Focus() ElseIf txtAmount.Text.Trim = "" Then errorMessage = "Amount" txtAmount.Focus() End If 'If no errors yet then check syntax of the two numerical fields If errorMessage = "" Then 'Check syntax of the amount field (Double) Try If CDbl(txtAmount.Text) <= 0 Then errorMessage = "The amount must be greater than zero." txtAmount.Focus() End If Catch exc As InvalidCastException errorMessage = "The amount " & txtAmount.Text & " is invalid." txtAmount.Focus() End Try Else errorMessage = "The '" & errorMessage & "' field must be filled." End If 'Display error message if available If errorMessage = "" Then 'All required data fields have been filled; recording can proceed Return True Else 'Advise user of invalid data MessageBox.Show(errorMessage & " Please try again.") Return False End If End Function Private Sub btnMode_Click(...) Handles btnMode.Click 'Toggle mode between Check and Deposit Slip If isCheck Then SetupDeposit() Else SetupCheck() End If 'Set fields for next entry ResetInput() End Sub
Instructor Solutions Manual (Page 66 of 196) Sub SetupCheck() 'Prepare form for the entry of a check isCheck = True Me.Text = "Check" 'Sets the title bar of the form lblToFrom.Text = "Pay To" btnRecord.Text = "&Record This Check" btnMode.Text = "&Switch to Deposits" Me.BackColor = Color.LightGray End Sub Sub SetupDeposit() 'Prepare form for the entry of a deposit isCheck = False Me.Text = "Deposit Slip" 'Sets the title bar of the form lblToFrom.Text = "Source" btnRecord.Text = "&Record This Deposit" btnMode.Text = "&Switch to Checks" Me.BackColor = Color.Yellow End Sub Sub ResetInput() 'Reset all text entry fields except date txtToFrom.Clear() txtAmount.Clear() txtMemo.Clear() If isCheck Then 'Make txtNum text box reflect next check number txtNum.Text = CStr(lastCkNum + 1) Else 'Make txtNum text box reflect next deposit slip number txtNum.Text = CStr(lastDpNum + 1) End If 'Set focus on to/from control for the next entry txtToFrom.Focus() End Sub Private Sub btnReport_Click(...) Handles btnReport.Click If IO.File.Exists(TRANS_FILE) Then Form2.ShowDialog() Else MessageBox.Show("There are no transactions to report.") End If End Sub Function FormNumber(type As String, checkNumber As String, depositNumber As String) As String If type = "Check" Then Return "Check #" & checkNumber Else Return "Deposit #" & depositNumber End If End Function
Instructor Solutions Manual (Page 67 of 196) Private Sub btnQuit_Click(...) Handles btnQuit.Click Me.Close() 'Exit the program End Sub
Form2's Code Private Sub Form2_Load(...) Handles MyBase.Load Dim transFileContents() = IO.File.ReadAllLines(frmAccount.TRANS_FILE) Dim query = From trans In transFileContents Let data = trans.Split(","c) Let transDate = CDate(data(7)) Let number = frmAccount.FormNumber(data(0), data(3), data(4)) Let toFrom = data(1) Let Memo = data(6) Let Amount = (CDbl(data(5))).ToString("C") Let Balance = (CDbl(data(2))).ToString("C") Select transDate, number, toFrom, Memo, Amount, Balance dgvTransactions.DataSource = query.ToList dgvTransactions.Columns("transDate").HeaderText = "Transaction Date" dgvTransactions.Columns("number").HeaderText = "Description" dgvTransactions.Columns("toFrom").HeaderText = "Recipient or Source" End Sub
Instructor Solutions Manual (Page 68 of 196) 10. 'Form1's code Structure Student Dim name As String Dim exam1 As Double Dim exam2 As Double Dim exam3 As Double End Structure Public numStudents As Integer = 0 Public students(50) As Student Public totalGrades As Double = 0 Private Sub Form1_Load(...) Handles MyBase.Load Form2.ShowDialog() End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click txtAverage.Text = (totalGrades / (3 * numStudents)).ToString("N1") ReDim Preserve students(numStudents - 1) Dim query = From student In students Let Name = student.name Let Average = ((student.exam1 + student.exam2 + student.exam3) / 3).ToString("N0") Select Name, Average dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing End Sub 'Form2's code Private Sub Form2_Load(...) Handles MyBase.Load Me.Text = "Student #1" End Sub Private Sub btnRecord_Click(...) Handles btnRecord.Click Dim sum As Double Form1.students(Form1.numStudents).name = txtName.Text Form1.students(Form1.numStudents).exam1 = CDbl(txtExam1.Text) Form1.students(Form1.numStudents).exam2 = CDbl(txtExam2.Text) Form1.students(Form1.numStudents).exam3 = CDbl(txtExam3.Text) sum = CDbl(txtExam1.Text) + CDbl(txtExam2.Text) + CDbl(txtExam3.Text) Form1.totalGrades += sum txtName.Clear() txtExam1.Clear() txtExam2.Clear() txtExam3.Clear() txtName.Focus() Form1.numStudents += 1 Me.Text = "Student #" & (Form1.numStudents + 1) End Sub Private Sub btnTerminate_Click(...) Handles btnTerminate.Click Me.Close() End Sub
Instructor Solutions Manual (Page 69 of 196)
11. 'Form1's code (Customer) Private Sub btnGet_Click(...) Handles btnGet.Click If radBillCust.Checked Then Form2.ShowDialog() Else Form3.ShowDialog() End If End Sub 'Form2's code (Customer Info) Private Sub Form2_Load(...) Handles MyBase.Load txtName.Text = Form1.txtName.Text End Sub Private Sub btnRecord_Click(...) Handles btnRecord.Click Dim city, state, zip As String Form1.lstOutput.Items.Add("Mail bill to:") Form1.lstOutput.Items.Add(txtName.Text) Form1.lstOutput.Items.Add(txtAddress.Text) city = txtCity.Text state = cboState.Text zip = txtZip.Text Form1.lstOutput.Items.Add(city & ", " & state & " " & zip) Me.Close() End Sub
Instructor Solutions Manual (Page 70 of 196) 'Form3's code (Credit Card Info) Private Sub Form3_Load(...) Handles MyBase.Load Dim num As Integer = Today.Year For i As Integer = num To (num + 5) cboYear.Items.Add(i) Next End Sub Private Sub btnRecord_Click(...) Handles btnRecord.Click Form1.lstOutput.Items.Add("Bill " & cboCard.Text) Form1.lstOutput.Items.Add("Name on card: " & txtName.Text) Form1.lstOutput.Items.Add("Card number: " & txtCardNumber.Text) Form1.lstOutput.Items.Add("Expiration date: " & cboMonth.Text & "/" & cboYear.Text) Me.Close() End Sub
Instructor Solutions Manual (Page 71 of 196) 12. 'frmNumber's code Private Sub btnShow_Click(...) Handles btnShow.Click 'Display the second form, and get the number. frmButtons.ShowDialog() 'After the second form is closed, display the value of 'its variable number in the first form's text box. txtOutput.Text = frmButtons.number End Sub 'frmButton's code Public number As String = "" Private Sub btn1_Click(...) Handles btn1.Click dial(1) End Sub Private Sub btn2_Click(...) Handles btn2.Click dial(2) End Sub Private Sub btn3_Click(...) Handles btn3.Click dial(3) End Sub Private Sub btn4_Click(...) Handles btn4.Click dial(4) End Sub Private Sub btn5_Click(...) Handles btn5.Click dial(5) End Sub Private Sub btn6_Click(...) Handles btn6.Click dial(6) End Sub Private Sub btn7_Click(...) Handles btn7.Click dial(7) End Sub Private Sub btn8_Click(...) Handles btn8.Click dial(8) End Sub Private Sub btn9_Click(...) Handles btn9.Click dial(9) End Sub Private Sub btn0_Click(...) Handles btn0.Click dial(0) End Sub
Get complete Order files download link below htps://www.mediafire.com/file/�351cwx7zi5x55/SM+ An+Introduc�on+to+Programming+Using+Visual+Basic +2012,+9e+David+Schneider.zip/file
If this link does not work with a click, then copy the complete Download link and paste link in internet explorer/firefox/google chrome and get all files download successfully.
Instructor Solutions Manual (Page 72 of 196) Sub dial(num As Integer) 'Add the number to the result, with a hyphen in its fourth position. If number.Length = 3 Then number &= "-" End If number &= CStr(num) txtOutput.Text = number End Sub Private Sub btnClear_Click(...) Handles btnClear.Click 'Clear the output. txtOutput.Clear() number = "" End Sub Private Sub btnEnter_Click(...) Handles btnEnter.Click 'Make frmButtons disappear. The number dialed will 'then appear in frmNumbers's text box. Me.Close() End Sub
Instructor Solutions Manual (Page 73 of 196) EXERCISES 9.4 1. Private Sub btnDraw_Click(...) Handles btnDraw.Click Dim gr As Graphics = picBox.CreateGraphics Dim x As Double = picBox.Width / 2 Dim y As Double = picBox.Height / 2 Dim r As Double = x / 2 If r > y / 2 Then r = y / 2 End If gr.FillEllipse(Brushes.Black, CSng(x - r), CSng(y - r), CSng(2 * r), CSng(2 * r)) End Sub
2. Private Sub btnDraw_Click(...) Handles btnDraw.Click Dim gr As Graphics = picBox.CreateGraphics Dim x As Double = picBox.Width / 2 Dim y As Double = picBox.Height / 2 Dim r As Double = x / 2 If r > y / 2 Then r = y / 2 End If gr.FillEllipse(Brushes.Black, CSng(x), CSng(y - r), CSng(2 * r), CSng(2 * r)) End Sub
Instructor Solutions Manual (Page 74 of 196) 3. Private Sub btnDraw_Click(...) Handles btnDraw.Click Dim gr As Graphics = picBox.CreateGraphics Dim x As Double = picBox.Width / 2 Dim y As Double = picBox.Height / 2 Dim r As Double = 20 gr.FillEllipse(Brushes.Red, CSng(x - r), CSng(y - r), CSng(2 * r), CSng(2 * r)) r = 19 gr.FillEllipse(Brushes.White, CSng(x - r), CSng(y - r), CSng(2 * r), CSng(2 * r)) End Sub
4. Private Sub btnDraw_Click(...) Handles btnDraw.Click Dim gr As Graphics = picBox.CreateGraphics gr.DrawLine(Pens.Red, 5, 100, 100, 5) gr.DrawLine(Pens.Red, 100, 5, 195, 100) gr.DrawLine(Pens.Red, 5, 100, 195, 100) End Sub
Instructor Solutions Manual (Page 75 of 196) 5. Private Sub btnCreate_Click(...) Handles btnCreate.Click 'Create flag of Italy Dim gr As Graphics = picFlag.CreateGraphics Dim br() As Brush = {Brushes.Green, Brushes.White, Brushes.Red} 'picFlag.Width = 149; picFlag.Height = 99 For i As Integer = 0 To 2 gr.FillRectangle(br(i), 0 + i * 50, 0, 50, 99) Next gr.DrawLine(Pens.Black, 0, 0, 148, 0) 'top border gr.DrawLine(Pens.Black, 0, 0, 0, 98) 'left border gr.DrawLine(Pens.Black, 0, 98, 148, 98) 'bottom border gr.DrawLine(Pens.Black, 148, 0, 148, 98) 'right border End Sub
Italy
Switzerland
6. Private Sub btnCreate_Click(...) Handles btnCreate.Click 'Create Swiss flag Dim gr As Graphics = picFlag.CreateGraphics 'picFlag.Width = 99, picFlag.Height = 99 gr.FillRectangle(Brushes.Red, 0, 0, 98, 98) gr.FillRectangle(Brushes.White, 40, 18, 18, 63) gr.FillRectangle(Brushes.White, 18, 40, 63, 18) End Sub
Instructor Solutions Manual (Page 76 of 196) 7. Private Sub btnCreate_Click(...) Handles btnCreate.Click 'Create flag of Niger Dim gr As Graphics = picFlag.CreateGraphics Dim br() As Brush = {Brushes.Orange, Brushes.White, Brushes.Green} Dim r As Integer = 12 'radius of circle 'picFlag.Width = 149; picFlag.Height = 99 For i As Integer = 0 To 2 gr.FillRectangle(br(i), 0, 0 + i * 33, 149, 33) Next gr.FillPie(Brushes.Orange, 75 - r, 49 - r, 2 * r, 2 * r, 0, 360) gr.DrawLine(Pens.Black, 0, 0, 148, 0) 'top border gr.DrawLine(Pens.Black, 0, 0, 0, 98) 'left border gr.DrawLine(Pens.Black, 0, 98, 148, 98) 'bottom border gr.DrawLine(Pens.Black, 148, 0, 148, 98) 'right border End Sub
Niger
Greenland
8. Private Sub btnCreate_Click(...) Handles btnCreate.Click 'Create flag of Greenland Dim gr As Graphics = picFlag.CreateGraphics Dim r As Integer = 40 'picFlag.Width = 149, picFlag.Height = 99 gr.FillRectangle(Brushes.White, 0, 0, 149, 49) gr.FillRectangle(Brushes.Red, 0, 49, 149, 49) gr.DrawLine(Pens.Black, 0, 0, 148, 0) 'top border gr.DrawLine(Pens.Black, 0, 0, 0, 98) 'left border gr.DrawLine(Pens.Black, 0, 98, 148, 98) 'bottom border gr.DrawLine(Pens.Black, 148, 0, 148, 98) 'right border gr.FillPie(Brushes.Red, 68 - r, 49 - r, 2 * r, 2 * r, 180, 180) gr.FillPie(Brushes.White, 68 - r, 49 - r, 2 * r, 2 * r, 0, 180) End Sub
Instructor Solutions Manual (Page 77 of 196) 9. Private Sub btnDraw_Click(...) Handles btnDraw.Click Dim numbers As String = "" Dim gr As Graphics = picBox.CreateGraphics picBox.Refresh() Dim n As Integer = CInt(txtNumber.Text) 'Font is Microsoft Sans Serif For i As Integer = 0 To n If i < 9 Then numbers &= i & " " Else numbers &= i & " " End If gr.DrawLine(Pens.Blue, 12 + (24 * i), 5, 12 + (24 * i), 15) Next gr.DrawLine(Pens.Blue, 0, 10, 24 * (n + 1), 10) gr.DrawString(numbers, Me.Font, Brushes.Blue, 8, 20) End Sub
10. Private Sub btnDraw_Click(...) Handles btnDraw.Click Dim gr As Graphics = picOutput.CreateGraphics picOutput.Refresh() For i As Integer = 1 To CInt(mtbNum.Text) gr.DrawLine(Pens.Red, 5, 25 * i, 100, 25 * i) gr.DrawString("LINE " & i, Me.Font, Brushes.Red, 110, 25 * i - 5) Next End Sub
Instructor Solutions Manual (Page 78 of 196)
11. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim legend() As String = {"Soft Drinks", "Beer", "Bottled Water", "Other"} Dim quantity() As Single = {52.9, 14.7, 11.1, 21.3} Dim percent(quantity. Count - 1) As Single Dim sumOfQuantities As Single = 0 Dim sumOfSweepAngles As Single = 0 Dim br() As Brush = {Brushes.Blue, Brushes.Red, Brushes.Tan, Brushes.Green, Brushes.Orange, Brushes.Gray} Dim gr As Graphics = picOutput.CreateGraphics 'The picture box has width 312 and height 215 Dim r As Integer = 100 'Radius of circle Dim c As Integer = 105 'Center of circle is (c, c) Me.Text = "U.S. Recreational Beverage Consumption" 'Sum the numbers for the quantities For i As Integer = 0 To (quantity.Count – 1) sumOfQuantities += quantity(i) Next 'Convert tbe quantities to percents For i As Integer = 0 To (quantity. Count – 1) percent(i) = quantity(i) / sumOfQuantities Next 'Display the pie chart and the legends For i As Integer = 0 To (quantity. Count – 1) gr.FillPie(br(i), c - r, c - r, 2 * r, 2 * r, sumOfSweepAngles, percent(i) * 360) sumOfSweepAngles += percent(i) * 360 gr.FillRectangle(br(i), 220, 20 + 30 * i, 20, 20) gr.DrawString(legend(i), Me.Font, Brushes.Black, 250, 22 + 30 * i) Next End Sub
Instructor Solutions Manual (Page 79 of 196) 12. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim quantity() As Single = {1, 1.15, 2.65, 3.35, 5.15, 7.25} Dim gr As Graphics = picOutput.CreateGraphics Dim dates as String 'The picture box has width 210 and height 150 gr.DrawLine(Pens.Black, 40, 170, picOutput.Width - 20, 170) 'Draw x-axis gr.DrawLine(Pens.Black, 40, 170, 40, 5) 'Draw y-axis gr.DrawLine(Pens.Black, 35, 170 - (7.25 * 20), 45, 170 - (7.25 * 20)) 'ticks gr.DrawString("$7.25", Me.Font, Brushes.Black, 1, 20) Me.Text = "U.S. Minimum Wage" For i As Integer = 0 To (quantity.Count – 1) gr.FillRectangle(Brushes.Blue, 60 + i * 50, (170 - quantity(i) * 20), 20, quantity(i) * 20) Next 'US minimum wage became $7.25 on July 24, 2009. dates = "1959 1968 1978 1988 1998 2009" gr.DrawString(dates, Me.Font, Brushes.Black, 55, 175) End Sub
Instructor Solutions Manual (Page 80 of 196) 13. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim gr As Graphics = picOutput.CreateGraphics Dim smokers() As Single = {11.6, 12.7, 10.0, 7.4, 6.4, 5.3, 4.4} gr.DrawLine(Pens.Black, 30, 100, picOutput.Width, 100) 'x-axis gr.DrawLine(Pens.Black, 30, 100, 30, 0) 'y-axis gr.DrawLine(Pens.Black, 27, 100 - 12.7 * 7, 33, 100 - 12.7 * 7) 'tick mark gr.DrawString("12.7", Me.Font, Brushes.Black, 0, 100 - 12.7 * 7 - 6) gr.DrawString("1998 2000 2002 2004 2006 2008 2010", Me.Font, Brushes.Black, 35, 102) gr.DrawString("Percentage of College Freshmen Who Smoke", Me.Font, Brushes.Blue, 30, 120) gr.DrawString("Source: Higher Education Research Institute", Me.Font, Brushes.Blue, 30, 135) For i As Integer = 0 To (smokers.Count – 2) gr.DrawLine(Pens.Blue, 50 + i * 35, 100 - smokers(i) * 7, 50 + (i + 1) * 35, 100 - smokers(i + 1) * 7) Next For i As Integer = 0 To (smokers.Count – 1) gr.DrawLine(Pens.Black, 50 + i * 35, 95, 50 + i * 35, 100) gr.FillEllipse(Brushes.Blue, 50 + i * 35 - 3, 100 - smokers(i) * 7 - 3, 6, 6) Next End Sub
Instructor Solutions Manual (Page 81 of 196) 14. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim males() As Single = {283, 1375, 2047, 2233, 2398} Dim females() As Single = {170, 945, 2479, 3007, 3358} Dim gr As Graphics = picBox.CreateGraphics gr.DrawLine(Pens.Blue, 30, 100, picBox.Width, 100) 'x-axis gr.DrawLine(Pens.Black, 30, 100, 30, 0) 'y-axis gr.DrawLine(Pens.Black, 27, 100 - females(4) / 40, 33, 100 - females(4) / 40) 'tick mark gr.DrawString(CStr(females(4)), Me.Font, Brushes.Blue, 0, 100 - females(4) / 40 - 6) gr.DrawString("1960 1970 1980 1990 2000", Me.Font, Brushes.Blue, 35, 102) gr.DrawString("Two-Year College Enrollments", Me.Font, Brushes.Blue, 30, 120) gr.DrawString("(in thousands)", Me.Font, Brushes.Blue, 30, 135) For i As Integer = 0 To (males.count – 2) gr.DrawLine(Pens.Red, 50 + i * 35, 100 - females(i) / 40, 50 + (i + 1) * 35, 100 - females(i + 1) / 40) gr.DrawLine(Pens.Green, 50 + i * 35, 100 - males(i) / 40, 50 + (i + 1) * 35, 100 - males(i + 1) / 40) Next For i As Integer = 0 To (males.count – 1) gr.FillEllipse(Brushes.Red, 50 + i * 35 - 3, 100 - females(i) / 40 - 3, 6, 6) gr.FillEllipse(Brushes.Green, 50 + i * 35 - 3, 100 - males(i) / 40 - 3, 6, 6) Next gr.DrawString("males", Me.Font, Brushes.Green, 40, 62) gr.DrawString("females", Me.Font, Brushes.Red, 135, 5) End Sub
Instructor Solutions Manual (Page 82 of 196) 15. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim quantity() As Single = {6.2, 5.4, 4.7, 3.4, 3.2} Dim gr As Graphics = picOutput.CreateGraphics Dim legend As String 'The picture box has width 310 and height 170 gr.DrawLine(Pens.Black, 10, 100, picOutput.Width - 10, 100) x-axis Me.Text = "Most Popular Majors" For i As Integer = 0 To (quantity.Count – 1) gr.FillRectangle(Brushes.Tan, 20 + i * 60, (100 - quantity(i) * 19), 30, quantity(i) * 19) gr.DrawString(((quantity(i)).ToString("N1") & "%"), Me.Font, Brushes.DarkBlue, 21 + i * 60, 85) Next legend = "Biology Psychology Nursing Predent Mechanical" gr.DrawString(legend, Me.Font, Brushes.Blue, 15, 102) legend = "(general) Premed" & " Engineering" gr.DrawString(legend, Me.Font, Brushes.Blue, 12, 115) gr.DrawString("Prevet", Me.Font, Brushes.Blue, 195, 128) gr.DrawString("Most Popular Majors for College Freshmen in Fall 2011", Me.Font, Brushes.Blue, 5, 145) End Sub
Instructor Solutions Manual (Page 83 of 196) 16. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim wellOff() As Single = {59, 74, 73, 77} Dim meaningfulPhil() As Single = {60, 43, 44, 51} Dim legend() As String = {"Be very well off financially", "Develop a meaningful philosophy of life"} Dim gr As Graphics = picOutput.CreateGraphics 'The picture box has width 210 and height 150 gr.DrawLine(Pens.Black, 35, 80, picOutput.Width, 80) 'Draw x-axis gr.DrawLine(Pens.Black, 35, 80, 35, 0) 'Draw y-axis gr.DrawLine(Pens.Black, 30, 80 - 74, 40, 80 - 74) 'Draw tick mark gr.DrawString("74", Me.Font, Brushes.Black, 12, 0) For i As Integer = 0 To 3 gr.FillRectangle(Brushes.Blue, 55 + i * 60, (80 - wellOff(i)), 15, wellOff(i)) Next For i As Integer = 0 To 3 gr.FillRectangle(Brushes.Red, 70 + i * 60, (80 - meaningfulPhil(i)), 15, meaningfulPhil(i)) Next gr.DrawString("1978 1988 1998 2008", Me.Font, Brushes.Black, 55, 82) gr.DrawString("Freshman Life Goals", Me.Font, Brushes.Black, 55, 95) gr.DrawString("(% of students committed to goal)", Me.Font, Brushes.Black, 55, 110) gr.FillRectangle(Brushes.Blue, 35, 135, 15, 15) gr.DrawString(legend(0), Me.Font, Brushes.Black, 53, 135) gr.FillRectangle(Brushes.Red, 35, 155, 15, 15) gr.DrawString(legend(1), Me.Font, Brushes.Black, 53, 155) End Sub
Instructor Solutions Manual (Page 84 of 196) 17. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim legend() As String = {"Bengali", "English", "German", "Hindi", "Japanese", "Mandarin", "Portuguese", "Russian", "Spanish", "Wu"} Dim quantity() As Single = {173, 311, 96, 182, 128, 882, 179, 146, 326, 78} Dim gr As Graphics = picOutput.CreateGraphics Dim caption As String 'The picture box has width 365 and height 185 gr.DrawLine(Pens.Black, 40, 100, picOutput.Width, 100) 'x-axis gr.DrawLine(Pens.Black, 40, 100, 40, 0) 'y-axis gr.DrawLine(Pens.Black, 35, 100 - 88.2, 45, 100 - 88.2) 'tick mark gr.DrawString("882", Me.Font, Brushes.Black, 8, 100 - 88.2 - 6) Me.Text = "Principal Languages" For i As Integer = 0 To (quantity.Count – 1) gr.FillRectangle(Brushes.Blue, 60 + i * 30, (100 - quantity(i) / 10), 15, quantity(i) / 10) Next For i As Integer = 0 To (quantity.Count – 1) Step 2 gr.DrawLine(Pens.Black, 60 + i * 30 + 7, 100, 60 + i * 30 + 7, 110) gr.DrawString(legend(i), Me.Font, Brushes.Black, 60 + i * 30 - 21, 110) Next For i As Integer = 1 To (quantity.Count – 1) Step 2 gr.DrawLine(Pens.Black, 60 + i * 30 + 7, 100, 60 + i * 30 + 7, 130) gr.DrawString(legend(i), Me.Font, Brushes.Black, 60 + i * 30 - 10, 130) Next gr.DrawString("Principal Languages of the World", Me.Font, Brushes.Blue, 90, 150) caption = "(in millions of " & Chr(34) & "first language" & Chr(34) & " speakers)" gr.DrawString(caption, Me.Font, Brushes.Blue, 90, 165) End Sub
Instructor Solutions Manual (Page 85 of 196) 18. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim legend() As String = {"Housing", "Transportation", "Food", "Other"} Dim quantity() As Single = {CSng(mtbHousing.Text), CSng(mtbTransportation.Text), CSng(mtbFood.Text),CSng(mtbOther.Text)} Dim percent(quantity.Count - 1) As Single Dim sumOfQuantities As Single = 0 Dim sumOfSweepAngles As Single = 0 Dim br() As Brush = {Brushes.Blue, Brushes.Red, Brushes.Green, Brushes.Orange} Dim gr As Graphics = picOutput.CreateGraphics 'The picture box has width 312 and height 215 Dim r As Integer = 100 'Radius of circle Dim c As Integer = 105 'Center of circle is (c, c) 'Sum the numbers for the quantities For i As Integer = 0 To (quantity.Count – 1) sumOfQuantities += quantity(i) Next 'Convert tbe quantities to percents For i As Integer = 0 To (quantity.Count – 1) percent(i) = quantity(i) / sumOfQuantities Next 'Display the pie chart and the legends For i As Integer = 0 To (quantity.Count – 1) gr.FillPie(br(i), c - r, c - r, 2 * r, 2 * r, sumOfSweepAngles, percent(i) * 360) sumOfSweepAngles += percent(i) * 360 gr.FillRectangle(br(i), 220, 20 + 30 * i, 20, 20) gr.DrawString(legend(i), Me.Font, Brushes.Black, 250, 22 + 30 * i) Next End Sub
Instructor Solutions Manual (Page 86 of 196) 19. Dim x As Integer = 1 Dim y As Integer = 40 Private Sub frmPlane_Load(...) Handles MyBase.Load Timer1.Enabled = True End Sub Private Sub Timer1_Tick(...) Handles Timer1.Tick If picBox.Left = Me.Width Then picBox.Left = -picBox.Width Else picBox.Left += 1 End If End Sub
Instructor Solutions Manual (Page 87 of 196) 20. Const ONE_INCH As Integer = 100 Const LINE_HEIGHT As Integer = 20
'number of pixels in an inch 'one quarter of an inch
Private Sub btnPrint_Click(...) Handles btnPrint.Click PrintDocument1.Print() End Sub Private Sub PrintDocument1_PrintPage(sender As System.Object, e As System.Drawing.Printing.PrintPageEventArgs) Handles _ PrintDocument1.PrintPage Dim gr As Graphics = e.Graphics Dim x1 As Integer = ONE_INCH 'use one inch beyond left margin Dim x2 As Integer = CInt(1.5 * ONE_INCH) 'offset for second column Dim y As Integer = ONE_INCH 'use one inch top margin Dim font1 As New Font("Courier New", 10, FontStyle.Bold) Dim font2 As New Font("Courier New", 10, FontStyle.Regular) gr.DrawString("PLS", font1, Brushes.Black, x1, y) gr.DrawString("Please", font2, Brushes.Black, x2, y) y += LINE_HEIGHT gr.DrawString("TAFN", font1, Brushes.Black, x1, y) gr.DrawString("That's all for now", font2, Brushes.Black, x2, y) y += LINE_HEIGHT gr.DrawString("HHOK", font1, Brushes.Black, x1, y) gr.DrawString("Ha, ha - only kidding", font2, Brushes.Black, x2, y) y += LINE_HEIGHT gr.DrawString("FWIW", font1, Brushes.Black, x1, y) gr.DrawString("For what its worth", font2, Brushes.Black, x2, y) y += LINE_HEIGHT gr.DrawString("IMHO", font1, Brushes.Black, x1, y) gr.DrawString("In my humble opinion", font2, Brushes.Black, x2, y) End Sub Private Sub btnPreview_Click(...) Handles btnPreview.Click PrintPreviewDialog1.Document = PrintDocument1 PrintPreviewDialog1.ShowDialog() End Sub PLS TAFN HHOK FWIW IMHO
Please That’s all for now Ha, ha - only kidding For what its worth In my humble opinion
Instructor Solutions Manual (Page 88 of 196) 21. Const ONE_INCH As Integer = 100 Const LINE_HEIGHT As Integer = 20
'number of pixels in an inch 'one quarter of an inch
Private Sub btnPrint_Click(...) Handles btnPrint.Click PrintDocument1.Print() End Sub Private Sub PrintDocument1_PrintPage(sender As System.Object, e As System.Drawing.Printing.PrintPageEventArgs) Handles _ PrintDocument1.PrintPage Dim gr As Graphics = e.Graphics Dim x1 As Integer = ONE_INCH 'use one inch beyond left margin Dim x2 As Integer = CInt(1.5 * ONE_INCH) 'offset for second column Dim x3 As Integer = CInt(2.25 * ONE_INCH) 'offset for third column Dim y As Integer = ONE_INCH 'use one inch top margin Dim font1 As New Font("Courier New", 10, FontStyle.Underline) Dim font2 As New Font("Courier New", 10, FontStyle.Regular) gr.DrawString("% That uses", font2, Brushes.Black, x3, y) y += LINE_HEIGHT gr.DrawString("Rank", font1, Brushes.Black, x1, y) gr.DrawString("Country", font1, Brushes.Black, x2, y) gr.DrawString("the Internet", font1, Brushes.Black, x3, y) y += LINE_HEIGHT gr.DrawString("1", font2, Brushes.Black, x1, y) gr.DrawString("Korea", font2, Brushes.Black, x2, y) gr.DrawString((0.828).ToString("P1"), font2, Brushes.Black, x3, y) y += LINE_HEIGHT gr.DrawString("2", font2, Brushes.Black, x1, y) gr.DrawString("Germany", font2, Brushes.Black, x2, y) gr.DrawString((0.827).ToString("P1"), font2, Brushes.Black, x3, y) y += LINE_HEIGHT gr.DrawString("3", font2, Brushes.Black, x1, y) gr.DrawString("Japan", font2, Brushes.Black, x2, y) gr.DrawString((0.8).ToString("P1"), font2, Brushes.Black, x3, y) End Sub Private Sub btnPreview_Click(...) Handles btnPreview.Click PrintPreviewDialog1.Document = PrintDocument1 PrintPreviewDialog1.ShowDialog() End Sub Rank 1 2 3
Country Korea Germany Japan
% That uses the Intenet 82.8 % 82.7 % 80.0 %
22. Private Sub btnPreview_Click(...) Handles btnPreview.Click PrintPreviewDialog1.Document = PrintDocument1 PrintPreviewDialog1.ShowDialog() End Sub Private Sub btnPrint_Click(...) Handles btnPrint.Click PrintDocument1.Print() End Sub
Instructor Solutions Manual (Page 89 of 196) Private Sub PrintDocument1_PrintPage(sender As System.Object, e As System.Drawing.Printing.PrintPageEventArgs ) Handles _ PrintDocument1.PrintPage Dim legend() As String = {"Federal", "State", "Local"} Dim quantity() As Single = {33, 207, 180} Dim percent(quantity.Count - 1) As Single Dim sumOfQuantities As Single = 0 Dim sumOfSweepAngles As Single = 0 Dim br() As Brush = {Brushes.Blue, Brushes.Red, Brushes.Tan, Brushes.Green, Brushes.Orange, Brushes.Gray} Dim gr As Graphics = e.Graphics Dim r As Integer = 100 'Radius of circle Dim cx As Integer = 405 'Center of circle is (cx, cy) Dim cy As Integer = 305 gr.DrawString("Financing for Public Schools (K - 12)", Me.Font, Brushes.Black, 300, 175) For i As Integer = 0 To (quantity.Count – 1) sumOfQuantities += quantity(i) Next 'Convert tbe quantities to percents For i As Integer = 0 To (quantity.Count – 1) percent(i) = quantity(i) / sumOfQuantities Next 'Print the pie chart and the legends For i As Integer = 0 To (quantity.Count – 1) gr.FillPie(br(i), cx - r, cy - r, 2 * r, 2 * r, sumOfSweepAngles, percent(i) * 360) sumOfSweepAngles += percent(i) * 360 gr.FillRectangle(br(i), 520, 220 + 30 * i, 20, 20) gr.DrawString(legend(i), Me.Font, Brushes.Black, 550, 222 + 30 * i) Next End Sub
23. Private Sub btnPrint_Click(...) Handles btnPrint.Click PrintDocument1.Print() End Sub Private Sub PrintDocument1_PrintPage(sender As System.Object, e As System.Drawing.Printing.PrintPageEventArgs) Handles _ PrintDocument1.PrintPage 'Print Italian flag Dim gr As Graphics = e.Graphics Dim br() As Brush = {Brushes.Green, Brushes.White, Brushes.Red} For i As Integer = 0 To 2 gr.FillRectangle(br(i), 300 + i * 50, 200, 50, 99) Next gr.DrawLine(Pens.Black, 300, 200, 448, 200) 'top border gr.DrawLine(Pens.Black, 300, 200, 300, 298) 'left border gr.DrawLine(Pens.Black, 300, 298, 448, 298) 'bottom border gr.DrawLine(Pens.Black, 448, 200, 448, 298) 'right border End Sub Private Sub btnPreview_Click(...) Handles btnPreview.Click PrintPreviewDialog1.Document = PrintDocument1 PrintPreviewDialog1.ShowDialog() End Sub
Instructor Solutions Manual (Page 90 of 196) 24. Private Sub btnPrint_Click(...) Handles btnPrint.Click PrintDocument1.Print() End Sub Private Sub PrintDocument1_PrintPage(sender As System.Object, e As System.Drawing.Printing.PrintPageEventArgs) Handles _ PrintDocument1.PrintPage Dim gr As Graphics = e.Graphics Dim br() As Brush = {Brushes.Orange, Brushes.White, Brushes.Green} Dim r As Integer = 12 'radius of circle 'picFlag.Width = 99, picFlag.Height = 149 For i As Integer = 0 To 2 gr.FillRectangle(br(i), 300, 200 + i * 33, 149, 33) Next gr.FillPie(Brushes.Orange, 375 - r, 249 - r, 2 * r, 2 * r, 0, 360) gr.DrawLine(Pens.Black, 300, 200, 448, 200) 'top border gr.DrawLine(Pens.Black, 300, 200, 300, 298) 'left border gr.DrawLine(Pens.Black, 300, 298, 348, 298) 'bottom border gr.DrawLine(Pens.Black, 448, 200, 448, 298) 'right border End Sub Private Sub btnPreview_Click(...) Handles btnPreview.Click PrintPreviewDialog1.Document = PrintDocument1 PrintPreviewDialog1.ShowDialog() End Sub
CHAPTER 9 PROGRAMMING PROJECTS 1. Const FILE_NAME As String = "MemberPhones.txt" Dim membs() As String = IO.File.ReadAllLines(FILE_NAME) Private Sub frmMembers_Load(...) Handles MyBase.Load DisplayList() End Sub Sub DisplayList() lstMembers.Items.Clear() Dim query = From member In membs Let data = member.Split(","c) Select data(0) For Each person In query lstMembers.Items.Add(person) Next End Sub
Instructor Solutions Manual (Page 91 of 196) Private Sub lstMembers_SelectedIndexChanged(...) Handles _ lstMembers.SelectedIndexChanged 'Display the structure's data corresponding to the selected item. Dim i As Integer = lstMembers.SelectedIndex Dim data() = membs(i).Split(","c) If i >= 0 Then txtName.Text = data(0) mtbPhone.Text = data(1) Else txtName.Clear() mtbPhone.Clear() End If End Sub Private Sub mnuUpdateModify_Click(...) Handles mnuUpdateModify.Click 'Store the modifications. Dim i As Integer = lstMembers.SelectedIndex If i >= 0 Then membs(i) = txtName.Text & "," & mtbPhone.Text End If 'Sort list of names Dim query = From member In membs Let data = member.Split(","c) Let names = data(0).Split(" "c) Order By names(1), names(0) Select member membs = query.ToArray DisplayList() End Sub Private Sub mnuUpdateAdd_Click(...) Handles mnuUpdateAdd.Click 'Add a new member. Dim n = membs.Count ReDim Preserve membs(n) membs(n) = txtName.Text & "," & mtbPhone.Text Dim query = From member In membs Let data = member.Split(","c) Let names = data(0).Split(" "c) Order By names(1), names(0) Select member membs = query.ToArray DisplayList() End Sub Private Sub mnuUpdateDelete_Click(...) Handles mnuUpdateDelete.Click 'Delete a member. Dim i As Integer = lstMembers.SelectedIndex If i >= 0 Then 'Only delete the entry if one is selected. Dim query = From member In membs Where member.Split(","c)(0) <> txtName.Text Select member membs = query.ToArray DisplayList() End If End Sub
Instructor Solutions Manual (Page 92 of 196) Private Sub mnuExit_Click(...) Handles mnuExit.Click 'Store the membership information into the file and end the program. IO.File.WriteAllLines(FILE_NAME, membs) Me.Close() 'Terminate the program End Sub
2. Dim votes(0) As Integer
'Dimension a small array of length 1.
Private Sub btnCandidate_Click(...) Handles btnCandidate.Click 'Nominate a candidate by adding him or her to the list. Dim name As String 'Clear the existing votes and results lstVotes.Visible = False lstVotes.Items.Clear() txtVotes.Clear() 'Get the name of the candidate name = InputBox("Enter the candidate's name:", "Nominate") 'If the name is not already in the list, then add it If lstCandidate.Items.IndexOf(name) = -1 Then lstCandidate.Items.Add(name) End If End Sub Private Sub btnStartVoting_Click(...) Handles btnStartVoting.Click btnCandidate.Enabled = False lblInstructions.Text = "Vote for a candidate by" & " double-clicking on his/her name. " & "End the voting by clicking on 'Tally Votes'." End Sub Private Sub lstCandidate_DoubleClick(...) Handles lstCandidate.DoubleClick 'Vote for a candidate by incrementing the candidate's count If votes.Count <= 1 Then 'Resize the votes array if not done so already ReDim votes(lstCandidate.Items.Count) End If votes(lstCandidate.SelectedIndex) += 1 txtVotes.Clear() 'Clear the results lstVotes.Visible = False MessageBox.Show("You voted for " & lstCandidate.Text & ".", "VOTE RECORDED") End Sub
Instructor Solutions Manual (Page 93 of 196) Private Sub btnTallyVotes_Click(...) Handles btnTallyVotes.Click 'Count the results and display the winner Dim winner As Integer Dim count As String lblInstructions.Text = "" lstVotes.Visible = True lstVotes.Items.Clear() winner = 0 'Index of the candidate with the most votes For i As Integer = 0 To (lstCandidate.Items.Count – 1) Select Case votes(i) Case 0 count = "No votes" Case 1 count = "One vote" Case Else count = CStr(votes(i)) & " votes" End Select lstVotes.Items.Add(count) 'Display the votes for the candidate. If votes(i) > votes(winner) Then winner = i 'Remember who has the most votes. End If Next txtVotes.Clear() 'Display the candidate(s) with the most votes For i As Integer = 0 To (lstCandidate.Items.Count – 1) If votes(i) = votes(winner) Then If txtVotes.Text.Length = 0 Then 'The first winning candidate txtVotes.Text = CStr(lstCandidate.Items(i)) Else 'Multiple candidates with the winning vote count txtVotes.Text = txtVotes.Text & " and " & CStr(lstCandidate.Items(i)) End If End If Next 'Display the winning vote count txtVotes.Text = txtVotes.Text & " wins with " & votes(winner) & " votes." End Sub 3. 'frmBooks' code Structure Book Dim title As String Dim author As String Dim category As String Dim stock As Integer Dim price As Double End Structure
'Title 'Author's name 'True = fiction, False = nonfiction 'Quantity in stock 'Wholesale price
Public books() As Book Public numBooks As Integer 'number of books carried Public flagNewBook As Boolean = False Public n As Integer 'current index
Instructor Solutions Manual (Page 94 of 196) Private Sub frmBooks_Load(...) Handles MyBase.Load 'Load the data file into the array and display all books If IO.File.Exists("Books.txt") Then Dim tomes() As String = IO.File.ReadAllLines("Books.txt") numBooks = tomes.Count ReDim books(numBooks - 1) Dim data(4) As String For i As Integer = 0 To (numBooks – 1) data = tomes(i).Split(","c) books(i).title = data(0) books(i).author = data(1) books(i).category = data(2) books(i).stock = CInt(data(3)) books(i).price = CDbl(data(4)) Next Dim query = From book In tomes Let line = book.Split(","c) Let title = line(0) Select title lstBooks.DataSource = query.ToList lstBooks.SelectedItem = Nothing End If End Sub Private Sub mnuDisplayAll_Click(...) Handles mnuDisplayAll.Click 'Display books mnuDisplayAll.Checked = True mnuDisplayFiction.Checked = False mnuDisplayNonfiction.Checked = False Display() End Sub Private Sub mnuDisplayFiction_Click(...) Handles mnuDisplayFiction.Click 'Display books mnuDisplayAll.Checked = False mnuDisplayFiction.Checked = True mnuDisplayNonfiction.Checked = False Display() End Sub Private Sub mnuDisplayNonfiction_Click(...) Handles mnuDisplayNonfiction.Click 'Display books mnuDisplayAll.Checked = False mnuDisplayFiction.Checked = False mnuDisplayNonfiction.Checked = True Display() End Sub Sub Display() 'Display appropriate subset of books Dim query = From book In books Where (book.category = "F" And (Not mnuDisplayNonfiction.Checked)) Or (book.category = "N" And (Not mnuDisplayFiction.Checked)) Select book.title lstBooks.DataSource = query.ToList lstBooks.SelectedItem = Nothing End Sub
Instructor Solutions Manual (Page 95 of 196)
Private Sub mnuBookAdd_Click(...) Handles mnuBookAdd.Click 'Add a new book to the array flagNewBook = True frmDetails.txtTitle.Clear() frmDetails.txtAuthor.Clear() frmDetails.txtStock.Clear() frmDetails.txtPrice.Clear() frmDetails.radFiction.Checked = True frmDetails.ShowDialog() End Sub Private Sub mnuBookDelete_Click(...) Handles mnuBookDelete.Click 'Delete the selected book from the array n = lstBooks.SelectedIndex If n >= 0 Then 'Only delete if book is selected numBooks = numBooks - 1 For j As Integer = n To (numBooks – 1) 'Shift the items above down by one books(j) = books(j + 1) Next ReDim Preserve books(numBooks - 1) Display() 'Redisplay the output End If End Sub Private Sub mnuBookUpdate_Click(...) Handles mnuBookUpdate.Click 'Update the stock or price of the selected book n = lstBooks.SelectedIndex If n >= 0 Then 'Only update if book is selected flagNewBook = False frmDetails.txtTitle.Text = books(n).title frmDetails.txtTitle.SelectionStart = 0 frmDetails.txtAuthor.Text = books(n).author frmDetails.txtStock.Text = CStr(books(n).stock) frmDetails.txtPrice.Text = (books(n).price).ToString("C") If books(n).category = "F" Then frmDetails.radFiction.Checked = True Else frmDetails.radNonFiction.Checked = True End If frmDetails.ShowDialog() End If End Sub Private Sub mnuFileSave_Click(...) Handles mnuFileSave.Click 'Save the array into the text file Dim query = From book In books Let line = book.title & "," & book.author & "," & book.category & "," & book.stock & "," & book.price Select line IO.File.WriteAllLines("Books.txt", query) MessageBox.Show("File saved.") End Sub
Instructor Solutions Manual (Page 96 of 196) Private Sub mnuFileExit_Click(...) Handles mnuFileExit.Click 'End the program End End Sub Private Sub mnuValuesAll_Click(...) Handles mnuValuesAll.Click Dim query = From book In books Select book.price * book.stock MessageBox.Show("Value: " & (query.Sum).ToString("C"), "All") End Sub Private Sub mnuValuesFiction_Click(...) Handles mnuValuesFiction.Click Dim query = From book In books Where book.category = "F" Select book.price * book.stock MessageBox.Show("Value: " & (query.Sum).ToString("C"), "Fiction") End Sub Private Sub mnuValuesNonfiction_Click(...) Handles mnuValuesNonfiction.Click Dim query = From book In books Where book.category = "N" Select book.price * book.stock MessageBox.Show("Value: " & (query.Sum).ToString("C"), "Nonfiction") End Sub 'frmDetails' code Private Sub btnRecord_Click(...) Handles btnRecord.Click If (txtTitle.Text = "") Or (txtAuthor.Text = "") Or _ (txtStock.Text = "") Or (txtPrice.Text = "") Then MessageBox.Show("You must enter the title, author, stock and price.") Else If frmBooks.flagNewBook Then ReDim Preserve frmBooks.books(frmBooks.numBooks) frmBooks.books(frmBooks.numBooks).title = txtTitle.Text frmBooks.books(frmBooks.numBooks).author = txtAuthor.Text frmBooks.books(frmBooks.numBooks).stock = CInt(txtStock.Text) frmBooks.books(frmBooks.numBooks).price = CDbl(txtPrice.Text) If radFiction.Checked Then frmBooks.books(frmBooks.numBooks).category = "F" Else frmBooks.books(frmBooks.numBooks).category = "N" End If frmBooks.numBooks += 1 Else frmBooks.books(frmBooks.n).title = txtTitle.Text frmBooks.books(frmBooks.n).author = txtAuthor.Text frmBooks.books(frmBooks.n).stock = CInt(txtStock.Text) frmBooks.books(frmBooks.n).price = CDbl(txtPrice.Text) If radFiction.Checked Then frmBooks.books(frmBooks.n).category = "F" Else frmBooks.books(frmBooks.n).category = "N" End If End If End If Me.Close() End Sub
Instructor Solutions Manual (Page 97 of 196)
4. 'frmChart's code Dim seats(15, 6) As String '15 rows of six seats per row ' Each may have value R, L, V or . (period) Dim frmAssign As New frmMeal() 'Form to use to assign a seat Private Sub frmChart_Load(...) Handles MyBase.Load 'Initialize the display and data array. 'Add heading to list box lstRows.Items.Add(" ABC DEF ") For i As Integer = 1 To 15 'Loop over each row. For j As Integer = 1 To 6 'Initialize each seat to empty. seats(i, j) = "." Next 'Initialize the display row. lstRows.Items.Add(" ... ... ") Next End Sub Private Sub lstRows_SelectedIndexChanged(...) Handles _ lstRows.SelectedIndexChanged 'Display the details of the selected row in the text boxes. Dim row As Integer = lstRows.SelectedIndex If row > 0 Then ShowRow(row) End If End Sub Private Sub ShowRow(row As Integer) 'Update the row's information in the text boxes. txtRow.Text = CStr(row) txtA.Text = seats(row, 1) txtB.Text = seats(row, 2) txtC.Text = seats(row, 3) txtD.Text = seats(row, 4) txtE.Text = seats(row, 5) txtF.Text = seats(row, 6) End Sub
Instructor Solutions Manual (Page 98 of 196) Private Sub txtA_Click(...) Handles txtA.Click Assign(1) End Sub Private Sub txtB_Click(...) Handles txtB.Click Assign(2) End Sub Private Sub txtC_Click(...) Handles txtC.Click Assign(3) End Sub Private Sub txtD_Click(...) Handles txtD.Click Assign(4) End Sub Private Sub txtE_Click(...) Handles txtE.Click Assign(5) End Sub Private Sub txtF_Click(...) Handles txtF.Click Assign(6) End Sub Sub Assign(seat As Integer) 'Assign the seat in the current row Dim row As Integer = lstRows.SelectedIndex 'Only assign the seat if the row selected is valid If row > 0 Then 'Display a secondary form to get value for a seat in a row. frmAssign.seat = seats(row, seat) 'Assign seat's data to the second form. frmAssign.Text = "Assign seat " & row & Chr(64 + seat) frmAssign.ShowDialog() 'Display form, and wait until it is closed. seats(row, seat) = frmAssign.seat 'Retrieve the new data from the form. ShowRow(row) 'Update the row's data in the text boxes and list box. lstRows.Items(row) = " " & seats(row, 1) & seats(row, 2) & seats(row, 3) & " " & seats(row, 4) & seats(row, 5) & seats(row, 6) & " " 'Clear the statistics window lstDisplay.Items.Clear() End If End Sub
Instructor Solutions Manual (Page 99 of 196) Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display statistics on meal totals, filled and vacant window seats Dim meals(3) As Integer Dim vacant As Integer = 0 Dim window As Integer = 0 For row As Integer = 1 To 15 'Compile the statistics. For seat As Integer = 1 To 6 Select Case seats(row, seat) Case "R" meals(1) += 1 Case "L" meals(2) += 1 Case "V" meals(3) += 1 Case Else 'If none of the above, then seat is unoccupied. vacant += 1 If (seat = 1) Or (seat = 6) Then window += 1 'If it is a window, count it. End If End Select Next Next lstDisplay.Items.Clear() 'Display the results lstDisplay.Items.Add("Seats filled: " & (15 * 6 - vacant)) lstDisplay.Items.Add("Windows avail: " & window) lstDisplay.Items.Add("Regular meals: " & meals(1)) lstDisplay.Items.Add("LowCal meals: " & meals(2)) lstDisplay.Items.Add("Vegie meals: " & meals(3)) End Sub 'frmMeal's code Public seat As String '
'seat has values R, L, V or . (period) In frmChart it is referred to as frmAssign.seat.
Private Sub frmMeal_Load(...) Handles MyBase.Load 'Update the checked status per the seat Select Case seat Case "R" radRegular.Checked = True Case "L" radLowCal.Checked = True Case "V" radVeg.Checked = True Case Else 'If none of the above, then seat is unoccupied radUnoccupied.Checked = True End Select End Sub Private Sub radUnoccupied_CheckedChanged(...) Handles _ radUnoccupied.CheckedChanged 'Set value to seat and close the form seat = "." Me.Close() End Sub
Instructor Solutions Manual (Page 100 of 196) Private Sub radRegular_CheckedChanged(...) Handles radRegular.CheckedChanged 'Set value to seat and close the form seat = "R" Me.Close() End Sub Private Sub radLowCal_CheckedChanged(...) Handles radLowCal.CheckedChanged 'Set value to seat and close the form seat = "L" Me.Close() End Sub Private Sub radVeg_CheckedChanged(...) Handles radVeg.CheckedChanged 'Set value to seat and close the form seat = "V" Me.Close() End Sub
Instructor Solutions Manual (Page 101 of 196) 5. Dim randomNum As New Random Private Sub frmWorldSeries_Load(...) Handles MyBase.Load ResetControls() End Sub Private Sub btnSimulate_Click(...) Handles btnSimulate.Click Dim games As Integer Dim winner As String = "" 'Simulate the playing of 10,000 world series. Update the values of the scroll 'bars and text boxes to reflect the current statistics ResetControls() For i As Integer = 1 To 10000 PlaySeries(winner, games) If winner = "Weaker team won" Then hsbUnderdog.Value = hsbUnderdog.Value + 1 Else hsbFavorite.Value = hsbFavorite.Value + 1 End If Select Case games Case 4 hsbFour.Value += 1 Case 5 hsbFive.Value += 1 Case 6 hsbSix.Value += 1 Case 7 hsbSeven.Value += 1 End Select 'Force a refresh every 10th time, so that the computer is not too 'overwhelmed with refreshes If i Mod 10 = 0 Then UpdateLabels(i) txtUnderdog.Refresh() txtFavorite.Refresh() txtFour.Refresh() txtFive.Refresh() txtSix.Refresh() txtSeven.Refresh() End If Next txtAverageDuration.Text = ((4 * CDbl(hsbFour.Value) + 5 * CSng(hsbFive.Value) + 6 * CSng(hsbSix.Value) + 7 * CSng(hsbSeven.Value)) / 10000).ToString("N") & " games" End Sub Private Sub PlaySeries(ByRef winner As String, ByRef games As Integer) Dim weakerTeamWins As Integer = 0 Dim strongerTeamWins As Integer = 0 Dim numGames As Integer = 0 Dim prob As Integer = CInt(txtProb.Text) Dim seriesOver As Boolean = False Do While seriesOver = False If randomNum.Next(0, 100) < prob Then weakerTeamWins += 1 Else strongerTeamWins += 1 End If If weakerTeamWins = 4 Then winner = "Weaker team won"
Instructor Solutions Manual (Page 102 of 196) seriesOver = True ElseIf strongerTeamWins = 4 Then winner = "Stronger team won" seriesOver = True End If numGames += 1 Loop games = numGames End Sub Private Sub ResetControls() 'Resets the initial value of all scroll bars and statistic labels hsbFavorite.Value = 0 hsbUnderdog.Value = 0 hsbFour.Value = 0 hsbFive.Value = 0 hsbSix.Value = 0 hsbSeven.Value = 0 UpdateLabels(1) 'reuse procedure to set all percentages to zero txtAverageDuration.Clear() End Sub Private Sub UpdateLabels(ByRef numGames As Integer) txtUnderdog.Text = CStr(hsbUnderdog.Value) txtFavorite.Text = CStr(hsbFavorite.Value) txtFour.Text = CStr(hsbFour.Value) txtFive.Text = CStr(hsbFive.Value) txtSix.Text = CStr(hsbSix.Value) txtSeven.Text = CStr(hsbSeven.Value) txtUnderdogPercent.Text = (CInt(txtUnderdog.Text) / numGames).ToString("P") txtFavoritePercent.Text = (CInt(txtFavorite.Text) / numGames).ToString("P") txtFourPercent.Text = (hsbFour.Value / numGames).ToString("P") txtFivePercent.Text = (hsbFive.Value / numGames).ToString("P") txtSixPercent.Text = (hsbSix.Value / numGames).ToString("P") txtSevenPercent.Text = (hsbSeven.Value / numGames).ToString("P") End Sub
Instructor Solutions Manual (Page 103 of 196) 6. Dim dayNumber As Integer Dim people() As Integer = {9700, 200, 100, 0} 'people(0) = number susceptible, people(1) = number sick one day 'people(2) = number sick two days, people(3) = number immune Private Sub btnShow_Click(...) Handles btnShow.Click DrawBarGraph() End Sub Private Sub btnAdvance_Click(...) Handles btnAdvance.Click Dim totalSick As Integer dayNumber = dayNumber + 1 totalSick = people(1) + people(2) people(3) = people(3) + people(2) people(2) = people(1) people(1) = CInt(0.0001735 * totalSick * people(0)) people(0) = 10000 - people(1) - people(2) - people(3) DrawBarGraph() End Sub Private Sub DrawBarGraph() Dim gr As Graphics = picOutput.CreateGraphics picOutput.Refresh() gr.DrawLine(Pens.Black, 40, 100, picOutput.Width, 100) 'Draw x-axis. gr.DrawLine(Pens.Black, 40, 100, 40, 0) 'Draw y-axis. gr.DrawLine(Pens.Black, 35, 0, 45, 0) 'Draw tick mark gr.DrawString("10,000", Me.Font, Brushes.Blue, 0, 0) 'Label tick mark. gr.DrawString("Susceptible Sick 1 Day Sick 2 Days Immune", Me.Font, Brushes.Blue, 42, 102) For i As Integer = 0 To (people.Count – 1) gr.FillRectangle(Brushes.Blue, 60 + i * 63, CInt(100 - people(i) / 100), 25, CInt(people(i) / 100)) Next gr.DrawString("Day " & dayNumber, Me.Font, Brushes.Blue, 125, 0) End Sub
Instructor Solutions Manual (Page 104 of 196) 7. Const ONE_INCH As Integer = 75 'number of pixels in an inch Const LINE_HEIGHT As Integer = 15 'one-quarter of an inch Private Sub btnPrint_Click(sender As System.Object, e As System.EventArgs) Handles btnPrint.Click 'Print a Business Travel Expense attachment PrintDocument1.Print() End Sub Private Sub btnPreview_Click(sender As System.Object, e As System.EventArgs) Handles btnPreview.Click PrintPreviewDialog1.Document = PrintDocument1 PrintPreviewDialog1.ShowDialog() End Sub Private Sub PrintDocument1_PrintPage(sender As System.Object, e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage Dim gr As Graphics = e.Graphics Dim str As String Dim x1 As Integer = ONE_INCH 'use one inch left margin Dim x2 As Integer = 5 * ONE_INCH Dim y As Integer = 2 * ONE_INCH 'use two inch top margin Dim font As New Font("Courier New", 10, FontStyle.Bold) str = "Business Travel Expenses" gr.DrawString(str, font, Brushes.Black, x1, y) font = New Font("Courier New", 10, FontStyle.Regular) y += 2 * LINE_HEIGHT 'double space str = "Trip to attend meeting of" gr.DrawString(str, font, Brushes.Black, x1, y) y += LINE_HEIGHT gr.DrawString(txtOrg.Text, font, Brushes.Black, x1, y) y += LINE_HEIGHT str = txtDates.Text & " in " & txtPlace.Text gr.DrawString(str, font, Brushes.Black, x1, y) y += 2 * LINE_HEIGHT str = "Meals and entertainment:" & " " & (CDbl(txtMealsEnt.Text)).ToString("C") gr.DrawString(lblMealsEnt.Text, font, Brushes.Black, x1, y) gr.DrawString((CDbl(txtMealsEnt.Text)).ToString("C"), font, Brushes.Black, x2, y) y += LINE_HEIGHT str = "Airplane fare:" & " " & (CDbl(txtAirFare.Text)).ToString("C") gr.DrawString(lblAirfare.Text, font, Brushes.Black, x1, y) gr.DrawString((CDbl(txtAirFare.Text)).ToString("C"), font, Brushes.Black, x2, y) y += LINE_HEIGHT str = "Lodging:" & " " & (CDbl(txtLodging.Text)).ToString("C") gr.DrawString(lblLodging.Text, font, Brushes.Black, x1, y) gr.DrawString((CDbl(txtLodging.Text)).ToString("C"), font, Brushes.Black, x2, y) y += LINE_HEIGHT str = "Taxi fares:" & " " & (CDbl(txtTaxi.Text)).ToString("C") gr.DrawString(lblTaxi.Text, font, Brushes.Black, x1, y) gr.DrawString((CDbl(txtTaxi.Text)).ToString("C"), font, Brushes.Black, x2, y) y += 2 * LINE_HEIGHT Dim other As Double = CDbl(txtAirFare.Text) + CDbl(txtLodging.Text) + CDbl(txtTaxi.Text) str = "Total other than meals and entertainment: " & other.ToString("C") gr.DrawString(str, font, Brushes.Black, x1, y)
Instructor Solutions Manual (Page 105 of 196) y += LINE_HEIGHT Dim mealEntDeduction As Double = 0.5 * CDbl(txtMealsEnt.Text) str = "50% of meals and entertainment: " & (CDbl(mealEntDeduction)).ToString("C") gr.DrawString(str, font, Brushes.Black, x1, y) y += 2 * LINE_HEIGHT str = "TOTAL DEDUCTIBLE EXPENSES: " & (CDbl(other + mealEntDeduction)).ToString("C") gr.DrawString(str, font, Brushes.Black, x1, y) End Sub
Instructor Solutions Manual (Page 106 of 196) CHAPTER 10 EXERCISES 10.1 1. (e)
2. (c)
3. (d)
4. (f)
5. (b)
6. (a)
7. Private Sub frmCities_Load(...) Handles MyBase.Load Me.CitiesTableAdapter.Fill(Me.MegacitiesDataSet.Cities) End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From city In MegacitiesDataSet.Cities Let popGrowth = (city.pop2015 - city.pop2010) / city.pop2010 Let formattedPopGrowth = popGrowth.ToString("P") Order By popGrowth Descending Select city.name, city.country, formattedPopGrowth dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "City" dgvOutput.Columns("country").HeaderText = "Country" dgvOutput.Columns("formattedPopGrowth").HeaderText = "Projected Population Growth" End Sub
Instructor Solutions Manual (Page 107 of 196) 8. Private Sub frmCities_Load(...) Handles MyBase.Load Me.CountriesTableAdapter.Fill(Me.MegacitiesDataSet.Countries) Me.CitiesTableAdapter.Fill(Me.MegacitiesDataSet.Cities) End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From city In MegacitiesDataSet.Cities Join country In MegacitiesDataSet.Countries On city.country Equals country.name Let cityPer = city.pop2010 / country.pop2010 Order By cityPer Descending Let formattedCityPer = cityPer.ToString("P") Select city.name, city.country, formattedCityPer dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "City" dgvOutput.Columns("country").HeaderText = "Country" dgvOutput.Columns("formattedCityPer").HeaderText = "Percentage of Country's Population" End Sub
Instructor Solutions Manual (Page 108 of 196) 9. Private Sub frmCities_Load(...) Handles MyBase.Load Me.CitiesTableAdapter.Fill(Me.MegacitiesDataSet.Cities) End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From city In MegacitiesDataSet.Cities Where city.pop2015 > 20 Order By city.pop2015 Descending Select city.name lstOutput.DataSource = query.ToList lstOutput.SelectedItem = Nothing End Sub
10. Private Sub frmCities_Load(...) Handles MyBase.Load Me.CitiesTableAdapter.Fill(Me.MegacitiesDataSet.Cities) Dim query = From city In MegacitiesDataSet.Cities Order By city.country Select city.country Distinct lstCountries.DataSource = query.ToList End Sub Private Sub lstCountries_SelectedIndexChanged(...) Handles lstCountries.SelectedIndexChanged Dim query = From city In MegacitiesDataSet.Cities Where city.country = lstCountries.Text Order By city.pop2010 Descending Select city.name txtMostPopulousCity.Text = query.First End Sub
Instructor Solutions Manual (Page 109 of 196) 11. Private Sub frmCities_Load(...) Handles MyBase.Load Me.CitiesTableAdapter.Fill(Me.MegacitiesDataSet.Cities) End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query1 = From city In MegacitiesDataSet.Cities Let perIncr = (city.pop2015 - city.pop2010) / city.pop2010 Order By perIncr Descending Select city.name Dim geatestCity As String = query1.First Dim query2 = From city In MegacitiesDataSet.Cities Where city.name = geatestCity Select city.name, city.country, city.pop2010, city.pop2015 dgvOutput.DataSource = query2.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "City" dgvOutput.Columns("country").HeaderText = "Country" dgvOutput.Columns("pop2010").HeaderText = "Population in 2010" dgvOutput.Columns("pop2015").HeaderText = "Population in 2015" End Sub
Instructor Solutions Manual (Page 110 of 196) 12. Private Sub frmCities_Load(...) Handles MyBase.Load Me.CitiesTableAdapter.Fill(Me.MegacitiesDataSet.Cities) End Sub Private Sub Button1_Click(...) Handles btnDisplay.Click Dim query = From city In MegacitiesDataSet.Cities Where (city.pop2010 >= 13) And (city.pop2010 <= 19) Order By city.country Select city.name, city.country, city.pop2010 dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "City" dgvOutput.Columns("country").HeaderText = "Country" dgvOutput.Columns("pop2010").HeaderText = "Population in 2010" End Sub
Instructor Solutions Manual (Page 111 of 196) 13. Private Sub frmCities_Load(...) Handles MyBase.Load Me.CountriesTableAdapter.Fill(Me.MegacitiesDataSet.Countries) Me.CitiesTableAdapter.Fill(Me.MegacitiesDataSet.Cities) Dim query = From city In MegacitiesDataSet.Cities Select city.name lstCities.DataSource = query.ToList End Sub Private Sub lstCities_SelectedIndexChanged(...) Handles _ lstCities.SelectedIndexChanged Dim query = From city In MegacitiesDataSet.Cities Join country In MegacitiesDataSet.Countries On city.country Equals country.name Let cityPer = city.pop2010 / country.pop2010 Where city.name = lstCities.Text Select cityPer txtOutput.Text = (query.First).ToString("P") End Sub
14. Private Sub frmCities_Load(...) Handles MyBase.Load Me.CountriesTableAdapter.Fill(Me.MegacitiesDataSet.Countries) Me.CitiesTableAdapter.Fill(Me.MegacitiesDataSet.Cities) Dim query = From city In MegacitiesDataSet.Cities Select city.name lstCities.DataSource = query.ToList End Sub Private Sub lstCities_SelectedIndexChanged(...) Handles lstCities.SelectedIndexChanged Dim query = From city In MegacitiesDataSet.Cities Join country In MegacitiesDataSet.Countries On city.country Equals country.name Where city.name = lstCities.Text Select country.monetaryUnit txtOutput.Text = query.First End Sub
Instructor Solutions Manual (Page 112 of 196) 15. Private Sub frmCities_Load(...) Handles MyBase.Load Me.CitiesTableAdapter.Fill(Me.MegacitiesDataSet.Cities) End Sub Private Sub btnCreate_Click(...) Handles btnCreate.Click Dim query = From city In MegacitiesDataSet.Cities Select city.name & "," & city.country & "," & city.pop2010 & "," & city.pop2015 IO.File.WriteAllLines("Megacities.txt", query.ToArray) MessageBox.Show("File Created") End Sub
16. Private Sub frmCities_Load(...) Handles MyBase.Load Me.CitiesTableAdapter.Fill(Me.MegacitiesDataSet.Cities) End Sub Private Sub btnCreate_Click(...) Handles btnCreate.Click Dim sw As IO.StreamWriter = IO.File.CreateText("Megacities.xml") sw.WriteLine("<?xml version='1.0'?>") sw.WriteLine("<!-- This file contains data on large cities -->") sw.WriteLine("<Megacities>") Dim query = From city In MegacitiesDataSet.Cities Select city.name, city.country, city.pop2010, city.pop2015 For Each city In query sw.WriteLine(" <city>") sw.WriteLine(" <name>" & city.name & "</name>") sw.WriteLine(" <country>" & city.country & "</country>") sw.WriteLine(" <pop2010>" & city.pop2010 & "</pop2010>") sw.WriteLine(" <pop2015>" & city.pop2015 & "</pop2015>") sw.WriteLine(" </city>") Next sw.WriteLine("</Megacities>") sw.Close() MessageBox.Show("File Created") End Sub
Instructor Solutions Manual (Page 113 of 196) 17. Private Sub frmNations_Load(...) Handles MyBase.Load Me.NationsTableAdapter.Fill(Me.UNDataSet.Nations) Dim query = From nation In UNDataSet.Nations Order By nation.continent Ascending Select nation.continent Distinct lstContinents.DataSource = query.ToList End Sub Private Sub lstContinents_SelectedIndexChanged(...) Handles _ lstContinents.SelectedIndexChanged Dim queryPop = From nation In UNDataSet.Nations Where nation.continent = lstContinents.Text Order By nation.population Descending Select nation.name lstCountriesPop.DataSource = queryPop.ToList lstCountriesPop.SelectedItem = Nothing Dim queryArea = From nation In UNDataSet.Nations Where nation.continent = lstContinents.Text Order By nation.area Descending Select nation.name lstCountriesArea.DataSource = queryArea.ToList lstCountriesArea.SelectedItem = Nothing End Sub
Instructor Solutions Manual (Page 114 of 196) 18. Private Sub frmNations_Load(...) Handles MyBase.Load Me.NationsTableAdapter.Fill(Me.UNDataSet.Nations) Dim query = From nation In UNDataSet.Nations Order By nation.continent Ascending Select nation.continent Distinct lstContinents.DataSource = query.ToList End Sub Private Sub lstContinents_SelectedIndexChanged(...) Handles lstContinents.SelectedIndexChanged Dim query = From nation In UNDataSet.Nations Where nation.continent = lstContinents.Text Let popDensity = 100000 * nation.population / nation.area Order By popDensity Ascending Let formattedDen = popDensity.ToString("N") Select nation.name, formattedDen dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "Country" dgvOutput.Columns("formattedDen").HeaderText = "Population Density" End Sub
Instructor Solutions Manual (Page 115 of 196) 19. Private Sub Form1_Load(...) Handles MyBase.Load Me.NationsTableAdapter.Fill(Me.UNDataSet.Nations) End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From country In UNDataSet.Nations Select country.area Dim max As Double = query.Max Dim min As Double = query.Min Dim queryOutput = From country In UNDataSet.Nations Where country.area = max Or country.area = min Order By country.area Descending Select country.name, country.continent, country.population, country.area dgvOutput.DataSource = queryOutput.ToList dgvOutput.CurrentCell = Nothing End Sub
20. Private Sub frmCurrency_Load(...) Handles MyBase.Load Me.RatesTableAdapter.Fill(Me.ExchrateDataSet.Rates) Dim query = From money In ExchrateDataSet.Rates Select money.country lstCountries.DataSource = query.ToList End Sub Private Sub lstCountries_SelectedIndexChanged(...) Handles lstCountries.SelectedIndexChanged Dim query = From money In ExchrateDataSet.Rates Where money.country = lstCountries.Text Select money.monetaryUnit, money.dollarRate txtCurrency.Text = query.First.monetaryUnit txtRate.Text = CStr(query.First.dollarRate) End Sub
Instructor Solutions Manual (Page 116 of 196) 21. Private Sub frmCurrencies_Load(...) Handles MyBase.Load Me.RatesTableAdapter.Fill(Me.ExchrateDataSet.Rates) Dim query = From money In ExchrateDataSet.Rates Order By money.dollarRate Ascending Select money.country lstCountries.DataSource = query.ToList End Sub Private Sub lstCountries_SelectedIndexChanged(...) Handles _ lstCountries.SelectedIndexChanged Dim query = From money In ExchrateDataSet.Rates Where money.country = lstCountries.Text Select money.monetaryUnit, money.dollarRate txtCurrency.Text = query.First.monetaryUnit txtRate.Text = CStr(query.First.dollarRate) End Sub
Instructor Solutions Manual (Page 117 of 196) 22. Private Sub frmCurrencies_Load(...) Handles MyBase.Load Me.RatesTableAdapter.Fill(Me.ExchrateDataSet.Rates) Dim query = From money In ExchrateDataSet.Rates Select money.country lstFrom.DataSource = query.ToList lstTo.DataSource = query.ToList End Sub Private Sub btnConvert_Click(...) Handles btnConvert.Click Dim amount As Double = CDbl(txtAmount.Text) Dim fromCountry As String = lstFrom.Text Dim toCountry As String = lstTo.Text Dim queryFrom = From money In ExchrateDataSet.Rates Where money.country = fromCountry Select money.monetaryUnit, money.dollarRate Dim fromRate As Double = queryFrom.First.dollarRate Dim queryTo = From money In ExchrateDataSet.Rates Where money.country = toCountry Select money.monetaryUnit, money.dollarRate Dim toRate As Double = queryTo.First.dollarRate Dim convertedAmount = amount * toRate / fromRate txtOutput.Text = amount.ToString("N") & " " & queryFrom.First.monetaryUnit & "s from " & lstFrom.Text & " equals " & convertedAmount.ToString("N") & " " & queryTo.First.monetaryUnit & "s from " & lstTo.Text & "." End Sub
Instructor Solutions Manual (Page 118 of 196) 23. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams) Dim query = From team In BaseballDataSet.Teams Order By team.name Select team.name lstTeams.DataSource = query.ToList End Sub Private Sub lstTeams_SelectedIndexChanged(...) Handles _ lstTeams.SelectedIndexChanged Dim query = From team In BaseballDataSet.Teams Where team.name = lstTeams.Text Select team.stadium txtStadium.Text = query.First End Sub
24. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams) End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From team In BaseballDataSet.Teams Let battingAve = team.hits / team.atBats Let formattedBattingAve = battingAve.ToString("N3") Order By battingAve Ascending Select team.name, team.stadium, formattedBattingAve dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "Team" dgvOutput.Columns("stadium").HeaderText = "Stadium" dgvOutput.Columns("formattedBattingAve").HeaderText = "Batting Average" End Sub
Instructor Solutions Manual (Page 119 of 196) 25. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.PlayersTableAdapter.Fill(Me.BaseballDataSet.Players) End Sub Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim query1 = From player In BaseballDataSet.Players Order By player.hits Descending Select player.hits Dim mostHits As Double = query1.Max Dim query2 = From player In BaseballDataSet.Players Where player.hits = mostHits Select player.name lstOutput.DataSource = query2.ToList lstOutput.SelectedItem = Nothing End Sub
26. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.PlayersTableAdapter.Fill(Me.BaseballDataSet.Players) End Sub Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim query1 = From player In BaseballDataSet.Players Let battingAve = player.hits / player.atBats Order By battingAve Descending Select battingAve Dim highestBattingAve As Double = query1.Max Dim query2 = From player In BaseballDataSet.Players Let battingAve = player.hits / player.atBats Where battingAve = highestBattingAve Select player.name lstOutput.DataSource = query2.ToList lstOutput.SelectedItem = Nothing End Sub
Instructor Solutions Manual (Page 120 of 196) 27. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams) Me.PlayersTableAdapter.Fill(Me.BaseballDataSet.Players) Dim query = From team In BaseballDataSet.Teams Order By team.name Select team.name lstTeams.DataSource = query.ToList End Sub Private Sub lstTeams_SelectedIndexChanged(...) Handles _ lstTeams.SelectedIndexChanged Dim query = From player In BaseballDataSet.Players Where player.team = lstTeams.Text Let battingAve = player.hits / player.atBats Let formattedBattingAve = battingAve.ToString("N3") Order By battingAve Descending Select player.name, formattedBattingAve dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "Name" dgvOutput.Columns("formattedBattingAve").HeaderText = "Batting Average" End Sub
Instructor Solutions Manual (Page 121 of 196) 28. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.PlayersTableAdapter.Fill(Me.BaseballDataSet.Players) Dim query = From player In BaseballDataSet.Players Let battingAve = player.hits / player.atBats Where battingAve > 0.3 Order By battingAve Ascending Let formattedBattingAve = battingAve.ToString("N3") Select formattedBattingAve Distinct lstPlayers.DataSource = query.ToList End Sub Private Sub lstPlayers_SelectedIndexChanged(...) Handles lstPlayers.SelectedIndexChanged Dim query = From player In BaseballDataSet.Players Let battingAve = player.hits / player.atBats Where battingAve.ToString("N3")= lstPlayers.Text Let lastName = player.name.Split(" "c)(1) Order By lastName Ascending Select player.name, player.team dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "Player" dgvOutput.Columns("team").HeaderText = "Team" End Sub
Instructor Solutions Manual (Page 122 of 196) 29. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams) End Sub Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim query1 = From team In BaseballDataSet.Teams Where team.league = "American" Select team.hits Dim query2 = From team In BaseballDataSet.Teams Where team.league = "American" Select team.atBats txtBattingAve.Text = (query1.Sum / query2.Sum).ToString("N3") End Sub
30. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams) End Sub Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim query = From team In BaseballDataSet.Teams Where team.league = "National" Select team.hits txtHits.Text = (query.Sum).ToString("N0") End Sub
Instructor Solutions Manual (Page 123 of 196)
31. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams) Me.PlayersTableAdapter.Fill(Me.BaseballDataSet.Players) End Sub Private Sub btnCount_Click(...) Handles btnCount.Click Dim query = From player In BaseballDataSet.Players Join team In BaseballDataSet.Teams On player.team Equals team.name Where team.league = "National" Select player.name txtNational.Text = (query.Count).ToString("N0") End Sub
32. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams) Me.PlayersTableAdapter.Fill(Me.BaseballDataSet.Players) End Sub Private Sub btnCount_Click(...) Handles btnCount.Click Dim query = From player In BaseballDataSet.Players Join team In BaseballDataSet.Teams On player.team Equals team.name Where team.location = "New York" Select player.name txtNY.Text = (query.Count).ToString("N0") End Sub
Instructor Solutions Manual (Page 124 of 196) 33. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams) End Sub Private Sub radAmerican_CheckedChanged(...) Handles _ radAmerican.CheckedChanged DisplayPlayers("American") End Sub Private Sub radNational_CheckedChanged(...) Handles _ radNational.CheckedChanged DisplayPlayers("National") End Sub Sub DisplayPlayers(group As String) Dim query = From team In BaseballDataSet.Teams Let battingAve = team.hits / team.atBats Let formattedBattingAve = battingAve.ToString("N3") Where team.league = group Order By battingAve Descending Select team.name, formattedBattingAve dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "Team" dgvOutput.Columns("formattedBattingAve").HeaderText = "Batting Average" End Sub
Instructor Solutions Manual (Page 125 of 196) 34. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams) Me.PlayersTableAdapter.Fill(Me.BaseballDataSet.Players) End Sub Private Sub radAmerican_CheckedChanged(...) Handles radAmerican.CheckedChanged DisplayPlayers("American") End Sub Private Sub radNational_CheckedChanged(...) Handles radNational.CheckedChanged DisplayPlayers("National") End Sub Sub DisplayPlayers(group As String) Dim query = From player In BaseballDataSet.Players Join team In BaseballDataSet.Teams On player.team Equals team.name Where team.league = group And player.hits > 150 Let battingAve = player.hits / player.atBats Let formattedBattingAve = battingAve.ToString("N3") Order By battingAve Descending Select player.name, formattedBattingAve, team.stadium dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "Player" dgvOutput.Columns("formattedBattingAve").HeaderText = "Batting Average" dgvOutput.Columns("stadium").HeaderText = "Stadium" End Sub
Instructor Solutions Manual (Page 126 of 196) 35. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams) Me.PlayersTableAdapter.Fill(Me.BaseballDataSet.Players) Dim query = From team In BaseballDataSet.Teams Order By team.name Select team.name lstTeams.DataSource = query.ToList End Sub Private Sub lstTeams_SelectedIndexChanged(...) Handles _ lstTeams.SelectedIndexChanged Dim query = From player In BaseballDataSet.Players Join team In BaseballDataSet.Teams On player.team Equals team.name Let playerBattingAve = player.hits / player.atBats Let teamBattingAve = team.hits / team.atBats Where team.name = lstTeams.Text And playerBattingAve > teamBattingAve Order By playerBattingAve Descending Select player.name lstPlayers.DataSource = query.ToList lstPlayers.SelectedItem = Nothing End Sub
Instructor Solutions Manual (Page 127 of 196) 36. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams) Me.PlayersTableAdapter.Fill(Me.BaseballDataSet.Players) End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim ave = CDbl(txtAve.Text) Dim group As String If ave >= 0 And ave <= 1 Then If radAmerican.Checked Then group = "American" Else group = "National" End If Dim query = From player In BaseballDataSet.Players Join team In BaseballDataSet.Teams On player.team Equals team.name Let playerBattingAve = player.hits / player.atBats Where team.league = group And playerBattingAve > ave Order By player.hits Descending Select player.name lstPlayers.DataSource = query.ToList lstPlayers.SelectedItem = Nothing Else MessageBox.Show("The batting average must be between 0 and 1.") txtAve.Clear() txtAve.Focus() End If End Sub
Instructor Solutions Manual (Page 128 of 196) 37. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams) Me.PlayersTableAdapter.Fill(Me.BaseballDataSet.Players) End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query1 = From player In BaseballDataSet.Players Join team In BaseballDataSet.Teams On player.team Equals team.name Where team.league = "National" And player.atBats > 100 Let playerBattingAve = player.hits / player.atBats Select playerBattingAve Dim highestAve As Double = query1.Max Dim query2 = From player In BaseballDataSet.Players Join team In BaseballDataSet.Teams On player.team Equals team.name Let playerBattingAve = player.hits / player.atBats Where team.league = "National" And playerBattingAve = highestAve Select player.name lstPlayers.DataSource = query2.ToList lstPlayers.SelectedItem = Nothing End Sub
38. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams) Me.PlayersTableAdapter.Fill(Me.BaseballDataSet.Players) End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query1 = From player In BaseballDataSet.Players Join team In BaseballDataSet.Teams On player.team Equals team.name Where team.league = "American" Select player.hits Dim mostHits As Double = query1.Max Dim query2 = From player In BaseballDataSet.Players Join team In BaseballDataSet.Teams On player.team Equals team.name Where team.league = "American" And player.hits = mostHits Select player.name lstPlayers.DataSource = query2.ToList lstPlayers.SelectedItem = Nothing End Sub
Instructor Solutions Manual (Page 129 of 196) 39. film
40. film
41. Private Sub frmMovies_Load(...) Handles MyBase.Load Me.LinesTableAdapter.Fill(Me.MoviesDataSet.Lines) Me.ActorsTableAdapter.Fill(Me.MoviesDataSet.Actors) Dim query = From line In MoviesDataSet.Lines Select line.film Distinct lstFilms.DataSource = query.ToList End Sub Private Sub lstFilms_SelectedIndexChanged(...) Handles _ lstFilms.SelectedIndexChanged Dim query = From line In MoviesDataSet.Lines Join flick In MoviesDataSet.Actors On line.film Equals flick.film Where line.film = lstFilms.Text Select flick.maleLead txtLead.Text = query.First End Sub
42. Private Sub frmMovies_Load(...) Handles MyBase.Load Me.LinesTableAdapter.Fill(Me.MoviesDataSet.Lines) Me.ActorsTableAdapter.Fill(Me.MoviesDataSet.Actors) End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From line In MoviesDataSet.Lines Join flick In MoviesDataSet.Actors On line.film Equals flick.film Select line.famousLine, flick.maleLead, flick.film dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("famousLine").HeaderText = "Famous Line" dgvOutput.Columns("maleLead").HeaderText = "Actor" dgvOutput.Columns("film").HeaderText = "Film" End Sub
Instructor Solutions Manual (Page 130 of 196) 43. Private Sub frmFilms_Load(...) Handles MyBase.Load Me.LinesTableAdapter.Fill(Me.MoviesDataSet.Lines) Me.ActorsTableAdapter.Fill(Me.MoviesDataSet.Actors) Dim query = From flick In MoviesDataSet.Actors Select flick.maleLead Distinct lstActors.DataSource = query.ToList End Sub Private Sub lstFilms_SelectedIndexChanged(...) Handles _ lstActors.SelectedIndexChanged Dim query = From line In MoviesDataSet.Lines Join flick In MoviesDataSet.Actors On line.film Equals flick.film Where flick.maleLead = lstActors.Text Select line.famousLine lstLines.DataSource = query.ToList lstLines.SelectedItem = Nothing End Sub
x
Instructor Solutions Manual (Page 131 of 196) 44. Private Sub frmMovies_Load(...) Handles MyBase.Load Me.ActorsTableAdapter.Fill(Me.MoviesDataSet.Actors) Me.LinesTableAdapter.Fill(Me.MoviesDataSet.Lines) Dim query = From flick In MoviesDataSet.Actors Order By flick.film Select flick.film Distinct lstMovies.DataSource = query.ToList End Sub Private Sub lstMovies_SelectedIndexChanged(...) Handles lstMovies.SelectedIndexChanged Dim query = From line In MoviesDataSet.Lines Join flick In MoviesDataSet.Actors On line.film Equals flick.film Where flick.film = lstMovies.Text Select line.famousLine lstLines.DataSource = query.ToList lstLines.SelectedItem = Nothing End Sub
EXERCISES 10.2 6. Add a record to the Cities table whose country is not in the Countries table. 7. Add a record to the Cities table whose name field is empty or contains the same name as an already existing record. 8. Add a record to the Cities table with any or all of the country, pop2010 or pop2010 fields empty. 9. (BindingSource1.Find("name", strVar) = 0) And (strVar <> "Bombay")
Instructor Solutions Manual (Page 132 of 196) 10. Private Sub btnUpdate_Click(...) Handles btnUpdate.Click Try BindingSource1.EndEdit() CitiesTableAdapter.Update(MEGACITIESDataSet.Cities) Catch exp As OleDb.OleDbException MessageBox.Show("Rule of Referential Integrity violated.") End Try End Sub
11. Create a control named BindingSource2 that has the Countries table as its DataMember. Private Sub CountryTextBox_Leave(...) Handles _ CountryTextBox.Leave, BindingNavigator1.Click BindingSource2.Position = BindingSource2.Find("name", CountryTextBox.Text) If (CountryTextBox.Text <> "") And (BindingSource2.Position = 0) And (CountryTextBox.Text <> "Argentina") Then MessageBox.Show("Not a valid country.", "ERROR") CountryTextBox.Focus() End If End Sub 12. Private Sub NameTextBox_Leave(...) Handles _ NameTextBox.Leave, BindingNavigator1.Click If NameTextBox.Text = "" Then MessageBox.Show("You must include the name of a city.") NameTextBox.Focus() Else Dim index As Integer = BindingSource1.Find("name", NameTextBox.Text) If index <> 0 Then MessageBox.Show("There is already a record for " & NameTextBox.Text & ".") NameTextBox.Focus() End If End If End Sub 13. Private Sub frmMovies_Load(...) Handles MyBase.Load Me.LinesTableAdapter.Fill(Me.MoviesDataSet.Lines) End Sub Private Sub btnUpdate_Click(...) Handles btnUpdate.Click BindingSource1.EndEdit() LinesTableAdapter.Update(MoviesDataSet.Lines) End Sub
Instructor Solutions Manual (Page 133 of 196) 14. Private Sub frmMovies_Load(...) Handles MyBase.Load Me.ActorsTableAdapter.Fill(Me.MOVIESDataSet.Actors) End Sub Private Sub btnUpdate_Click(...) Handles btnUpdate.Click BindingSource1.EndEdit() ActorsTableAdapter.Update(MOVIESDataSet.Actors) End Sub
17. Apollo 13 does not appear in the key field of the Actors table. Thus the Rule of Referential Integrity would be violated. 18. Casablanca appears in the film field of the Lines table. Thus, the Rule of Referential Integrity would be violated. The program will crash when the Update button is clicked. 19. Replace the table with two tables. The first table should contain the fields name, address, and city. The second table should contain the fields city, state, and stateCapital. 20. Replace the table with two tables. The first table should contain the fields name, state, and party. The second table should contain the fields state, statePop, and numColleges. 21. Write a program similar to the one in Example 1, but using the database Justices accdb. Then use the program to update the database.
Instructor Solutions Manual (Page 134 of 196) CHAPTER 10 PROGRAMMING PROJECTS 1. Private Sub frmMicroland_Load(...) Handles MyBase.Load Me.OrdersTableAdapter.Fill(Me.MICROLANDDataSet.Orders) Me.InventoryTableAdapter.Fill(Me.MICROLANDDataSet.Inventory) Me.CustomersTableAdapter.Fill(Me.MICROLANDDataSet.Customers) End Sub Private Sub btnStock_Click(...) Handles btnStock.Click lstOutput.Items.Clear() lstOutput.Items.Add("Here are the items that are out of inventory " & "or must be reordered. ") lstOutput.Items.Add("The numbers shown give the minimum reorder" & "quantity required.") lstOutput.Items.Add("") Dim query1 = From item In MICROLANDDataSet.Orders Order By item.itemID Select item.itemID, item.quantity Dim query2 = From item In MICROLANDDataSet.Inventory Select item.itemID, item.quantity, item.description Dim ID, desc As String Dim quant As Integer For Each item In query2 ID = item.itemID quant = item.quantity desc = item.description Dim query3 = From ite In query1 Where ite.itemID = ID Select CInt(ite.quantity) If query3.Sum >= quant Then lstOutput.Items.Add(ID & " " & query3.Sum - quant & " " & desc) End If Next End Sub
Get complete Order files download link below htps://www.mediafire.com/file/�351cwx7zi5x55/SM+ An+Introduc�on+to+Programming+Using+Visual+Basic +2012,+9e+David+Schneider.zip/file
If this link does not work with a click, then copy the complete Download link and paste link in internet explorer/firefox/google chrome and get all files download successfully.
Instructor Solutions Manual (Page 135 of 196) 2. Private Sub frmGradeBook_Load(...) Handles MyBase.Load Me.GradesTableAdapter.Fill(Me.GRADEBOOKDataSet.Grades) Me.StudentsTableAdapter.Fill(Me.GRADEBOOKDataSet.Students) End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From person1 In GRADEBOOKDataSet.Students Join person2 In GRADEBOOKDataSet.Grades On person1.socSecNumber Equals person2.socSecNumber Let semGrade = ((person2.firstExam + person2.secondExam + 2 * person2.finalExam) / 4).ToString("N4") Let fullName = person1.firstName & " " & person1.lastName Select fullName, semGrade dgvSemesterGrades.DataSource = query.ToList dgvSemesterGrades.CurrentCell = Nothing End Sub Private Sub btnUpdate_Click(...) Handles btnUpdate.Click BindingSource2.EndEdit() GradesTableAdapter.Update(GRADEBOOKDataSet.Grades) MessageBox.Show("Grades table has been updated.") End Sub
Instructor Solutions Manual (Page 136 of 196) CHAPTER 11 EXERCISES 11.1 1. Any negative grade will be recorded as 0 and any grade greater than 100 will be recorded as 100. 2.
Every grade will be curved by 10 points.
3. Remove the keyword WriteOnly from the Midterm property block and add the following Get property procedure to it: Get Return m_midterm End Get
4.
Add the following procedure to the Student class block: Function Average() As Double Return (m_midterm + m_final) / 2 End Function
5. The properties Midterm and Final are write only. 6.
Sub New() Midterm = 10 Final = 10 End Sub
7. The property SocSecNum is initialized to the value 999-99-9999. 8.
The line scholar = New Student() should be inserted after the second line of the event procedure.
9. The keyword New is missing from the third line of the event procedure. 10. The member variable m_name was assigned a value from outside the class code. Even if the variable m_name were declared as Public, it would not be visible to the form’s code. 11. The statement nom = m_name is not valid. m_name would need to be Public and referred to by scholar.m_name. 12. The statement scholar.CalcSemGrade = "A"
is not valid. The method CalcSemGrade, which was defined by a Function procedure, returns a value, but cannot be used to set a value.
Instructor Solutions Manual (Page 137 of 196) 13. The statements pupil.Midterm = scholar.Midterm and lstGrades.Items.Add(pupil.Midterm) are not valid. The Midterm property is write only; it can be set, but cannot return a value. 14. The first two lines must be combined into one line: Dim scholar As New Student() 15. Country: Canada Capital: Ottawa Pop: 31 million
16. Replace the second line of the btnMove_Click event procedure with round.Xcoord += 20 round.Ycoord += 20
17. Change 20 to –20 in the btnMove_Click event procedure, and create a frmCircle_Load event procedure with the following lines, round.Xcoord = picCircle.Width - 40 round.Ycoord = picCircle.Height - 40
18. Place the statement Dim randomNum As New Random()
in the Declarations section of frmCircle's Code window, and replace the literal 20 with randomNum.Next(0, 41) in the btnMove_Click event procedure.
Instructor Solutions Manual (Page 138 of 196) 19. Class Square Private m_length, m_perimeter, m_area As Double Public Property Length() As Double Get Return m_length End Get Set(value As Double) m_length = value m_perimeter = value * 4 m_area = value * value End Set End Property Public Property Perimeter() As Double Get Return m_perimeter End Get Set(value As Double) m_perimeter = value m_length = value / 4 m_area = value * value / 16 End Set End Property Public Property Area() As Double Get Return m_area End Get Set(value As Double) m_area = value m_length = Math.Sqrt(value) m_perimeter = Math.Sqrt(value) * 4 End Set End Property End Class 'Square
Instructor Solutions Manual (Page 139 of 196) 20. Class Square Private m_length, m_perimeter, m_area As Double Public Property Length() As Double Get Return m_length End Get Set(value As Double) If value < 1 Then value = 1 ElseIf value > 10 Then value = 10 End If m_length = value m_perimeter = value * 4 m_area = value * value End Set End Property Public Property Perimeter() As Double Get Return m_perimeter End Get Set(value As Double) If value < 4 Then value = 4 ElseIf value > 40 Then value = 40 End If m_perimeter = value m_length = value / 4 m_area = value * value / 16 End Set End Property Public Property Area() As Double Get Return m_area End Get Set(value As Double) If value < 1 Then value = 1 ElseIf value > 100 Then value = 100 End If m_area = value m_length = Math.sqrt(value) m_perimeter = Math.sqrt(value) * 4 End Set End Property End Class
Instructor Solutions Manual (Page 140 of 196) 21. Class PairOfDice Private m_die1, m_die2 As Integer Dim randomNum As New Random() Public ReadOnly Property Die1() As Integer Get Return m_die1 End Get End Property Public ReadOnly Property Die2() As Integer Get Return m_die2 End Get End Property Public ReadOnly Property SumOfFaces() As Integer Get Return m_die1 + m_die2 End Get End Property Sub Roll() m_die1 = randomNum.Next(1, 7) m_die2 = randomNum.Next(1, 7) End Sub End Class 'PairOfDice
Instructor Solutions Manual (Page 141 of 196) 22. Public Class frmDice Private Sub btnRoll_Click(...) Handles btnRoll.Click 'Roll a pair of dice 1000 times. Dim dice As New PairOfDice() Dim count As Integer = 0 'Loop 1000 times. For i As Integer = 1 To 1000 dice.Roll() 'If the sum is 7, then count it. If dice.SumOfFaces = 7 Then count += 1 End If Next 'Display result. txtOutput.Text = "7 appeared " & count & " times." End Sub End Class 'frmDice Class PairOfDice Private m_die1, m_die2, m_sum As Integer Dim randomNum As New Random() 'Random number generator Public ReadOnly Property Die1() As Integer Get Return m_die1 End Get End Property Public ReadOnly Property Die2() As Integer Get Return m_die2 End Get End Property Public ReadOnly Property SumOfFaces() As Integer Get Return m_die1 + m_die2 End Get End Property Sub Roll() 'A die can have numbers between 1 and 6 inclusive m_die1 = randomNum.Next(1, 7) m_die2 = randomNum.Next(1, 7) End Sub End Class 'PairOfDice
Instructor Solutions Manual (Page 142 of 196) 23. Class College Private m_name As String Private m_students, m_faculty As Double Public WriteOnly Property Name() As String Set(Value As String) m_name = Value End Set End Property Public WriteOnly Property NumStudents() As Double Set(Value As Double) m_students = Value End Set End Property Public WriteOnly Property NumFaculty() As Double Set(Value As Double) m_faculty = Value End Set End Property Function SFRatio() As Double Return m_students / m_faculty End Function End Class 'College
Instructor Solutions Manual (Page 143 of 196) 24. Public Class frmWages Dim salary As New Wages() Private Sub btnCalculatePay_Click(...) Handles btnCalculatePay.Click 'Calculate weekly wage from input values in text boxes. salary.Hours = CDbl(txtHours.Text) salary.Wage = CDbl(txtWage.Text) txtPay.Text = (salary.PayForWeek).ToString("C") End Sub End Class 'frmWages Class Wages Private m_hours As Double Private m_wage As Double
'Number of hours worked during week 'Hourly wage
Public WriteOnly Property Hours() As Double Set(value As Double) m_hours = value End Set End Property Public WriteOnly Property Wage() As Double Set(value As Double) m_wage = value End Set End Property Function PayForWeek() As Double 'Calculate pay for the week. Return m_hours * m_wage End Function End Class 'Wages
Instructor Solutions Manual (Page 144 of 196) 25. Public Class frmCashRegister Dim register As New CashRegister() Private Sub btnAdd_Click(...) Handles btnAdd.Click 'Add an amount to the balance. register.Add(CDbl(txtAmount.Text)) txtBalance.Text = (register.Balance).ToString("C") txtAmount.Clear() txtAmount.Focus() End Sub Private Sub btnSubtract_Click(...) Handles btnSubtract.Click 'Subtract an amount from the balance. register.Subtract(CDbl(txtAmount.Text)) txtBalance.Text = (register.Balance).ToString("C") txtAmount.Clear() txtAmount.Focus() End Sub End Class 'frmCashRegister Class CashRegister Private m_balance As Double Public ReadOnly Property Balance() As Double Get Return m_balance End Get End Property Sub Add(amount As Double) If (m_balance + amount) >= 0 Then 'Ensure balance stays nonnegative m_balance += amount End If End Sub Sub Subtract(amount As Double) If (m_balance - amount) >= 0 Then 'Ensure balance stays nonnegative m_balance = m_balance - amount End If End Sub End Class 'CashRegister
Instructor Solutions Manual (Page 145 of 196) 26. Public Class frmAverage Dim stats As New Statistics() Private Sub btnRecord_Click(...) Handles btnRecord.Click 'Add a number to the statistics. stats.AddNumber(CInt(txtNumber.Text)) 'Clear and set the focus to the number text box. txtNumber.Clear() txtNumber.Focus() End Sub Private Sub btnAverage_Click(...) Handles btnAverage.Click 'Calculate and display the average txtAverage.Text = (stats.Average).ToString("N") End Sub End Class 'frmAverage Class Statistics Private m_numbers(49) As Integer Private m_count As Integer 'Count of numbers entered into array Sub AddNumber(number As Integer) 'Adds a number to the statistics m_count += 1 m_numbers(m_count) = number End Sub Public ReadOnly Property Count() As Integer 'Counter of numbers stored Get Return m_count End Get End Property Function Average() As Double 'Computes the average Dim sum As Integer = 0 For i As Integer = 1 To m_count sum += m_numbers(i) Next Return sum / m_count End Function End Class 'Statistics
Instructor Solutions Manual (Page 146 of 196) 27. Public Class frmFICA Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim tax As New FICA() tax.PreviousEarnings = CDbl(txtToDate.Text) tax.CurrentEarnings = CDbl(txtCurrent.Text) txtTax.Text = (tax.CalculateFICA).ToString("C") End Sub End Class 'frmFICA Class FICA 'Member variables store property values. Private m_previousEarnings As Double 'Previous year-to-date earnings Private m_currentEarnings As Double Public WriteOnly Property PreviousEarnings() As Double Set(Value As Double) m_previousEarnings = Value End Set End Property Public WriteOnly Property CurrentEarnings() As Double Set(Value As Double) m_currentEarnings = Value End Set End Property Function CalculateFICA() As Double 'Calculate Social Security benefits tax and Medicare tax 'for a single pay period in 2012. Dim socialSecurityBenTax, medicareTax As Double If (m_previousEarnings + m_currentEarnings) <= 110100 Then socialSecurityBenTax = 0.042 * m_currentEarnings ElseIf m_previousEarnings < 110100 Then socialSecurityBenTax = 0.042 * (110100 - m_previousEarnings) End If medicareTax = 0.0145 * m_currentEarnings Return socialSecurityBenTax + medicareTax End Function End Class 'FICA
Instructor Solutions Manual (Page 147 of 196) 28. Public Class frmAdd Dim x As New Fraction() Dim y As New Fraction() Dim z As New Fraction()
'left fraction 'Middle fraction 'Right fraction
Private Sub btnResult_Click(...) Handles btnResult.Click 'Add the x and y fractions to get the z fraction. 'Store the input into the x and y fractions. x.Num = CInt(txtNumX.Text) x.Den = CInt(txtDenX.Text) y.Num = CInt(txtNumY.Text) y.Den = CInt(txtDenY.Text) 'Add the two fractions. z.Num = (x.Num * y.Den) + (y.Num * x.Den) z.Den = x.Den * y.Den 'Reduce and display the result. z.Reduce() txtNumZ.Text = CStr(z.Num) txtDenZ.Text = CStr(z.Den) End Sub End Class 'frmAdd Class Fraction Private m_num As Double Private m_den As Double = 1
'Numerator 'Denominator set to default value
Public Property Num() As Double Get Return m_num End Get Set(Value As Double) m_num = Value End Set End Property Public Property Den() As Double Get Return m_den End Get Set(Value As Double) m_den = Value End Set End Property
Instructor Solutions Manual (Page 148 of 196) Sub Reduce() Dim t As Double Dim m As Double = m_num Dim n As Double = m_den 'Algorithm to calculate greatest common divisor of m and n. 'After the loop terminates, the value of m will be the GCD. Do While (n <> 0) t = n n = m Mod n m = t Loop 'Divide both numerator and denominator by greatest common divisor. If m <> 0 Then m_num = m_num / m m_den = m_den / m End If End Sub End Class 'Fraction
EXERCISES 11.2 1. Sub btnDisplay_Click(...) Handles btnDisplay.Click ReDim Preserve students(lastStudentAdded) Dim query = From pupil In students Let name = pupil.Name Let ssn = pupil.SocSecNum Let semGrade = pupil.CalcSemGrade Where semGrade = "A" Select pupil.Name, pupil.SocSecNum, pupil.CalcSemGrade dgvGrades.DataSource = query.ToList dgvGrades.CurrentCell = Nothing dgvGrades.Columns("Name").HeaderText = "Student Name" dgvGrades.Columns("SocSecNum").HeaderText = "SSN" dgvGrades.Columns("CalcSemGrade").HeaderText = "Grade" ReDim Preserve students(50) txtName.Focus() End Sub
Instructor Solutions Manual (Page 149 of 196) 2.
Class State 'Member variables hold property values. Private m_name, m_abbr, m_entered As String Private m_area, m_pop As Double Public ReadOnly Property Name() As String Get Return m_name End Get End Property Public ReadOnly Property Abbreviation() As String Get Return m_abbr End Get End Property Public ReadOnly Property Entered() As String Get Return m_entered End Get End Property Public ReadOnly Property Area() As Double Get Return m_area End Get End Property Public ReadOnly Property Population() As Double Get Return m_pop End Get End Property Public Sub New(n As String, a As String, _ e As String, ar As Double, p As Double) 'Store parameters into member variables. m_name = n m_abbr = a m_entered = e m_area = ar m_pop = p End Sub Function Density() As Double Return m_pop / m_area End Function End Class
Instructor Solutions Manual (Page 150 of 196) 3. Public Class frmStates Dim states(49) As State 'Holds the state's data Private Sub frmStates_Load(...) Handles MyBase.Load 'Load the data file into the array Dim usstates() As String = IO.File.ReadAllLines("UnitedStates.txt") Dim data() As String For i As Integer = 0 To 49 data = usstates(i).Split(","c) states(i) = New State(data(0), data(1), CDate(data(2)), CDbl(data(3)), CDbl(data(4))) Next End Sub Private Sub btnLookup_Click(...) Handles btnLookup.Click 'Look up name in the array and return the state information. Dim nm As String Dim i As Integer = 0 'Get name of state from message box nm = InputBox("Name of state:", "Enter state's name").ToUpper 'Clear the output text boxes txtName.Clear() txtAbbr.Clear() txtDensity.Clear() txtEntered.Clear() Dim query = From state In states Where state.Name.ToUpper = nm.ToUpper Select state.Name, state.Abbreviation, state.Density, state.Entered txtName.Text = query.First.Name txtAbbr.Text = query.First.Abbreviation txtDensity.Text = (query.First.Density).ToString("N1") txtEntered.Text = (query.First.Entered).ToString("D") End Sub End Class 'frmStates Class State Private m_name, m_abbr As String Private m_entered As Date Private m_area As Double Public ReadOnly Property Name() As String Get Return m_name End Get End Property Public ReadOnly Property Abbreviation() As String Get Return m_abbr End Get End Property
Instructor Solutions Manual (Page 151 of 196) Public ReadOnly Property Entered() As Date Get Return m_entered End Get End Property Public ReadOnly Property Area() As Double Get Return m_area End Get End Property Public Property Population() As Double Sub New(n As String, a As String, e As Date, ar As Double, p As Double) 'Store parameters into member variables m_name = n m_abbr = a m_entered = e m_area = ar _Population = p End Sub Function Density() As Double 'Density is calculated as population divided by area. Return _Population / m_area End Function End Class 'State
4. Public Class frmStates Dim states(49) As State
'Stores state data
Private Sub frmStates_Load(...) Handles MyBase.Load 'Load the data file into the array Dim usstates() As String = IO.File.ReadAllLines("United_States.txt") Dim data() As String For i As Integer = 0 To 49 data = usstates(i).Split(","c) states(i) = New State(data(0), data(1), CDate(data(2)), CDbl(data(3)), CDbl(data(4))) Next End Sub
Instructor Solutions Manual (Page 152 of 196) Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display the states and their densities ordered by density. Dim query = From state In states Order By state.Density Descending Let Density = (state.Density).ToString("N1") Select state.Name, Density dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing End Sub End Class 'frmStates Class State Private m_name, m_abbr As String Private m_entered As Date Private m_area As Double Public ReadOnly Property Name() As String Get Return m_name End Get End Property Public ReadOnly Property Abbreviation() As String Get Return m_abbr End Get End Property Public ReadOnly Property Entered() As Date Get Return m_entered End Get End Property Public ReadOnly Property Area() As Double Get Return m_area End Get End Property Public Property Population() As Double Sub New(n As String, a As String, e As Date, ar As Double, p As Double) 'Store parameters into member variables m_name = n m_abbr = a m_entered = e m_area = ar _Population = p End Sub Function Density() As Double 'Density is calculated as population divided by area. Return _Population / m_area End Function End Class 'State
Instructor Solutions Manual (Page 153 of 196) 5. Public Class frmStates Dim WithEvents usa As New UnitedStates() Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Load the data file into the array. Dim sr As IO.StreamReader = IO.File.OpenText("UnitedStates.txt") For i As Integer = 0 To 49 'Add each state to the USA object Dim data() As String = Split(sr.ReadLine, ","c) usa.Add(New State(data(0), data(1), CDate(data(2)), CDbl(data(3)), CDbl(data(4)))) Next sr.Close() End Sub Sub Populous(name As String, population As Double) Handles usa.Populous 'Display the populous states and their populations in the list box. lstOutput.Items.Add(name & ": " & population.ToString("N0")) End Sub End Class 'frmStates Class UnitedStates Dim states(49) As State 'Holds the state data Dim count As Integer 'Last stored state 'The event contains the state's name and population Public Event Populous(name As String, population As Double) Sub Add(state As State) 'Add the state to the array states(count) = state count += 1 'If the state's population is large then raise an event If state.Population > 10000000 Then RaiseEvent Populous(state.Name, state.Population) End If End Sub End Class 'UnitedStates Class State Private m_name, m_abbr As String Private m_entered As Date Private m_area As Double Public ReadOnly Property Name() As String Get Return m_name End Get End Property
Instructor Solutions Manual (Page 154 of 196) Public ReadOnly Property Abbreviation() As String Get Return m_abbr End Get End Property Public ReadOnly Property Entered() As Date Get Return m_entered End Get End Property Public ReadOnly Property Area() As Double Get Return m_area End Get End Property Public Property Population() As Double Sub New(n As String, a As String, e As Date, ar As Double, p As Double) 'Store parameters into member variables m_name = n m_abbr = a m_entered = e m_area = ar _Population = p End Sub Function Density() As Double 'Density is calculated as population divided by area. Return _Population / m_area End Function End Class 'State
Instructor Solutions Manual (Page 155 of 196) 6. Public Class frmDice Dim WithEvents dice As New PairOfDice() Private Sub btnRoll_Click(...) Handles btnRoll.Click dice.Roll() 'Roll the dice. 'Display the results. txtDie1.Text = CStr(dice.Die1) txtDie2.Text = CStr(dice.Die2) End Sub Sub dice_SnakeEyes() Handles dice.SnakeEyes txtDie1.Text = CStr(dice.Die1) txtDie2.Text = CStr(dice.Die2) MessageBox.Show("Snake Eyes!") End Sub End Class 'frmDice Class PairOfDice Private m_die1, m_die2 As Integer Dim randomNum As New Random() 'Random number generator Public Event SnakeEyes() Public ReadOnly Property Die1() As Integer Get Return m_die1 End Get End Property Public ReadOnly Property Die2() As Integer Get Return m_die2 End Get End Property Public ReadOnly Property SumOfFaces() As Integer Get Return m_die1 + m_die2 End Get End Property Sub Roll() m_die1 = randomNum.Next(1, 7) m_die2 = randomNum.Next(1, 7) 'If snake eyes, then raise the event. If (m_die1 = 1) And (m_die2 = 1) Then RaiseEvent SnakeEyes() End If End Sub End Class 'PairOfDice
Instructor Solutions Manual (Page 156 of 196) 7. Public Class frmCashRegister Dim WithEvents register As New CashRegister() Private Sub btnAdd_Click(...) Handles btnAdd.Click register.Add(CDbl(txtAmount.Text)) txtBalance.Text = (register.Balance).ToString("C") txtAmount.Clear() txtAmount.Focus() End Sub Private Sub btnSubtract_Click(...) Handles btnSubtract.Click register.Subtract(CDbl(txtAmount.Text)) txtBalance.Text = (register.Balance).ToString("C") txtAmount.Clear() txtAmount.Focus() End Sub Private Sub AttemptToOverdraw(amt As Double) Handles _ register.AttemptToOverdraw MessageBox.Show("You would have been overdrawn by " & amt.ToString("C") & ".", "Withdrawal Denied") End Sub End Class 'frmCashRegister Class CashRegister Private m_balance As Double Public Event AttemptToOverdraw(amt As Double) Public ReadOnly Property Balance() As Double Get Return m_balance End Get End Property Sub Add(amount As Double) If (m_balance + amount) >= 0 Then 'Ensure balance stays nonnegative m_balance += amount Else RaiseEvent AttemptToOverdraw(amount + m_balance) End If End Sub Sub Subtract(amount As Double) If (m_balance - amount) >= 0 Then 'Ensure balance stays nonnegative m_balance = m_balance - amount Else RaiseEvent AttemptToOverdraw(amount - m_balance) End If End Sub End Class 'CashRegister
Instructor Solutions Manual (Page 157 of 196) 8.
Public Class frmSquare Dim WithEvents poly As Square Sub poly_IllegalNumber(name As String, num As Double) _ Handles poly.IllegalNumber MessageBox.Show("You cannot set the " & name & " to " & num) End Sub Private Sub btnGo_Click(...) Handles btnGo.Click poly = New Square() poly.Area = -25 txtLength.Text = CStr(poly.Length) txtPerimeter.Text = CStr(poly.Perimeter) End Sub End Class 'frmSquare Class Square Private m_length, m_perimeter, m_area As Double Event IllegalNumber(name As String, num As Double) Public Property Length() As Double Get Return m_length End Get Set(value As Double) If value < 0 Then RaiseEvent IllegalNumber("Length", value) Else m_length = value m_perimeter = value * 4 m_area = value * value End If End Set End Property Public Property Perimeter() As Double Get Return m_perimeter End Get Set(value As Double) If value < 0 Then RaiseEvent IllegalNumber("Perimeter", value) Else m_perimeter = value m_length = value / 4 m_area = value * value / 16 End If End Set End Property Public Property Area() As Double Get Return m_area End Get Set(value As Double) If value < 0 Then RaiseEvent IllegalNumber("Area", value)
Instructor Solutions Manual (Page 158 of 196) Else m_area = value m_length = Math.sqrt(value) m_perimeter = Math.sqrt(value) * 4 End If End Set End Property End Class 9. Public Class frmAdd Dim WithEvents x As New Fraction() Dim WithEvents y As New Fraction() Dim WithEvents z As New Fraction()
'Left fraction 'Middle fraction 'Right fraction
Private Sub btnResult_Click(...) Handles btnResult.Click 'Add the x and y fractions to get the z fraction. 'Store the input into the x and y fractions. x.Num = CInt(txtNumX.Text) x.Den = CInt(txtDenX.Text) y.Num = CInt(txtNumY.Text) y.Den = CInt(txtDenY.Text) 'Add the two fractions. z.Num = (x.Num * y.Den) + (y.Num * x.Den) z.Den = x.Den * y.Den 'Reduce and display the result. z.Reduce() txtNumZ.Text = CStr(z.Num) txtDenZ.Text = CStr(z.Den) End Sub Sub fraction_ZeroDenominator() Handles x.ZeroDenominator, _ y.ZeroDenominator 'If x or y has a zero denominator, display an error message. Dim message As String = "You cannot set a denominator to zero. " & "All such denominators will be replaced by 1." MessageBox.Show(message) If txtDenX.Text = "0" Then txtDenX.Text = CStr(1) x.Den = 1 End If If txtDenY.Text = "0" Then txtDenY.Text = CStr(1) y.Den = 1 End If End Sub End Class 'frmAdd
Instructor Solutions Manual (Page 159 of 196) Class Fraction Private m_den As Double = 1
'Denominator set to default value
Public Event ZeroDenominator() Public Property Num() As Double Public Property Den() As Double Get Return m_den End Get Set(Value As Double) 'Raise the event if zero If Value = 0 Then RaiseEvent ZeroDenominator() Else m_den = Value End If End Set End Property Sub Reduce() Dim t As Double Dim m As Double = Num Dim n As Double = m_den 'Algorithm to calculate greatest common divisor of m and n. 'After the loop terminates, the value of m will be the GCD. Do While (n <> 0) t = n n = m Mod n m = t Loop 'Divide both numerator and denominator by greatest common divisor. If m <> 0 Then Num = Num / m m_den = m_den / m End If End Sub End Class 'Fraction
Instructor Solutions Manual (Page 160 of 196) 10. Public Class frmCalculator Dim calc As New Calculator() Sub ReadFractions() 'Read the text boxes into the fractions calc.x.Num = CInt(mtbNumX.Text) calc.x.Den = CInt(mtbDenX.Text) calc.y.Num = CInt(mtbNumY.Text) calc.y.Den = CInt(mtbDenY.Text) End Sub Sub DisplayResult() 'Display the values from the z fraction txtNumZ.Text = CStr(calc.z.Num) txtDenZ.Text = CStr(calc.z.Den) End Sub Private Sub btnPlus_Click(...) Handles btnPlus.Click 'Read the fractions, add them and display the result ReadFractions() calc.Add() DisplayResult() End Sub Private Sub bntMinus_Click(...) Handles bntMinus.Click 'Read the fractions, subtract them and display the result ReadFractions() calc.Subtract() DisplayResult() End Sub Private Sub btnMultiply_Click(...) Handles btnMultiply.Click 'Read the fractions, multiply them and display the result ReadFractions() calc.Multiply() DisplayResult() End Sub Private Sub bntDivide_Click(...) Handles bntDivide.Click 'Read the fractions, divide them and display the result ReadFractions() calc.Divide() DisplayResult() End Sub End Class 'frmCalculator Public Class Calculator Private m_x As New Fraction() Private m_y As New Fraction() Private m_z As New Fraction()
'Left fraction 'Middle fraction 'Right fraction
Public ReadOnly Property x() As Fraction Get Return m_x End Get End Property
Instructor Solutions Manual (Page 161 of 196) Public ReadOnly Property y() As Fraction Get Return m_y End Get End Property Public ReadOnly Property z() As Fraction Get Return m_z End Get End Property Sub Add() 'Add the numerators, using the common denominator multiple z.Num = (x.Num * y.Den) + (y.Num * x.Den) z.Den = x.Den * y.Den 'Reduce the result. z.Reduce() End Sub Sub Subtract() 'Subtract the numerators, using the common denominator multiple z.Num = (x.Num * y.Den) - (y.Num * x.Den) z.Den = x.Den * y.Den 'Reduce the result z.Reduce() End Sub Sub Multiply() 'Multiply the numerators and denominators z.Num = x.Num * y.Num z.Den = x.Den * y.Den 'Reduce the result z.Reduce() End Sub Sub Divide() 'Multiply the first fraction by the inverse of the second z.Num = x.Num * y.Den z.Den = x.Den * y.Num 'Reduce the result z.Reduce() End Sub End Class 'Calculator Public Class Fraction Private m_num As Double Private m_den As Double = 1
'Numerator 'Denominator set to default value
Public Property Num() As Double Get Return m_num End Get Set(Value As Double) m_num = Value End Set End Property
Instructor Solutions Manual (Page 162 of 196)
Public Property Den() As Double Get Return m_den End Get Set(Value As Double) m_den = Value End Set End Property Sub Reduce() Dim t As Double Dim m As Double = Num Dim n As Double = Den 'Algorithm to calculate greatest common divisor of m and n. 'After the loop terminates, the value of m will be the GCD. Do While (n <> 0) t = n n = m Mod n m = t Loop 'Divide both numerator and denominator by greatest common divisor. If (m <> 0) Then m_num = m_num / m m_den = m_den / m End If End Sub End Class 'Fraction
Instructor Solutions Manual (Page 163 of 196) 11. Public Class frmDice Dim game As New HighRoller() Private Sub btnPlay_Click(...) Handles btnPlay.Click 'Play the game. game.Play() 'Display the throws. Randomize() txt1Die1.Text = CStr(game.First.Die1) txt1Die2.Text = CStr(game.First.Die2) txt2Die1.Text = CStr(game.Second.Die1) txt2Die2.Text = CStr(game.Second.Die2) 'Display the results Select Case game.First.SumOfFaces Case game.Second.SumOfFaces txtOutput.Text = "Tie." Case Is > game.Second.SumOfFaces txtOutput.Text = "Player 1 wins." Case Else txtOutput.Text = "Player 2 wins." End Select End Sub End Class 'frmDice Class HighRoller Private m_first As PairOfDice Private m_second As PairOfDice
'First player 'Second player
Public Sub New() m_first = New PairOfDice() 'The time is used to determine how the sequence of random numbers 'will be generated. The For...Next loop below guarantees that the 'two random number generators will act differently. Without the 'For...Next loop, often the two rolls will be identical. For i As Integer = 1 To 10000000 Next Second = New PairOfDice() End Sub Public ReadOnly Property First() As PairOfDice Get Return m_first End Get End Property Public Property Second() As PairOfDice Get Return m_second End Get Set(value As PairOfDice) m_second = value End Set End Property
Instructor Solutions Manual (Page 164 of 196) Sub Play() 'Roll both pairs of dice. m_first.Roll() m_second.Roll() End Sub End Class 'HighRoller Class PairOfDice Private m_die1, m_die2 As Integer Dim randomNum As New Random() 'Random number generator Public ReadOnly Property Die1() As Integer Get Return m_die1 End Get End Property Public ReadOnly Property Die2() As Integer Get Return m_die2 End Get End Property Public ReadOnly Property SumOfFaces() As Integer Get Return m_die1 + m_die2 End Get End Property Sub Roll() 'Get random numbers between 1 through 6 inclusive. m_die1 = randomNum.Next(1, 7) m_die2 = randomNum.Next(1, 7) End Sub End Class 'PairOfDice
Instructor Solutions Manual (Page 165 of 196) 12. Public Class frmCashRegister Dim WithEvents regular As New Choices() Dim WithEvents kids As New Choices() Dim WithEvents order As New Choices()
'Regular menu 'Kids menu 'Current order
Private Sub frmCashRegister_Load(...) Handles MyBase.Load 'Initialize the regular and kids menus. Dim m As Food 'Populate regular choices m = New Food("pizza slice", 1.75) regular.Add(m) m = New Food("burger", 2.55) regular.Add(m) m = New Food("salad", 3.29) regular.Add(m) m = New Food("large soda", 1.25) regular.Add(m) m = New Food("medium soda", 0.9) regular.Add(m) 'Populate kids choices m = New Food("hot dog", 1.5) kids.Add(m) m = New Food("small soda", 0.6) kids.Add(m) m = New Food("cookie", 0.96) kids.Add(m) 'Display menus in list box For i As Integer = 0 To (regular.Count – 1) lstRegular.Items.Add(regular.Entry(i).Name & " (" & (regular.Entry(i).Price).ToString("C") & ")") Next For i As Integer = 0 To (kids.Count – 1) lstKids.Items.Add(kids.Entry(i).Name & " (" & (kids.Entry(i).Price).ToString("C") & ")") Next End Sub Private Sub btnRegular_Click(...) Handles btnRegular.Click 'Add an item from the regular menu to the order Dim choice As Integer 'Get the current choice; index starts at zero. choice = lstRegular.SelectedIndex If choice >= 0 Then 'Add an item from a menu to the order. Dim ent As Food 'Get the food item selected ent = regular.Entry(choice) 'Add it to the order, and display it. order.Add(ent) lstOrder.Items.Add(ent.Name & " (" & (ent.Price).ToString("C") & ")") End If End Sub Private Sub btnKids_Click(...) Handles btnKids.Click 'Add an item from the kids menu to the order. Dim choice As Integer 'Get the current choice; index starts at zero. choice = lstKids.SelectedIndex If choice >= 0 Then 'Add an item from a menu to the order. Dim ent As Food 'Get the food item selected ent = kids.Entry(choice)
Instructor Solutions Manual (Page 166 of 196) 'Add it to the order, and display it. order.Add(ent) lstOrder.Items.Add(ent.Name & " (" & (ent.Price).ToString("C") & ")") End If End Sub Private Sub btnClear_Click(...) Handles btnClear.Click order.Clear() End Sub Private Sub btnQuit_Click(...) Handles btnQuit.Click End 'Terminate the program. End Sub Private Sub order_ChoiceChanged(price As Double) Handles _ order.ChoiceChanged 'When the order has changed, update the price. If price = 0 Then 'If the price is 0, then the order was cleared. 'Clear the display and total. lstOrder.Items.Clear() txtTotal.Clear() Else 'Display the new total for the order. txtTotal.Text = (order.Total).ToString("C") End If End Sub End Class 'frmCashRegister Class Choices Dim m_entries(10) As Food
'Initial limit is 11 entries
Private m_lastEntryAdded As Integer 'Keeps track of # of entries Private m_total As Double 'Total price of the order Public Event ChoiceChanged(price As Double) Public ReadOnly Property Entry(i As Integer) As Food Get 'Return the item at the desired subscript. Return m_entries(i) End Get End Property Public ReadOnly Property Count() As Integer Get Return m_lastEntryAdded End Get End Property Public ReadOnly Property Total() As Double Get Return m_total End Get End Property Sub Add(Item As Food) 'Add the food item. 'Make room for the new item. If (m_entries.Count – 1) < m_lastEntryAdded Then ReDim Preserve m_entries(m_lastEntryAdded + 5) End If 'Store the item. m_entries(m_lastEntryAdded) = Item
Instructor Solutions Manual (Page 167 of 196) 'Add the items price to the menu's total m_total += Item.Price 'Raise the event with the new item as parameter. RaiseEvent ChoiceChanged(Item.Price) m_lastEntryAdded += 1 End Sub Sub Clear() 'Reset the counter and total. m_lastEntryAdded = 0 m_total = 0 'Raise the event with 0 as parameter. RaiseEvent ChoiceChanged(0) End Sub End Class 'Choices Class Food 'Member variables hold property values Private m_name As String Private m_price As Double Public Sub New(name As String, price As Double) 'Set the member variables to the parameter values. m_name = name m_price = price End Sub Public ReadOnly Property Name() As String Get Return m_name End Get End Property Public ReadOnly Property Price() As Double Get Return m_price End Get End Property End Class 'Food
Instructor Solutions Manual (Page 168 of 196) 13. Public Class frmPayroll Dim emp As New Employee() Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Read input and display paycheck receipt Dim wages, takeHome As Double 'Store input into properties emp.Name = txtName.Text emp.Hours = CDbl(txtHours.Text) emp.Salary = CDbl(txtSalary.Text) emp.YearToDate = CDbl(txtYtd.Text) emp.Withhold = CInt(txtWithhold.Text) emp.Married = radMarried.Checked 'Calculate take-home pay. wages = emp.Hours * emp.Salary takeHome = wages - emp.FICA - emp.Withholding 'Display paycheck receipt. lstOutput.Items.Clear() lstOutput.Items.Add("Name: " & emp.Name) lstOutput.Items.Add("Weekly Wages: " & wages.ToString("C")) lstOutput.Items.Add("Year-to-Date Wages: " & (emp.YearToDate + wages).ToString("C")) lstOutput.Items.Add("FICA tax deduction: " & (emp.FICA).ToString("C")) lstOutput.Items.Add("Withholding tax deduction: " & (emp.Withholding).ToString("C")) lstOutput.Items.Add("Take-home Pay: " & takeHome.ToString("C")) End Sub End Class 'frmPayroll Class Employee Private m_hours As Double Private m_salary As Double Dim tax As New Tax()
'Represents the tax for this employee
Public Property Name() As String Public Property Hours() As Double Get Return m_hours End Get Set(Value As Double) m_hours = Value 'Update the tax property also tax.Wages = m_hours * m_salary End Set End Property
Instructor Solutions Manual (Page 169 of 196) Public Property Salary() As Double Get Return m_salary End Get Set(Value As Double) m_salary = Value 'Update the tax property also tax.Wages = m_hours * m_salary End Set End Property Public Property YearToDate() As Double Get 'Return the tax property Return tax.YearToDate End Get Set(Value As Double) 'Update the tax property tax.YearToDate = Value End Set End Property Public Property Withhold() As Integer Get 'Return the tax property Return tax.Withhold End Get Set(Value As Integer) 'Update the tax property tax.Withhold = Value End Set End Property Public Property Married() As Boolean Get 'Return the tax property Return tax.Married End Get Set(Value As Boolean) 'Update the tax property tax.Married = Value End Set End Property Function FICA() As Double 'Return the tax property Return tax.FICA End Function Function Withholding() As Double 'Return the tax property Return tax.Withholding End Function End Class 'Employee
Instructor Solutions Manual (Page 170 of 196) Class Tax Public Property Wages() As Double Public Property YearToDate() As Double Public Property Withhold() As Integer Public Property Married() As Boolean Function FICA() As Double 'Calculate Social Security benefits tax and Medicare tax 'for a single pay period in 2012 Dim socialSecurityBenTax, medicare As Double If (YearToDate + Wages) <= 110100 Then socialSecurityBenTax = 0.042 * Wages ElseIf YearToDate < 110100 Then socialSecurityBenTax = 0.062 * (110100 - YearToDate) End If medicare = 0.0145 * Wages 'Return the sum Return socialSecurityBenTax + medicare End Function Function Withholding() As Double Dim adjPay As Double = Wages - (70.19 * Withhold) 'Subtract exemptions If Married Then Select Case adjPay Case 0 To 156 Return 0 Case 156 To 490 Return 0.1 * (adjPay - 156) Case 490 To 1515 Return 33.4 + 0.15 * (adjPay - 490) Case 1515 To 2900 Return 187.15 + 0.25 * (adjPay - 1515) Case 2900 To 4338 Return 533.4 + 0.28 * (adjPay - 2900) Case 4338 To 7624 Return 936.04 + 0.33 * (adjPay - 4338) Case Is > 7624 Return 2020.42 + 0.35 * (adjPay - 7624) End Select Else 'Withholding table for single earners Select Case adjPay Case 0 To 41 Return 0 Case 41 To 209 Return (0.1 * (adjPay - 41)) Case 209 To 721 Return 16.8 + 0.15 * (adjPay - 209) Case 721 To 1688 Return 93.6 + 0.25 * (adjPay - 721) Case 1688 To 3477 Return 335.35 + 0.28 * (adjPay - 1688) Case 3477 To 7510 Return 836.27 + 0.33 * (adjPay - 3477) Case Is > 7510 Return 2167.16 + 0.35 * (adjPay - 7510) End Select
Instructor Solutions Manual (Page 171 of 196) End If End Function End Class 'Tax
EXERCISES 11.3 1. 4
2. 8
3. 64
4. 8
5. Can move Has jointed limbs and no backbone
6. Can move Has a backbone 7. The keyword Overrides should be Inherits. 8. The class Greetings should inherit the class Hello, not the function Hi(). 9. The Hi function should be declared with the Overridable keyword in class Hello and with the keyword Overrides keyword in class Aussie. 10. The Hi function should be declared with the Overridable keyword in class Hello. 11. The Hi function should be declared with the Overrides keyword in class Cowboy. 12. The MustOverride keyword should be replaced with Overridable. 13. The Hello class should be declared with the MustInherit keyword, and the function Hi should be declared with the MustOverride keyword. 14. The Hello class should be declared with the MustInherit keyword. 15. The Hello class should be declared with the MustInherit keyword, not MustOverride. 16. The function Hi in the NorthEasterner class may not take a parameter.
Instructor Solutions Manual (Page 172 of 196) 17. Public Class frmCalculator 'Create the machines Dim adder As New AddingMachine() Dim calc As New Calculator() Dim sci As New ScientificCalculator() Private Sub radAddingMachine_CheckedChanged(...) Handles _ radAddingMachine.CheckedChanged 'Hide the multiply, divide and exponentiation 'functionality if checked If radAddingMachine.Checked Then btnMultiply.Visible = False btnDivide.Visible = False btnExponentiation.Visible = False End If End Sub Private Sub radCalculator_CheckedChanged(...) Handles _ radCalculator.CheckedChanged 'Show the multiply and divide functionality, 'hide the exponentiation if checked If radCalculator.Checked Then btnMultiply.Visible = True btnDivide.Visible = True btnExponentiation.Visible = False End If End Sub Private Sub radScientific_CheckedChanged(...) Handles _ radScientific.CheckedChanged 'Show the multiply, divide and exponentiation 'functionality if checked If radScientific.Checked Then btnMultiply.Visible = True btnDivide.Visible = True btnExponentiation.Visible = True End If End Sub Private Sub btnAdd_Click(...) Handles btnAdd.Click If radAddingMachine.Checked Then 'If adding machine selected, use it to get the result adder.num1 = CDbl(txtNumber1.Text) adder.num2 = CDbl(txtNumber2.Text) txtResult.Text = CStr(adder.Add()) ElseIf radCalculator.Checked Then 'If calculator selected, use it to get the result calc.num1 = CDbl(txtNumber1.Text) calc.num2 = CDbl(txtNumber2.Text) txtResult.Text = CStr(calc.Add()) Else 'If scientific calculator selected, use it to get the result sci.num1 = CDbl(txtNumber1.Text) sci.num2 = CDbl(txtNumber2.Text) txtResult.Text = CStr(sci.Add()) End If End Sub
Instructor Solutions Manual (Page 173 of 196) Private Sub btnSubtract_Click(...) Handles btnSubtract.Click If radAddingMachine.Checked Then 'If adding machine selected, use it to get the result adder.num1 = CDbl(txtNumber1.Text) adder.num2 = CDbl(txtNumber2.Text) txtResult.Text = CStr(adder.Subtract()) ElseIf radCalculator.Checked Then 'If calculator selected, use it to get the result calc.num1 = CDbl(txtNumber1.Text) calc.num2 = CDbl(txtNumber2.Text) txtResult.Text = CStr(calc.Subtract()) Else 'If scientific calculator selected, use it to get the result sci.num1 = CDbl(txtNumber1.Text) sci.num2 = CDbl(txtNumber2.Text) txtResult.Text = CStr(sci.Subtract()) End If End Sub Private Sub btnMultiply_Click(...) Handles btnMultiply.Click If radCalculator.Checked Then 'If calculator selected, use it to get the result. calc.num1 = CDbl(txtNumber1.Text) calc.num2 = CDbl(txtNumber2.Text) txtResult.Text = CStr(calc.Multiply()) Else 'If scientific calculator selected, use it to get the result. sci.num1 = CDbl(txtNumber1.Text) sci.num2 = CDbl(txtNumber2.Text) txtResult.Text = CStr(sci.Multiply()) End If End Sub Private Sub btnDivide_Click(...) Handles btnDivide.Click If radCalculator.Checked Then 'If calculator selected, use it to get the result. calc.num1 = CDbl(txtNumber1.Text) calc.num2 = CDbl(txtNumber2.Text) txtResult.Text = CStr(calc.Divide()) Else 'If scientific calculator selected, use it to get the result sci.num1 = CDbl(txtNumber1.Text) sci.num2 = CDbl(txtNumber2.Text) txtResult.Text = CStr(sci.Divide()) End If End Sub Private Sub btnExponentiation_Click(...) Handles _ btnExponentiation.Click sci.num1 = CDbl(txtNumber1.Text) sci.num2 = CDbl(txtNumber2.Text) txtResult.Text = CStr(sci.Exponentiation()) End Sub End Class 'frmCalculator
Instructor Solutions Manual (Page 174 of 196) Class AddingMachine Property num1() As Double Property num2() As Double Function Add() As Double Return num1 + num2 End Function Function Subtract() As Double Return num1 - num2 End Function End Class 'AddingMachine Class Calculator Inherits AddingMachine 'Calculator inherits properties num1 and num2 'and functions add() and subtract(). Function Multiply() As Double Return num1 * num2 End Function Function Divide() As Double Return num1 / num2 End Function End Class 'Calculator Class ScientificCalculator Inherits Calculator 'ScientificCalculator inherits properties num1 and num2 'and methods Add(), Subtract(), Multiply, and Divide. Function Exponentiation() As Double 'Raise the first number by the second Return num1 ^ num2 End Function End Class 'ScientificCalculator
Instructor Solutions Manual (Page 175 of 196) 18. Public Class frmGrades Dim students(49) As Student 'Stores the class Dim lastStudentAdded As Integer = -1 'Last student added to Students Private Sub btnEnter_Click(...) Handles btnEnter.Click Dim pupil As Student 'Create the appropriate object depending upon the radio button If rdoPassFail.Checked Then pupil = New PFStudent() Else pupil = New LGStudent() End If 'Store the values in the text boxes into the object pupil.Name = txtName.Text pupil.SocSecNum = mtbSSN.Text pupil.Midterm = CDbl(txtMidterm.Text) pupil.Final = CDbl(txtFinal.Text) 'Add the student to the array lastStudentAdded += 1 students(lastStudentAdded) = pupil 'Clear text boxes and list box txtName.Clear() mtbSSN.Clear() txtMidterm.Clear() txtFinal.Clear() MessageBox.Show("Student #" & lastStudentAdded + 1 & " recorded.") End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click ReDim Preserve students(lastStudentAdded) Dim query = From pupil In students Select pupil.Name, pupil.SocSecNum, pupil.CalcSemGrade dgvGrades.DataSource = query.ToList dgvGrades.CurrentCell = Nothing dgvGrades.Columns("Name").HeaderText = "Student Name" dgvGrades.Columns("SocSecNum").HeaderText = "SSN" dgvGrades.Columns("CalcSemGrade").HeaderText = "Grade" ReDim Preserve students(50) txtName.Focus() End Sub Private Sub btnQuit_Click(...) Handles btnQuit.Click Me.Close() End Sub End Class 'frmGrades MustInherit Class Student Public Property Name() As String Public Property SocSecNum() As String Public Property Midterm() As Double Public Property Final() As Double 'Child classes must override this function MustOverride Function CalcSemGrade() As String End Class 'Student
Instructor Solutions Manual (Page 176 of 196) Class LGStudent Inherits Student Overrides Function CalcSemGrade() As String Dim grade As Double grade = (Midterm + Final) / 2 grade = Math.Round(grade) 'Round the grade Select Case grade Case Is >= 90 Return "A" Case Is >= 80 Return "B" Case Is >= 70 Return "C" Case Is >= 60 Return "D" Case Else Return "F" End Select End Function End Class 'LGStudent Class PFStudent Inherits Student Overrides Function CalcSemGrade() As String Dim grade As Double 'The grade is based upon average of the midterm and final exams grade = (Midterm + Final) / 2 grade = Math.Round(grade) 'Round the grade If grade >= 60 Then Return "Pass" Else Return "Fail" End If End Function End Class 'PFStudent
Instructor Solutions Manual (Page 177 of 196) 19. Public Class frmRegister Dim tollBooth As New FastTrackRegister() Private Sub btnProcess_Click(...) Handles btnProcess.Click If radCar.Checked Then tollBooth.ProcessCar() Else tollBooth.ProcessTruck() End If txtRevenue.Text = (tollBooth.Balance).ToString("C") txtNumVehicles.Text = CStr(tollBooth.Count) End Sub End Class 'frmRegister Class CashRegister Private m_balance As Double Sub Deposit(amount As Double) m_balance += amount End Sub Sub WithDrawal(amount As Double) m_balance = m_balance - amount End Sub Public ReadOnly Property Balance() As Double Get Return m_balance End Get End Property End Class 'CashRegister Class FastTrackRegister Inherits CashRegister Private m_count As Integer Public ReadOnly Property Count() As Integer Get Return m_count End Get End Property Sub ProcessCar() m_count += 1 'Process a car: $1.00 Deposit(1) End Sub Sub ProcessTruck() m_count += 1 'Process a truck: $2.00 Deposit(2) End Sub End Class 'FastTrackRegister
Instructor Solutions Manual (Page 178 of 196)
20. Public Class frmGrades Dim WithEvents data As New CompleteStats() Private Sub btnRecord_Click(...) Handles btnRecord.Click 'Add the grade to the statistics data.AddNumber(CInt(txtGrade.Text)) 'Update the count txtCount.Text = CStr(data.Count) 'Clear the input for the next grade txtGrade.Clear() txtGrade.Focus() End Sub Private Sub btnAverage_Click(...) Handles btnAverage.Click 'Display the average grade txtAverage.Text = (data.Average).ToString("N") End Sub Sub Spread(spread As Integer) Handles data.NewSpread 'Display the new spread txtSpread.Text = CStr(spread) End Sub End Class 'frmGrades Class Statistics Private m_numbers(50) As Integer Private m_count As Integer 'Count of numbers entered into array Overridable Sub AddNumber(number As Integer) 'Adds a number to the array m_count += 1 m_numbers(m_count) = number End Sub Public ReadOnly Property Count() As Integer Get Return m_count End Get End Property Function Average() As Double 'Computes the average Dim sum As Integer = 0 For i As Integer = 1 To m_count sum += m_numbers(i) Next Return sum / m_count End Function End Class 'Statistics
Instructor Solutions Manual (Page 179 of 196) Class CompleteStats Inherits Statistics Private m_min As Integer = 100 'Current minimum Private m_max As Integer = 0 'Current maximum Public Event NewSpread(spread As Integer) 'Raised for a new spread Overrides Sub AddNumber(number As Integer) MyBase.AddNumber(number) If number < m_min Then 'If new number is less than current minimum then raise the event m_min = number RaiseEvent NewSpread(Spread()) End If If number > m_max Then 'If new number is more than current maximum then raise the event m_max = number RaiseEvent NewSpread(Spread()) End If End Sub Function Spread() As Integer 'Returns the difference between maximum and minimum Return m_max - m_min End Function End Class 'CompleteStats
Instructor Solutions Manual (Page 180 of 196) 21. Public Class frmBookstore Dim books(10) As Book Dim count As Integer
'Stores books 'Last stored book
Private Sub btnOrder_Click(...) Handles btnOrder.Click 'Create appropriate book object Dim book As Book If radTextbook.Checked Then book = New Textbook() Else book = New Tradebook() End If 'Store the values into the book object book.Name = txtName.Text book.Cost = CDbl(txtCost.Text) book.Quantity = CInt(txtQuantity.Text) 'Increment counter and store book into array books(count) = book count += 1 'Reset input fields and focus on the quantity txtName.Clear() txtCost.Clear() txtQuantity.Text = "" txtQuantity.Focus() End Sub Private Sub btnInventory_Click(...) Handles btnInventory.Click 'Display inventory of books Dim num As Integer = 0 Dim textb As Integer = 0 Dim cost As Double = 0 Dim value As Double = 0 'Aggregate totals For i As Integer = 0 To (count – 1) cost += books(i).Quantity * books(i).Cost value += books(i).Quantity * books(i).Price num += books(i).Quantity 'Count textbooks If TypeOf books(i) Is Textbook Then textb += books(i).Quantity End If Next 'Display totals lstInventory.Items.Clear() lstInventory.Items.Add("Total cost: " & cost.ToString("C")) lstInventory.Items.Add("Total value: " & value.ToString("C")) lstInventory.Items.Add("Number of books: " & num) lstInventory.Items.Add("Number of textbooks: " & textb) End Sub End Class 'frmBookstore
Instructor Solutions Manual (Page 181 of 196) MustInherit Class Book Public Property Name() As String Public Property Cost() As Double Public Property Quantity() As Integer 'Children must override this property MustOverride ReadOnly Property Price() As Double End Class 'Book Class Tradebook Inherits Book Overrides ReadOnly Property Price() As Double Get Return 1.4 * Cost '40% markup End Get End Property End Class 'Tradebook Class Textbook Inherits Book Overrides ReadOnly Property Price() As Double Get Return 1.2 * Cost '20% markup End Get End Property End Class 'Textbook
Instructor Solutions Manual (Page 182 of 196) 22. Public Class frmPayroll 'Holds the employee data and number of hours worked Structure Payroll Dim Employee As Employee 'Employee object Dim Hours As Double 'Hours worked during the week End Structure Dim pay(10) As Payroll Dim count As Integer
'Holds payroll records 'Last recorded employee
Private Sub btnRecord_Click(...) Handles btnRecord.Click 'Record an employee into the payroll Dim employee As Employee 'Determine employee type If radSalaried.Checked Then employee = New Salaried() Else employee = New Hourly() End If 'Store the data into the object employee.Name = txtName.Text employee.Rate = CDbl(txtRate.Text) 'Store the employee and hours into the structure array pay(count).Employee = employee pay(count).Hours = CDbl(txtHours.Text) count += 1 'Clear the input and set focus to name for the next employee txtName.Clear() txtRate.Clear() txtHours.Clear() txtName.Focus() End Sub Private Sub btnPayroll_Click(...) Handles btnPayroll.Click 'Display the statistics Dim hrs As Double 'Aggregate totals Dim sal As Integer = 0 Dim payroll As Double = 0 For i As Integer = 0 To (count – 1) If TypeOf pay(i).Employee Is Salaried Then sal += 1 End If payroll += pay(i).Employee.GrossPay(pay(i).Hours) hrs += pay(i).Hours Next lstPayroll.Items.Clear() lstPayroll.Items.Add("Number of employees: " & CStr(count)) lstPayroll.Items.Add("Salaried employees: " & CStr(sal)) lstPayroll.Items.Add("Total payroll: " & payroll.ToString("C")) lstPayroll.Items.Add("Average hours worked: " & (hrs / count).ToString("N1")) End Sub End Class 'frmPayroll
Instructor Solutions Manual (Page 183 of 196) Public MustInherit Class Employee Public Property Name() As String Public Property Rate() As Double 'Children must override this function to return gross pay MustOverride Function GrossPay(hours As Double) As Double End Class 'Employee Class Salaried Inherits Employee Overrides Function GrossPay(hours As Double) As Double 'Disregard hours worked; pay is simply the weekly salary Return Rate End Function End Class 'Salaried Class Hourly Inherits Employee Overrides Function GrossPay(hours As Double) As Double 'Multiply hours worked by rate Return hours * Rate End Function End Class 'Hourly
Instructor Solutions Manual (Page 184 of 196) CHAPTER 11 PROGRAMMING PROJECTS 1. Public Class frmBank 'Create checking and savings accounts. Dim WithEvents checking As New Account("Checking") Dim WithEvents savings As New Account("Savings") Dim check As Boolean 'True if current mode is Checking Dim committed As Boolean 'True if transaction was committed Dim curDate As Date 'Current date Structure Trans Dim dt As Date Dim nom As String Dim newBal As Double Dim amt As Double Dim cred As Boolean End Structure Dim sav() As Trans Dim chk() As Trans Private Sub frmBank_Load(...) Handles MyBase.Load 'Setup user interface for Checking. 'Load the transactions from the data files. checking.Load() savings.Load() 'Select checking account as account to transfer from. cboTransfer.SelectedIndex = 0 'Select checking account as the first account to see. cboAccount.SelectedIndex = 0 txtDate.Text = CStr(Today) 'Today's date UpdateGrid() End Sub Sub UpdateGrid() Dim temp() As String If cboAccount.SelectedIndex = 0 Then temp = IO.File.ReadAllLines("Checking.txt") Else temp = IO.File.ReadAllLines("Savings.txt") End If Dim n = temp.Count - 1 Dim data() As String ReDim sav(n) For i As Integer = 0 To n Dim preBal As Double = 0 data = temp(i).Split(","c) sav(i).dt = CDate(data(0)) sav(i).nom = data(1) sav(i).amt = CDbl(data(2)) If i = 0 Then preBal = 0 Else preBal = sav(i - 1).newBal End If
Instructor Solutions Manual (Page 185 of 196) If CBool(data(3)) Then sav(i).newBal = preBal + sav(i).amt Else sav(i).newBal = preBal - sav(i).amt End If Next Dim query = From s In sav Let amt = (s.amt).ToString("C") Let newBal = (s.newBal).ToString("C") Select s.dt, s.nom, amt, newBal dgvTransactions.DataSource = query.ToList dgvTransactions.CurrentCell = Nothing dgvTransactions.Columns("dt").HeaderText = "Date" dgvTransactions.Columns("nom").HeaderText = "Type of Transaction" dgvTransactions.Columns("amt").HeaderText = "Amount" dgvTransactions.Columns("newBal").HeaderText = "New Balance" End Sub Sub Insufficient(over As Double) Handles _ checking.Insufficient, savings.Insufficient 'If insufficient funds, set the committed flag to false and display message committed = False MessageBox.Show("Insufficient Funds: " & over.ToString("C"), "Insufficient Funds") End Sub Sub TransactionCommitted() Handles checking.TransactionCommitted, savings.TransactionCommitted 'If transaction committed, set the committed flag to True committed = True End Sub Private Sub cboAccount_SelectedIndexChanged(...) Handles _ cboAccount.SelectedIndexChanged 'Show the check group box if checking is enabled check = (cboAccount.SelectedIndex = 0) grpCheck.Visible = check Display() 'Display the transactions for the account UpdateGrid() End Sub Sub Display() 'Display the transactions belonging to the account If check Then 'Display the transactions in the lstTransactions list box 'checking.EnumerateTransactions(lstTransactions) 'Display the balance in the text box txtBalance.Text = (checking.Balance).ToString("C") Else 'Display the transactions in the lstTransactions list box 'savings.EnumerateTransactions(lstTransactions) 'Display the balance in the text box txtBalance.Text = (savings.Balance).ToString("C") End If UpdateGrid() End Sub
Instructor Solutions Manual (Page 186 of 196) Private Sub btnDeposit_Click(...) Handles btnDeposit.Click 'Deposit an amount into an account Dim trans As Transaction 'Create new deposit transaction curDate = CDate(txtDate.Text) trans = New Transaction(curDate, "Deposit", CDbl(txtDeposit.Text), True) 'Store transaction and update display If check Then checking.Add(trans) Dim sw As IO.StreamWriter = IO.File.AppendText("CHECKING.TXT") sw.WriteLine(trans.Format) sw.Close() Else savings.Add(trans) Dim sw As IO.StreamWriter = IO.File.AppendText("SAVINGS.TXT") sw.WriteLine(trans.Format) sw.Close() End If 'Display new transaction Display() txtDeposit.Clear() End Sub Private Sub btnWithdrawal_Click(...) Handles btnWithdrawal.Click 'Withdrawal an amount from an account Dim trans As Transaction 'Create new deposit transaction curDate = CDate(txtDate.Text) trans = New Transaction(curDate, "Withdrawal", CDbl(txtWithdrawal.Text), False) 'Store transaction and update display If check Then checking.Add(trans) If committed Then Dim sw As IO.StreamWriter = IO.File.AppendText("CHECKING.TXT") sw.WriteLine(trans.Format) sw.Close() End If Else savings.Add(trans) If committed Then Dim sw As IO.StreamWriter = IO.File.AppendText("SAVINGS.TXT") sw.WriteLine(trans.Format) sw.Close() End If End If 'Display new transaction Display() txtWithdrawal.Clear() End Sub Private Sub btnCheck_Click(...) Handles btnCheck.Click 'Withdrawal an amount from an account. Dim trans As Transaction 'Create new deposit transaction curDate = CDate(txtDate.Text) trans = New Transaction(curDate, "Check cashed by " & txtCheckTo.Text,
Instructor Solutions Manual (Page 187 of 196) CDbl(txtCheck.Text), False) 'Store transaction, and update display. checking.Add(trans) If committed Then Dim sw As IO.StreamWriter = IO.File.AppendText("CHECKING.TXT") sw.WriteLine(trans.Format) sw.Close() End If Display() txtCheck.Clear() txtCheckTo.Clear() End Sub Private Sub cboTransfer_SelectedIndexChanged(...) Handles _ cboTransfer.SelectedIndexChanged 'Display the proper account label caption. If cboTransfer.SelectedIndex = 0 Then lblTransferTo.Text = "to Savings" Else lblTransferTo.Text = "to Checking" End If End Sub Private Sub btnTransfer_Click(...) Handles btnTransfer.Click 'Transfer money from one account to the other. Dim trans As Transaction Dim amount As Double = CDbl(txtTransfer.Text) curDate = CDate(txtDate.Text) 'Create new withdrawal transaction. committed = True If cboTransfer.SelectedIndex = 0 Then 'Store transaction from checking account. trans = New Transaction(curDate, "Transfer to Savings", amount, False) checking.Add(trans) If committed Then Dim sw As IO.StreamWriter = IO.File.AppendText("Checking.txt") sw.WriteLine(trans.Format) sw.Close() End If Else 'Store transaction from savings account. trans = New Transaction(curDate, "Transfer to Checking", amount, False) savings.Add(trans) If committed Then Dim sw As IO.StreamWriter = IO.File.AppendText("Savings.txt") sw.WriteLine(trans.Format) sw.Close() End If End If 'Deposit to other account only if last transaction was committed. If committed Then If cboTransfer.SelectedIndex = 0 Then 'Store transaction to savings trans = New Transaction(curDate, "Transfer from Checking", amount, True) savings.Add(trans) Dim sw As IO.StreamWriter = IO.File.AppendText("Savings.txt")
Instructor Solutions Manual (Page 188 of 196) sw.WriteLine(trans.Format) sw.Close() Else 'Store transaction to checking account. trans = New Transaction(curDate, "Transfer from Savings", amount, True) checking.Add(trans) Dim sw As IO.StreamWriter = IO.File.AppendText("Checking.txt") sw.WriteLine(trans.Format) sw.Close() End If 'Display transactions. Display() txtTransfer.Clear() End If End Sub End Class 'frmBank Class Transaction Private m_name As String Private m_amount As Double Private m_date As Date Private m_credit As Boolean Public ReadOnly Property Name() As String Get Return m_name End Get End Property Public ReadOnly Property Amount() As Double Get Return m_amount End Get End Property Public ReadOnly Property TransDate() As Date Get Return m_date End Get End Property Public ReadOnly Property Credit() As Boolean Get Return m_credit End Get End Property Public Sub New(dt As Date, nm As String, amt As Double, cred As Boolean) 'Create new transaction object. 'Store parameters into member variables. m_name = nm m_amount = amt m_credit = cred m_date = dt End Sub
Instructor Solutions Manual (Page 189 of 196) Function Format() As String 'Put information into the proper form for insertion 'into one of the two text files Return CStr(TransDate) & "," & Name & "," & CStr(Amount) & "," & CStr(Credit) End Function End Class 'Transaction Class Account Dim trans(50) As Transaction Dim lastNum As Integer Private m_name As String Private m_balance As Double
'Holds the transactions 'Last transaction stored 'Name of the account 'Current balance
Public ReadOnly Property Name() As String Get Return m_name End Get End Property Public ReadOnly Property Balance() As Double Get Return m_balance End Get End Property 'Insufficient event is raised when a withdrawal is more than the balance. Public Event Insufficient(over As Double) Public Event TransactionCommitted() Public Sub New(name As String) 'Store the name m_name = name End Sub Sub Add(transaction As Transaction) 'Add a transaction to the account. Dim newBalance As Double 'Calculate new balance. If transaction.Credit Then newBalance = Balance + transaction.Amount Else newBalance = Balance - transaction.Amount End If 'If new balance is negative, then raise the insufficient event. If newBalance < 0 Then RaiseEvent Insufficient(newBalance) Else lastNum += 1 'Ensure there is space to store the transaction within the array. If (trans.Count – 1) <= lastNum Then ReDim Preserve trans(lastNum + 5) End If 'Store the tranasction, new balance, and raise the committed event. trans(lastNum) = transaction m_balance = newBalance RaiseEvent TransactionCommitted() End If End Sub
Instructor Solutions Manual (Page 190 of 196)
Sub Load() 'Load the data from a comma separated value (CSV) text file Dim fileName As String = m_name & ".TXT" Dim sr As IO.StreamReader Dim data() As String 'Array to receive values of Split function. Dim trans As Transaction 'Only load account if file exists If IO.File.Exists(fileName) Then sr = IO.File.OpenText(fileName) 'Loop through all lines of the file While Not sr.EndOfStream 'Split the line of data on commas into the string array data(). data = sr.ReadLine.Split(","c) 'Add the transaction to the account. trans = New Transaction(CDate(data(0)), data(1), CDbl(data(2)), CBool(data(3))) Add(trans) End While sr.Close() End If End Sub End Class 'Account
Instructor Solutions Manual (Page 191 of 196) 2. Public Class frmBlackJack Dim player, dealer As Hand 'The two hands Dim WithEvents deck As DeckOfCards 'The deck of cards Private Sub frmBlackJack_Load(...) Handles MyBase.Load 'Instantiate hands and deck. player = New Hand() dealer = New Hand() deck = New DeckOfCards() 'Deal the first hand NewHand() txtOutput.Clear() End Sub Private Sub btnNewHand_Click(...) Handles btnNewHand.Click 'Only deal a new hand if the hand is not finished If dealer.LastStored <> 1 Then NewHand() End If End Sub Private Sub btnHold_Click(...) Handles btnHold.Click 'Only stay if not stayed before and player has not busted yet If (player.Score <= 21) And (dealer.LastStored = 1) Then Hold() End If End Sub Private Sub btnHit_Click(...) Handles btnHit.Click 'Only hit if player has less than 5 cards, has not yet bust and not held If (player.LastStored < 5) And (player.Score < 21) And (dealer.LastStored = 1) Then Deal_Player() End If 'If reached 5 cards or busted then the player must hold If (player.LastStored = 5) Or (player.Score > 21) Then Hold() End If End Sub Sub NewHand() 'Reset hands and result. player.Clear() dealer.Clear() lstPlayer.Items.Clear() lstDealer.Items.Clear() txtPlayer.Clear() txtDealer.Clear() txtOutput.Clear() 'Shuffle the deck. deck.ShuffleDeck() 'Deal one card to dealer and two cards to player Deal_Dealer() Deal_Player() Deal_Player() End Sub
Instructor Solutions Manual (Page 192 of 196) Sub Deal_Player() 'Deal one card to player. Dim card As Card card = deck.Deal() player.Deal(card) 'Display card and score in appropriate list boxes lstPlayer.Items.Add(card.IdentifyCard) txtPlayer.Text = CStr(player.Score) End Sub Sub Deal_Dealer() 'Deal one card to dealer. Dim card As Card card = deck.Deal() dealer.Deal(card) 'Display card and score in appropriate list boxes lstDealer.Items.Add(card.IdentifyCard) txtDealer.Text = CStr(dealer.Score) End Sub Sub Hold() 'Deal one card to dealer until number reaches 5 or score reaches 17. 'If player has busted, then just deal one more card. Do Deal_Dealer() Loop Until (player.Score > 21) Or (dealer.LastStored = 5) Or (dealer.Score > 16) 'Display the result of the hands. txtOutput.Text = Result() End Sub Function Result() As String 'Determines the result of the hands 'If player or dealer busted If player.Score > 21 Then Return "You Busted - Dealer Wins" End If If dealer.Score > 21 Then Return "Dealer Busted - You win" End If If player.LastStored = 5 Then If dealer.LastStored = 5 Then Return "Both hands reached 5 - Push" End If Return "Hand reached 5 - You win" End If If dealer.LastStored = 5 Then Return "Dealer hand reached 5 - Dealer Wins" End If 'Compare scores Select Case player.Score Case Is > dealer.Score Return "You win" Case dealer.Score Return "Push" Case Else Return "Dealer wins" End Select End Function
Instructor Solutions Manual (Page 193 of 196) Private Sub cards_Shuffling(n As Integer, nMax As Integer) Handles deck.Shuffling 'n is the number of the specific pass through the deck (1, 2, 3...). 'nMax is the total number of passes when the deck is shuffled. txtOutput.Text = "Shuffling Pass: " & n & " out of " & nMax For i As Integer = 1 To 1000000 'Slow down the shuffle. Next txtOutput.Update() 'Refresh contents of text box End Sub End Class 'frmBlackJack Class Hand Private cards(5) As Card Private m_lastStored As Integer
'Maximum of 5 cards in a hand 'Location of last stored card
Public ReadOnly Property LastStored() As Integer Get Return m_lastStored End Get End Property Public ReadOnly Property Card(i As Integer) As Card Get Return cards(i) End Get End Property Public ReadOnly Property Score() As Integer Get Dim total As Integer Dim Ace As Boolean = False 'Add up all of the cards' scores in the hand. For i As Integer = 1 To m_lastStored 'Remember if there was an ace. total += cards(i).Score If cards(i).Denomination = 1 Then Ace = True End If Next 'If ace in the hand and less than 12, then ace counts 11. If (total < 12) And Ace Then total += 10 End If Return total End Get End Property Sub Deal(card As Card) 'Add the card to the hand. If m_lastStored < 5 Then 'Increment counter, and store card in array. m_lastStored += 1 cards(m_lastStored) = card End If End Sub
Instructor Solutions Manual (Page 194 of 196) Sub Clear() 'Removeall cards from hand. m_lastStored = 0 End Sub End Class 'Hand Class Card Private m_Denomination As Integer Private m_Suit As String
'A number from 1 through 13 'Hearts, Clubs, Diamonds, Spades
Public Property Denomination() As Integer Get Return m_Denomination End Get Set(Value As Integer) 'Only store valid values. If (Value >= 1) And (Value <= 13) Then m_Denomination = Value End If End Set End Property Public ReadOnly Property Score() As Integer Get 'Jack, Queen and King count 10. If m_Denomination > 10 Then Return 10 Else Return m_Denomination End If End Get End Property Public Property Suit() As String Get Return m_Suit End Get Set(Value As String) 'Only store valid values If (Value = "Hearts") Or (Value = "Clubs") Or (Value = "Diamonds") Or (Value = "Spades") Then m_Suit = Value End If End Set End Property
Instructor Solutions Manual (Page 195 of 196) Function IdentifyCard() As String Dim Denom As String = "" Select Case m_Denomination Case 1 Denom = "Ace" Case Is <= 10 Denom = CStr(m_Denomination) Case 11 Denom = "Jack" Case 12 Denom = "Queen" Case 13 Denom = "King" End Select Return Denom & " of " & m_Suit End Function End Class 'Card Class DeckOfCards Private m_deck(52) As Card 'Deck of 52 Cards Private m_dealt As Integer 'Last card dealt (1, 2, ..., 52) 'Shuffling event contains the current pass and total number of passes Public Event Shuffling(n As Integer, nMax As Integer) Public Sub New() 'Make the first thirteen cards hearts, the 'next thirteen cards diamonds, and so on. Dim suits() As String = {"Hearts", "Diamonds", "Clubs", "Spades"} For i As Integer = 0 To 3 For j As Integer = 1 To 13 'Assign numbers from 1 through 13 to the 'cards of each suit. m_deck(i * 13 + j) = New Card() m_deck(i * 13 + j).Suit = suits(i) m_deck(i * 13 + j).Denomination = j Next Next End Sub Function Deal() As Card 'Increment counter, cycling to one. If m_dealt < 52 Then m_dealt += 1 Else m_dealt = 1 End If Return m_deck(m_dealt) End Function Sub Swap(i As Integer, j As Integer) 'Swap the ith and jth card in the deck Dim tempCard As Card tempCard = m_deck(i) m_deck(i) = m_deck(j) m_deck(j) = tempCard End Sub
Instructor Solutions Manual (Page 196 of 196) Sub ShuffleDeck() 'Do 2000 passes through the deck. On each pass, 'swap each card with a randomly selected card. Dim index As Integer Dim randomNum As New Random() For i As Integer = 1 To 2000 For k As Integer = 1 To 52 index = randomNum.Next(1, 53) 'Randomly select a number ' from 1 through 52 inclusive Swap(k, index) Next 'Raise the shuffling event to track the progress of the shuffle. RaiseEvent Shuffling(i, 2000) Next End Sub End Class 'DeckOfCards
Get complete Order files download link below htps://www.mediafire.com/file/�351cwx7zi5x55/SM+ An+Introduc�on+to+Programming+Using+Visual+Basic +2012,+9e+David+Schneider.zip/file
If this link does not work with a click, then copy the complete Download link and paste link in internet explorer/firefox/google chrome and get all files download successfully.