Skip to main content

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

Page 1

Instructor Solutions Manual (Page 4 of 221)

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


Instructor Solutions Manual (Page 5 of 221)

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

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


Instructor Solutions Manual (Page 6 of 221)

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


Instructor Solutions Manual (Page 7 of 221)

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


Instructor Solutions Manual (Page 8 of 221)

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


Instructor Solutions Manual (Page 9 of 221)

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

34. 0

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


Instructor Solutions Manual (Page 10 of 221)

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


Instructor Solutions Manual (Page 11 of 221)

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


Instructor Solutions Manual (Page 12 of 221)

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

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

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

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

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


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


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


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


Instructor Solutions Manual (Page 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


Turn static files into dynamic content formats.

Create a flipbook