KEMBAR78
SSM Visual Basic | PDF | Button (Computing) | Window (Computing)
0% found this document useful (0 votes)
4 views193 pages

SSM Visual Basic

Uploaded by

rodman823
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views193 pages

SSM Visual Basic

Uploaded by

rodman823
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 193

Student Solutions Manual (Page 1 of 193)

STUDENT
SOLUTIONS
MANUAL
to accompany
An Introduction to Programming
Using VISUAL BASIC, 11th Edition

by David I. Schneider
Student Solutions Manual (Page 2 of 193)

Copyright © 2020 by Pearson Higher Education. All rights reserved.

“Visual Studio 2017 Community Edition” can be installed on PCs running Windows 7
(along with SP 1), Windows 8, or Windows10. It can be downloaded free of charge from
the website

https://docs.microsoft.com/en-us/visualstudio/install/install-visual-studio?view=vs-2017
Student Solutions Manual (Page 3 of 193)

CONTENTS
Chapter Comments 5

Chapter 2 Visual Basic Controls and Events


Exercises 2.2 Visual Basic Controls 9
Exercises 2.3 Visual Basic Events 12

Chapter 3 Variables, Input, and Output


Exercises 3.1 Numbers 15
Exercises 3.2 Strings 18
Exercises 3.3 Input and Output 23

Chapter 4 Decisions
Exercises 4.1 Relational and Logical Operators 27
Exercises 4.2 If Blocks 27
Exercises 4.3 Select Case Blocks 36
Exercises 4.4 Input via User Selection 41

Chapter 5 General Procedures


Exercises 5.1 Function Procedures 48
Exercises 5.2 Sub Procedures, Part I 53
Exercises 5.3 Sub Procedures, Part II 57

Chapter 6 Repetition
Exercises 6.1 Do Loops 61
Exercises 6.2 For…Next Loops 65
Exercises 6.3 List Boxes and Loops 73

Chapter 7 Arrays
Exercises 7.1 Creating and Using Arrays 81
Exercises 7.2 Using LINQ with Arrays 89
Exercises 7.3 Arrays of Structures 94
Exercises 7.4 Two-Dimensional Arrays 107

Chapter 8 Text Files


Exercises 8.1 Managing Text Files 114
Exercises 8.2 StreamReaders, StreamWriters, Structured Exception Handling 119
Exercises 8.3 XML 125
Student Solutions Manual (Page 4 of 193)

Chapter 9 Additional Controls and Objects


Exercises 9.1 List Boxes and Combo Boxes 130
Exercises 9.2 Eight Additional Controls and Objects 133
Exercises 9.3 Multiple-Form Programs 139
Exercises 9.4 Graphics 147

Chapter 10 Databases
Exercises 10.1 An Introduction to Databases 156
Exercises 10.2 Editing and Designing Databases 166

Chapter 11 Object-Oriented Programming


Exercises 11.1 Classes and Objects 167
Exercises 11.2 Working with Objects 174
Exercises 11.3 Inheritance 187
Student Solutions Manual (Page 5 of 193)

Chapter Comments

Chapter 1
1. Your instructor might skip this chapter. If so, we recommend that you take a quick look at a few items
from the chapter. Look at the last question and answer on page 3 to see how the appearance of a
program varies with the version of Windows being used. Also, look at the four questions and answers
on page 5. We especially recommend that you configure Windows to display file extensions as advised
in the second answer on page 5.

Chapter 2
1. On page 43 you are asked to run a program that was downloaded from the Pearson website for the
book. All of the programs appearing in Examples and Case Studies can be downloaded from that
website. There is never any need for you to manually type in the code for a program in this textbook.
The website also contains all the text files, xml files, databases, and picture files needed for the
exercises.
These files are contained in the folders “Ch02”, “Ch03”, “Ch04”, and so on. Each chapter file
contains a subfolder named “Text_Files_for_Exercises” which contains the text and xml files needed
for that chapter’s exercises. The folder “Ch09” has a subfolder named “Pictures” that contains picture
files. The folder “Ch10” has a subfolder named “Databases” containing all the databases needed for
the exercises.
Each program is contained in a folder with a name of the form chapter–section–example
number. For instance, the program in Chapter 3, Section 1, Example 2 is contained in the folder “3-1-
2”. Many of the programs make use of a text file contained in the subfolder Debug of the program’s
bin subfolder.
2. On page 43, we explain our use of ellipses (...) as place holders for the phrase "sender As Object,
e As EventArgs". A program will not run when the phrase is replaced with an ellipsis. However, a
program will run if the phrase is simply deleted. Therefore, if you use Ctrl+C to copy code from this
Student Solutions Manual and paste it into your own program, the code will execute after you delete
the ellipses.

Chapter 3
1. Figure 3.13 on page 75 shows the settings for Options Explicit, Strict, and Infer set to On. Most
instructors will recommend that the first two Options be set to On. Option Infer, on the other hand, is
debatable. If you want to learn more about the effect of Option Infer, take a quick look at the
discussion of local type inference on pages 262-263.
2. On page 81 we discuss line continuation. Before Visual Basic 2010, the underscore character was
needed to continue a statement onto another line. Beginning with VB2010, the underscore character
can be omitted for a line that obviously has a continuation (such as, when the line ends with a comma
or an arithmetic operator) and therefore will seldom be needed in the programs you write.
3. DateDiff(DateInterval.Year, d1, d2) gives the number of years (sort of) between the
two dates. It must be employed with care since it only uses the year parts of the two
dates.
4. The topic “Formatting Output with Zones” was added at the request of some instructors. It can be
used as an alternate way to display output in some of the exercises. However, we do use it in the
book.
Student Solutions Manual (Page 6 of 193)

Chapter 4
1. Section 4.1 is unusual in that you will only be asked to write one program in the exercise set.
However, the concepts presented in this section are fundamental to the rest of the textbook.
2. In Section 4.2 we discuss short-circuit evaluation with AndAlso and OrElse. They are superior to And
and Or when evaluating cond2 is very time consuming. Since that is seldom the case in this book, we
almost exclusively use And and Or to improve readability.
3. In Chapter 3 we used list boxes to display data. In Section 4.4, we show how list boxes can be used to
make selections. Another control used to make a selection from a list, the combo box, is discussed in
Chapter 9.

Chapter 5
1. In this book, Function procedures appear in many more programs than Sub procedures. The use of
Sub procedures is part of good programming practice, but is not essential. Any computer program can
be written without Sub procedures. However, there are many programs in this textbook that would be
very difficult to write without Function procedures.
2. The above comment is not intended to diminish the importance of Sub procedures. They are a
fundamental component of good program design. However, if you find Sub procedures somewhat
confusing at first, don't worry. You will still be able to work the exercises. You will eventually become
comfortable with Sub procedures after seeing them used in subsequent chapters.

Chapter 6
1. There are two types of loops presented in this chapter—Do loops and For...Next loops. A third type of
loop, called a For Each loop, is presented in Section 7.1.
2. Loops have traditionally been used to process lists of data. For instance, loops can be used with a list
of numbers to compute the sum of the numbers, the average of the numbers, the largest number in
the list and the smallest number in the list. The algorithms for calculating sums and averages are
obvious. In Example 3 of Section 6.3, the maximum value of the numbers in a list box is calculated
with the following algorithm:
(a) Declare a variable named max.
(b) Assign a value to the variable that is guaranteed to be less than or equal to the maximum value in
the list. One possibility is to set the value of max equal to the first number in the list. Another
possibility requires some knowledge of the numbers in the list. For instance, if the numbers are all
grades on an exam, the initial value of max can be set to 0.
(c) Use a loop to examine the numbers one at a time. Whenever a number is greater than the current
value of max, change the value of max to be that number. After the loop has executed, the value of
max will be the largest number in the list.
Exercise 35 of Section 6.3 uses an analogous algorithm to find the smallest number in the list box.
These two algorithms appear several times in the textbook in both examples and exercises.
3. Section 6.3 presents techniques for processing lists of data with loops. In Section 7.2, a method for
examining lists without using loops is presented.
Student Solutions Manual (Page 7 of 193)

Chapter 7
1. A very important idea to take away from Section 7.1 is that there are four ways to fill an array. Let's
illustrate the ways by filling an array with the names of the first three U.S. presidents.
(a) Dim pres() As String = {"Washington", "Jefferson", "Adams}
(b) Dim pres() As String = IO.File.ReadAllLines("Pres.txt"), where the text file
Pres.txt is located in the program's bin\Debug folder and contains three lines (each containing
the name of a president).
(c) Dim strVar As String = "Washington,Jefferson,Adams"
Dim pres() As String = strVar.Split(","c)
(d) Dim pres(2) As String
pres(0) = "Washington"
pres(1) = "Jefferson"
pres(2) = "Adams"
In the first three ways, the array is declared and sized automatically at the same time it is filled. The
second and third ways will be the most used in this book.
2. Section 7.3 is perhaps the most challenging section in the book. However, the techniques presented in
this section are very powerful and are heavily used later in the book with text files and databases.
The techniques also are presented in Section 8.1 in a slightly different form. Some instructors will
skip Section 7.3 and rely solely on Section 8.1. Important: When using a DataGridView control,
always set the RowHeadersVisible property to False and the AutoSizeColumnsMode property to Fill.
3. Some important text files used in this chapter are the following:
a. Baseball.txt: contains statistics for the top 139 hitters on major league teams who had at least 430
at bats in the 2018 regular season.
b. Justices.txt: contains all people who served on the U.S. Supreme Court prior to January 2019.
c. SBWinners.txt: contains all Super Bowl winners up to and including 2018.

Chapter 8
1. The first two sections in this chapter are independent of each other.
2. The preliminaries section at the beginning of Section 8.1 can be omitted if you covered Section 7.3.
The techniques presented in the preliminaries will take a fair amount of effort to master. However,
the payoff will be substantial.
3. Section 8.1 shows some modern techniques for combining lists of data. In earlier versions of Visual
Basic, these tasks could only be carried out with complicated algorithms involving loops.
4. Some important data files used in this chapter are as follows:
a. Baseball.xml: : contains statistics the top 139 hitters on major league teams who had at least 430 at
bats in the 2018 regular season
b. Justices.txt: contains all people who served on the U.S. Supreme Court prior to January 2019.
c. Senate116.txt: contains the composition of the U.S. Senate that was sworn in on January 3, 2019.
d. USPres.txt: contains the names of the first 45 U.S. presidents.
Student Solutions Manual (Page 8 of 193)

Chapter 9
1. Most of Chapter 9 is not needed in the remainder of the book. However, the chapter shows how to
use several tools that are familiar to you from major programs you have used.
2. Programs written by professional programmers often use more than one form. Section 9.3 shows how
this is done. However, since this is an introductory book, all programs outside of Section 9.3 use only
one form.

Chapter 10
1. The steps for binding a database to a program may look complicated at first. However, after you get
used to it you will find it simple to carry out. Also, when you work several exercises using the same
database, you can just bind the database once and write a different event procedure for each
exercise.
2. Some important databases used in this chapter are the following:
a. Baseball.accdb: contains statistics the top 139 hitters on major league teams who had at least 430
at bats during the 2018 regular season.
b. Justices.accdb: contains all people who served on the U.S. Supreme Court as of January 2013.
c. UN.accdb: contains the composition of the United Nations as of January 1, 2019.
d. Exchrate.accdb: contains currency exchange rates in October 2018.
Student Solutions Manual (Page 9 of 193)

CHAPTER 2

EXERCISES 2.2 Visual Basic Controls

1. While the mouse cursor is still hovering over the button that was just clicked, the button has a
pale blue color. After the cursor leaves the button, the button has a dark blue border.

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.

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 yellow text box.

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.

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 2017".
Select the Font property and click on the ellipsis to the right of the Settings box.
Scroll up the Font box, and click on Courier New in the Font box.
Click on the OK button.
Widen the text box to accommodate its text.

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 Oblique in the "Font style" list.
Click on 24 in the Size list.
Click on the OK button.
Resize the button.
Student Solutions Manual (Page 10 of 193)

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.

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 Oblique in the "Font style" list.
Click on the OK button.
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.

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.

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 Oblique in the "Font style" list, and click on the Underline box.
Click on the OK button.

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.

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, and click the No button in the box that appears.
Right-click on the form in the Form Designer, and click on Properties in 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.
Student Solutions Manual (Page 11 of 193)

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.

27. Begin a new program.


Change the text in the form's title bar to "Fill in 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".

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.

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

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.

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 two 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.

41. The label is positioned just to the left of the text box, and the middles of the two controls are
aligned.

43. Center refers to the midpoint horizontally, whereas middle refers to the midpoint vertically.

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
Student Solutions Manual (Page 12 of 193)

47. The setting is cycling through the different available colors.

EXERCISES 2.3 Visual Basic Events

1. The word Hello 3. The word Hello on an orange-colored background

5. The text box vanishes. 7. The word Hello in green letters

9. The word Hello on a gold background. 11. Form1.Text should be Me.Text.

13. Red should be replaced with Color.Red.

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.

17. lblTwo.Text = "E.T. phone home."

19. txtBox.ForeColor = Color.Red


txtBox.Text = "The stuff that dreams are made of."

21. txtBox.Enabled = False

23. lblTwo.Visible = False

25. btnOutcome.Enabled = True

27. txtBoxTwo.Focus()

29. The Enter event occurs when a control gets 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.

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
Student Solutions Manual (Page 13 of 193)

Private Sub btnRight_Click(...) Handles btnRight.Click


txtBox.Text = "Right Justify"
txtBox.TextAlign = HorizontalAlignment.Right
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

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

Private Sub txtTruth_Enter(...) Handles txtTruth.Enter


txtQuote.Text = "Tell the truth and run."
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
Student Solutions Manual (Page 14 of 193)

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

43. Private Sub btnAny_Click(...) Handles btnOne.Click, btnTwo.Click


txtOutput.Text = "You just clicked on a button."
End Sub
Student Solutions Manual (Page 15 of 193)

CHAPTER 3

EXERCISES 3.1 Numbers

1. 12 3. .125 5. 8 7. 2 9. 1 11. 3

13. Not valid 15. Valid 17. Not valid 19. 10 21. 16 23. 9

25. Private Sub btnCompute_Click(...) Handles btnCompute.Click


lstOutput.Items.Add((7 * 8) + 5)
End Sub

27. Private Sub btnCompute_Click(...) Handles btnCompute.Click


lstOutput.Items.Add(0.055 * 20)
End Sub

29. Private Sub btnCompute_Click(...) Handles btnCompute.Click


lstOutput.Items.Add(17 * (3 + 162))
End Sub

31.
x y
Private Sub btnEvaluate_Click(...) Handles btnEvaluate.Click
Dim x, y As Double 0 0
x = 2 2 0
y = 3 * x 2 6
x = y + 5 11 6
lstResults.Items.Clear() 11 6
lstResults.Items.Add(x + 4) 11 6
y = y + 1 11 7
End Sub

33. 6 35. 1 37. 1 39. 2


8 64 15
9

41. The third line should read c = a + b

43. The first assignment statement should not contain a comma. The second assignment
statement should not contain a dollar sign.

45. 9W is not a valid variable name. 47. Dim quantity As Integer = 12

49. 10 51. 6 53. 3.128 55. –3 57. 0 59. 6

61. cost += 5 63. cost /= 6 65. sum ^= 2

67. Private Sub btnCompute_Click(...) Handles btnCompute.Click


Dim revenue, costs, profit As Decimal
revenue = 98456
costs = 45000
profit = revenue - costs
lstOutput.Items.Add(profit)
End Sub
Student Solutions Manual (Page 16 of 193)

69. Private Sub btnCompute_Click(...) Handles btnCompute.Click


Dim price, discountPercent, markdown As Decimal
price = 19.95D
discountPercent = 30
markdown = (discountPercent / 100) * price
price = price - markdown
lstOutput.Items.Add(Math.Round(price, 2))
End Sub

71. Private Sub btnCompute_Click(...) Handles btnCompute.Click


Dim balance As Decimal
balance = 100
balance += 0.05D * balance
balance += 0.05D * balance
balance += 0.05D * balance
lstOutput.Items.Add(Math.Round(balance, 2))
End Sub

73. Private Sub btnCompute_Click(...) Handles btnCompute.Click


Dim purchasePrice As Decimal = 215.50D
Dim sellingPrice As Decimal = 644.99D
Dim markup As Decimal = sellingPrice - purchasePrice
Dim percentageMarkup As Decimal = 100 * (markup / purchasePrice)
lstOutput.Items.Add(percentageMarkup)
End Sub

75. 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

77. 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
Student Solutions Manual (Page 17 of 193)

79. Private Sub btnCompute_Click(...) Handles btnCompute.Click


Dim waterPerPersonPerDay, people, days, waterUsed As Double
waterPerPersonPerDay = 1600
people = 329000000
days = 365
waterUsed = waterPerPersonPerDay * people * days
lstOutput.Items.Add(waterUsed)
End Sub

81. 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

83. Private Sub btnConvert_Click(...) Handles btnConvert.Click


Dim conversionFactor As Double = 0.6214
Dim kilometersPerHr, milesPerHr As Double
kilometersPerHr = CDbl(txtSpeedKil.Text)
milesPerHr = conversionFactor * kilometersPerHr
txtSpeedMph.Text = milesPerHr.ToString("N")
End Sub

85. Private Sub btnEstimate_Click(...) Handles btnEstimate.Click


Dim cal As Double
cal = (5280 ^ 3) * 48600
lstCalories.Items.Add(cal)
End Sub
Student Solutions Manual (Page 18 of 193)

EXERCISES 3.2 Strings

1. Visual Basic 3. Ernie 5. flute 7. 123 9. Your age is 21.

11. A ROSE IS A ROSE IS A ROSE 13. 5.5 15. goodbye 17. WALLAWALLA

19. ABC 21. 12 23. 8 (0 through 7) 25. True


2 MUNICIPALITY
4 city
55 mph 6
STU

27. The variable phoneNumber should be declared as type String, not Double.

29. End is a keyword and cannot be used as a variable name.

31. The IndexOf method cannot be applied to a number, only a string.

33. 2 ^ 3 is a Double value and therefore cannot be assigned to the Decimal variable m. Also,
4 / 2 is a Double value and cannot be assigned to an Integer variable.

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


Dim firstName, middleName, lastName As String, yearOfBirth As Integer
firstName = "Thomas"
middleName = "Alva"
lastName = "Edison"
yearOfBirth = 1847
txtOutput.Text = firstName & " " & middleName & " " & lastName &
", " & yearOfBirth
End Sub

37. Dim str As String 'Place in the Declarations section of the program.

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
Student Solutions Manual (Page 19 of 193)

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

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

45. Private Sub btnCompute_Click(...) Handles btnCompute.Click


Dim revenue, expenses, income As Decimal
revenue = CDec(txtRevenue.Text)
expenses = CDec(txtExpenses.Text)
income = revenue - expenses
txtNetIncome.Text = CStr(income)
End Sub
Student Solutions Manual (Page 20 of 193)

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

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

51. Dim sum As Double 'sum of the scores entered


Dim num As Integer '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
Student Solutions Manual (Page 21 of 193)

53. Private Sub btnCompute_Click(...) Handles btnCompute.Click


Dim amount, percentage, tip As Decimal
amount = CDec(txtAmount.Text)
percentage = CDec(txtPercentage.Text)
tip = amount * (percentage / 100)
txtTip.Text = CStr(Math.Round(tip, 2))
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
Student Solutions Manual (Page 22 of 193)

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

59. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click


Dim futureValue, interestRate, presentValue As Decimal
Dim numYears As Integer
futureValue = CDec(txtFutureValue.Text)
interestRate = CDec(txtInterest.Text)
numYears = CInt(txtYears.Text)
presentValue = CDec(futureValue / (1 + interestRate / 100) ^ numYears)
txtPresentValue.Text = CStr(Math.Round(presentValue, 2))
End Sub
Student Solutions Manual (Page 23 of 193)

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 Input and Output

1. 1,235 3. 1,234.0

5. 0.0 7. -0.67 9. 12,346.000 11. 12 13. $12,346

15. ($0.23) 17. $0.80 19. $0.08 21. 100.00 %

23. 66.67 % 25. Pay to France $27,267,622.00

27. 25.6 % of the U.S. population 25+ years old are college graduates.

29. The likelihood of Heads is 50 % 31. 10/23/2021

33. Thursday, November 26, 2020 35. 10/2/2021 37. 4/5/2019

39. 29 41. 5 43. 1 45. 2022 47. You might win 360 dollars.

49. Hello John Jones 51. $106.00

53. 123456789012345678901234567890
Mountain Place Ht (ft)
K2 Kashmir 28,250

55. 12345678901234567890
Element Weight Percent
Oxygen 97.5 65.0 %
Carbon 27.0 18.0 %

57. The statement n += 1 is not valid since the value of a named constant cannot be changed.
59. The second line should use CDbl to convert the right-hand side to type Double.
61. (123456).ToString("N") is a string and therefore cannot be assigned to a numeric variable.
63. You must insert .Show after the word MessageBox.
65. 000 67. LLL000 69. 0-00-000000-&
71. MessageBox.Show("First solve the problem. Then write the code.",
"Good Advice")
Student Solutions Manual (Page 24 of 193)

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


'Inflation
Dim begOfYearCost, endOfYearCost As Decimal
Dim percentIncrease As Decimal
begOfYearCost = 200
endOfYearCost = CDec(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
75. Private Sub txtPhoneNumber_Enter(...) Handles txtPhoneNumber.Enter
'Reminder
MessageBox.Show("Be sure to include the area code!", "Reminder")
End Sub

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


'Length of year
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

79. Private Sub Determine_Click(...) Handles btnDetermine.Click


'Day of week
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
Student Solutions Manual (Page 25 of 193)

81. Private Sub btnConvert_Click(...) Handles btnConvert.Click


'Convert date formats
Dim dt As Date
dt = CDate(txtUS.Text)
txtEurope.Text = dt.Day & "/" & dt.Month & "/" & dt.Year
End Sub

83. Private Sub Determine_Click(...) Handles btnDetermine.Click


'Length of month
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

85. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click


'Change in salary
Dim begSalary, salary As Decimal
begSalary = CDec(txtBeginningSalary.Text)
salary = begSalary + (0.1D * begSalary)
salary = salary – (0.1D * salary)
txtNewSalary.Text = salary.ToString("C")
txtChange.Text = ((salary - begSalary) / begSalary).ToString("P")
End Sub
Student Solutions Manual (Page 26 of 193)

87. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click


'Taxi fare
Dim distance As Double
distance = CDbl(txtDistance.Text)
txtFare.Text = (0.8 + 0.2 * (Int(4 * distance))).ToString("C")
End Sub
Student Solutions Manual (Page 27 of 193)

CHAPTER 4

EXERCISES 4.1 Relational and Logical Operators

1. hi 3. The letter before G is F

5. "We're all in this alone." - Lily Tomlin

6. D is the 4th letter of the alphabet.

7. True 9. True 11. True 13. True 15. False 17. False

19. True 21. True 23. False 25. False 27. False 29. True

31. Equivalent 33. Not equivalent 35. Equivalent 37. Not equivalent

39. a <= b 41. (a >= b) Or (c = d)

43. (a = "") Or (a >= b) Or (a.Length >= 5)

[In Exercises 45 through 47, execute a statement of the form txtOutput.Text = CStr(Boolean
expression).]

45. True 47. True 49. False 51. False 53. True 55. True 57. False 59. True

61. Private Sub btnFind_Click(...) Handles btnFind.Click


'Find the position of a letter in the alphabet.
Dim letter As String, position As Integer
letter = txtLetter.Text.ToUpper
position = Asc(letter) - 64
txtPosition.Text = CStr(position)
End Sub

EXERCISES 4.2 If Blocks

1. Less than ten. 3. Your change contains 3 dollars.

5. To be, or not to be. 7. Hi 9. You are old enough to vote in 7 days.

11. Syntax error. Third line should be If ((1 < num) And (num < 3)) Then

13. Syntax error. Fourth line should be If ((major = "Business") Or (major = "Computer
Science")) Then
Student Solutions Manual (Page 28 of 193)

15. a = 5

17. 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

19. If IsNumeric(txtBox.Text) AndAlso (CDbl(txtBox.Text) < 0) Then


MessageBox.Show("negative")
End If

21. Private Sub btnCompute_Click(...) Handles btnCompute.Click


Dim cost, tip As Decimal
cost = CDec(txtAmount.Text)
tip = cost * 0.18D
If tip < 1 Then
tip = 1
End If
txtOutput.Text = tip.ToString("C")
End Sub

23. Private Sub btnCompute_Click(...) Handles btnCompute.Click


Dim num, cost As Decimal
num = CDec(txtNumber.Text)
If num < 100 Then
cost = 0.25D * num '25 cents each
Else
cost = 0.2D * num '20 cents each
End If
txtOutput.Text = cost.ToString("C")
End Sub
Student Solutions Manual (Page 29 of 193)

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

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
Student Solutions Manual (Page 30 of 193)

29. Private Sub btnCompute_Click(...) Handles btnCompute.Click


Dim weight, cost, amount, change As Decimal
weight = CDec(txtWeight.Text)
amount = CDec(txtAmount.Text)
cost = weight * 2.5D
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

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
Student Solutions Manual (Page 31 of 193)

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

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
Student Solutions Manual (Page 32 of 193)

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
Student Solutions Manual (Page 33 of 193)

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

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
Student Solutions Manual (Page 34 of 193)

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

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
Student Solutions Manual (Page 35 of 193)

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

49. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click


'Buy two, get one free sale
Dim cost1, cost2, cost3, minimumCost As Decimal
cost1 = CDec(txtCostOfItem1.Text)
cost2 = CDec(txtCostOfItem2.Text)
cost3 = CDec(txtCostOfItem3.Text)
minimumCost = cost1
If cost2 < minimumCost Then
minimumCost = cost2
End If
If cost3 < minimumCost Then
minimumCost = cost3
End If
txtTotalCost.Text = (cost1 + cost2 + cost3 –
minimumCost).ToString("C")
End Sub
Student Solutions Manual (Page 36 of 193)

51. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click


'Sort three numbers.
Dim max, min As Double
max = CDbl(txtNum1.Text)
If CDbl(txtNum2.Text) > max Then
max = CDbl(txtNum2.Text)
End If
If CDbl(txtNum3.Text) > max Then
max = CDbl(txtNum3.Text)
End If
txtMax.Text = CStr(max)
min = CDbl(txtNum1.Text)
If CDbl(txtNum2.Text) < min Then
min = CDbl(txtNum2.Text)
End If
If CDbl(txtNum3.Text) < min Then
min = CDbl(txtNum3.Text)
End If
txtMin.Text = CStr(min)
If (CDbl(txtNum1.Text) < max) AndAlso (CDbl(txtNum1.Text) > min) Then
txtMiddle.Text = txtNum1.Text
End If
If (CDbl(txtNum2.Text) < max) AndAlso (CDbl(txtNum2.Text) > min) Then
txtMiddle.Text = txtNum2.Text
End If
If (CDbl(txtNum3.Text) < max) AndAlso (CDbl(txtNum3.Text) > min) Then
txtMiddle.Text = txtNum3.Text
End If
End Sub

EXERCISES 4.3 Select Case Blocks

1. The price is $3.75 3. Mesozoic Era


The price is $3.75 Paleozoic Era
?

5. The equation has no real solutions.


The equation has two solutions.
The equation has exactly one solution.

7. Should have a Case clause before the 4th line.


Student Solutions Manual (Page 37 of 193)

9. Case nom = "Bob" should be Case "Bob"

11. Logic error: >= "Peach" should be >= "PEACH".


Syntax error: "ORANGE TO PEACH" should be "ORANGE" To "PEACH".

13. Valid 15. Invalid 17. Valid

19. Select Case a


Case 1
txtOutput.Text = "one"
Case Is > 5
txtOutput.Text = "two"
End Select

21. Select Case a


Case 2
txtOutput.Text = "maybe"
Case Is > 5
txtOutput.Text = "no"
End Select

23. Private Sub btnDescribe_Click(...) Handles btnDescribe.Click


Dim percent As Integer
percent = CInt(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
Student Solutions Manual (Page 38 of 193)

25. Private Sub btnCompute_Click(...) Handles btnCompute.Click


Dim shapeNum As Integer
Dim radius, length, height, width As Double
'Input choice of shape and its dimensions
'1. Circle 2. Parallelogram 3. Kite
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

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 = letterGrade
End Sub
Student Solutions Manual (Page 39 of 193)

29. Private Sub btnDescribe_Click(...) Handles btnDetermine.Click


Dim amountRecovered, payment As Decimal
amountRecovered = CDec(txtAmount.Text))
Select Case amountRecovered
Case Is <= 75000
payment = 0.1D * amountRecovered
Case Is <= 100000
payment = 7500 + 0.05D * (amountRecovered - 75000)
Case Is > 100000
payment = 8750 + 0.01D * (amountRecovered - 100000)
If payment > 50000 Then
payment = 50000
End If
End Select
txtOutput.Text = payment.ToString("C")
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
Student Solutions Manual (Page 40 of 193)

33. Private Sub btnEvaluate_Click(...) Handles btnEvaluate.Click


Dim amount, cost, costPerOzWithIncrease, costPerOzWithDiscount As Decimal
Dim betterOffer As String
amount = 18
cost = 9
costPerOzWithIncrease = cost / (1.5D * amount)
costPerOzWithDiscount = (0.65D * 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

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"
Student Solutions Manual (Page 41 of 193)

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

EXERCISES 4.4 Input via User Selection


1. The word "Income" becomes the caption embedded in the top of GroupBox1.
3. The CheckBox1 check box becomes (or remains) unchecked.
5. The radio button becomes (or remains) unselected.
7. The radio button’s caption becomes "Clear All" when the Alt key is pressed.
9. RadioButton1.Text = "Yes" 11. CheckBox1.Checked = True
13. RadioButton2 is on and RadioButton1 is off. 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 Decimal = 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")
Else
MessageBox.Show("You must first select a model!")
End If
End Sub
Student Solutions Manual (Page 42 of 193)

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
Student Solutions Manual (Page 43 of 193)

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

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
Student Solutions Manual (Page 44 of 193)

25. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click


Dim fee As Decimal = 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
Student Solutions Manual (Page 45 of 193)

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
Student Solutions Manual (Page 46 of 193)

29. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click


'Compound interest
Dim intRate As Decimal 'interest per period
Dim n As Integer 'number of interest periods
If (lstRates.SelectedIndex <> -1) AndAlso
(lstCompounding.SelectedIndex <> -1) Then
Select Case lstRates.Text
Case "2%"
intRate = 0.02D
Case "2.5%"
intRate = 0.025D
Case "3%"
intRate = 0.03D
Case "3.5%"
intRate = 0.035D
Case "4%"
intRate = 0.04D
End Select
Select Case lstCompounding.Text
Case "annually"
n = 1
Case "semi-annually"
n = 2
Case "quarterly"
n = 4
Case "monthly"
n = 12
Case "weekly"
n = 52
End Select
txtAmount.Text = (10000 * (1 + intRate / n) ^ (5 * n)).ToString("C")
Else
MessageBox.Show("You must select an item from each list box.")
End If
End Sub
Student Solutions Manual (Page 47 of 193)

31. Private Sub lstProperties_SelectedIndexChanged(...) Handles _


lstProperties.SelectedIndexChanged
'Railroad properties in Monopoly
If lstProperties.Text = "Short Line" Then
MessageBox.Show("Short Line is a bus company.", "Correct")
Else
MessageBox.Show("It is an actual railroad.", "Incorrect")
End If
End Sub
Student Solutions Manual (Page 48 of 193)

CHAPTER 5

EXERCISES 5.1 Function Procedures

1. 59 3. The population will double in 24 years. 5. 27 is an odd number.

7. Your state income tax is $150.00. 9. age before beauty

11. The function header should end with "As String", not "As Integer".

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

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
Student Solutions Manual (Page 49 of 193)

17. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click


Dim popcorn, butter, bucket, price As Decimal 'amount in dollars
popcorn = CDec(txtPopcorn.Text)
bucket = CDec(txtBucket.Text)
butter = CDec(txtButter.Text)
price = CDec(txtPrice.Text)
txtProfit.Text = (Profit(popcorn, butter, bucket, price)).ToString("C")
End Sub

Function Profit(popcorn As Decimal, butter As Decimal ,


bucket As Decimal, price As Decimal) As Decimal
'Calculate the profit on a bucket of popcorn
Return price - (popcorn + butter + bucket)
End Function
Student Solutions Manual (Page 50 of 193)

19. Private Sub btnCompute_Click(...) Handles btnCompute.Click


Dim weight As Double
weight = CDbl(txtWeight.Text)
txtOutput.Text = (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

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
Student Solutions Manual (Page 51 of 193)

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

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
Student Solutions Manual (Page 52 of 193)

27. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click


'College tuition
Dim resident As Boolean = False, undergraduate As Boolean = False
Dim numCredits As Integer
If IsNumeric(txtNumCredits.Text) Then
numCredits = CInt(txtNumCredits.Text)
If radYes.Checked Then
resident = True
End If
If radUndergraduate.Checked Then
undergraduate = True
End If
txtTuition.Text = (CalculateTuition(numCredits, resident,
undergraduate)).ToString("C")
Else
MessageBox.Show("You must enter the number of credits.", "Missing Input")
End If
End Sub

Function CalculateCostPerCredit(resident As Boolean,


undergraduate As Boolean) As Decimal
If resident Then
If undergraduate Then
Return 90
Else
Return 110
End If
Else
If undergraduate Then
Return 150
Else
Return 180
End If
End If
End Function
Function CalculateTuition(numCredits As Integer, resident As Boolean,
undergraduate As Boolean) As Decimal
Return numCredits * CalculateCostPerCredit(resident, undergraduate)
End Function
Student Solutions Manual (Page 53 of 193)

29. Function Embed(strVar1 As String, strVar2 As String, n As Integer) As String


If (n < 0) OrElse (n > strVar1.Length) Then
MessageBox.Show("Task cannot be completed.")
Exit Function
End If
Dim strVar3 As String = strVar1.Substring(0, n)
Dim strVar4 As String = strVar1.Substring(n)
Return strVar3 & strVar2 & strVar4
End Function

EXERCISES 5.2 Sub Procedures, Part I

1. 88 keys on a piano 3. You look dashing in blue. 5. 1440 minutes in a day

7. Why do clocks run clockwise?

Because they were invented in the northern 9. It was the best of times.
hemisphere where sundials go clockwise. It was the worst of times.

11. divorced 13. 24 blackbirds 15. The first 6 letters are Visual.
beheaded baked in
died a pie.
divorced
beheaded
survived

17. Cost: $250.00 19. You passed with a grade of 92.


Shipping cost: $15.00
Total cost: $265.00

21. There is a parameter in the Sub procedure, but no argument in the statement calling the Sub
procedure.

23. Since Handles is a keyword, it cannot be used as the name of a Sub procedure.

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

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
Student Solutions Manual (Page 54 of 193)

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


DisplayHeader()
Majors(0.138, "business")
Majors(0.0370, "computer science")
End Sub

Sub DisplayHeader()
Dim phrase As String
phrase = "Intended majors of freshmen in 2016:"
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

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
Student Solutions Manual (Page 55 of 193)

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
Student Solutions Manual (Page 56 of 193)

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
Student Solutions Manual (Page 57 of 193)

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

39. Sub ShowCentury(anyDate As Date)


If anyDate >= Today Then
MessageBox.Show("You did not enter a past date.")
Exit Sub
End If
Select Case anyDate
Case Is >= #1/1/2000#
txtOutput.Text = "twenty-first century"
Case Is >= #1/1/1900#
txtOutput.Text = "twentieth century"
Case Else
txtOutput.Text = "prior to the twentieth century"
End Select
End Sub

EXERCISES 5.3 Sub Procedures, Part II

1. Gabriel was born in the year 1980.

3. The state flower of Alaska is the Forget Me Not.

5. The first 3 letters of EDUCATION are EDU.

7. sum = 4
difference = 2
Student Solutions Manual (Page 58 of 193)

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


Dim firstName As String = ""
Dim lastName As String = ""
Dim salary, newSalary As Decimal
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 Decimal)
firstName = txtFirstName.Text
lastName = txtLastName.Text
salary = CDec(txtCurrentSalary.Text)
End Sub

Function RaisedSalary(salary As Decimal) As Decimal


If salary <= 40000 Then
Return 1.05D * salary
Else
Return salary + 2000 + 0.02D * (salary - 40000)
End If
End Function

Sub DisplayOutput(firstName As String, lastName As String,


newSalary As Decimal)
txtOutput.Text = "New salary for " & firstName & " " & lastName &
" is " & newSalary.ToString("C") & "."
End Sub
Student Solutions Manual (Page 59 of 193)

11. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click


Dim annualRateOfInterest, monthlyPayment, begBalance As Decimal
Dim intForMonth, redOfPrincipal, endBalance As Decimal
InputData(annualRateOfInterest, monthlyPayment, begBalance)
Calculate(annualRateOfInterest, monthlyPayment, begBalance,
intForMonth, redOfPrincipal, endBalance)
DisplayData(intForMonth, redOfPrincipal, endBalance)
End Sub

Sub InputData(ByRef annualRateOfInterest As Decimal,


ByRef monthlyPayment As Decimal,
ByRef begBalance As Decimal)
annualRateOfInterest = CDec(txtAnnualRateOfInterest.Text)
monthlyPayment = CDec(txtMonthlyPayment.Text)
begBalance = CDec(txtBegBalance.Text)
End Sub

Sub Calculate(annualRateOfInterest As Decimal, monthlyPayment As Decimal,


begBalance As Decimal, ByRef intForMonth As Decimal,
ByRef redOfPrincipal As Decimal, ByRef endBalance As Decimal)
Dim monthlyRateOfInterest As Decimal = annualRateOfInterest / 12
intForMonth = (monthlyRateOfInterest / 100) * begBalance
redOfPrincipal = monthlyPayment - intForMonth
endBalance = begBalance - redOfPrincipal
End Sub

Sub DisplayData(intForMonth As Decimal, redOfPrincipal As Decimal,


endBalance As Decimal)
txtIntForMonth.Text = intForMonth.ToString("C")
txtRedOfPrincipal.Text = redOfPrincipal.ToString("C")
txtEndBalance.Text = endBalance.ToString("C")
End Sub

13. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click


'Sort three numbers
Dim first As Double = CDbl(txtNum1.Text)
Dim second As Double = CDbl(txtNum2.Text)
Dim third As Double = CDbl(txtNum3.Text)
Sort(first, second, third)
txtMax.Text = CStr(first)
txtMiddle.Text = CStr(second)
txtMin.Text = CStr(third)
End Sub
Student Solutions Manual (Page 60 of 193)

Sub Sort(ByRef first As Double, ByRef second As Double, ByRef third As Double)
Dim max As Double
'Find greatest value
max = first
If second > max Then
max = second
End If
If third > max Then
max = third
End If
'Store maximum value in variable first
If second = max Then
Swap(first, second)
ElseIf third = max Then
Swap(first, third)
End If
'Order remaining two values
If third > second Then
Swap(second, third)
End If
End Sub

Sub Swap(ByRef x As Double, ByRef y As Double)


Dim temp As Double
temp = x
x = y
y = temp
End Sub

15. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click


Dim price, salesTaxRate, cost As Decimal
price = 29.95D
salesTaxRate = 0.05D
cost = FindCost(price, salesTaxRate)
txtResult.Text = cost.ToString("C")
End Sub

Function FindCost(price As Decimal, salesTaxRate As Decimal) As Decimal


Return price * (1 + salesTaxRate)
End Function
Student Solutions Manual (Page 61 of 193)

CHAPTER 6

EXERCISES 6.1 Do Loops

1. 18 3. 10 5. Maximum number: 7

7. Infinite loop. (To end the program, click on the Stop Debugging button on the Toolbar.)

9. Do and Loop are interchanged 11. While num >= 7

13. Until response <> "Y" 15. Until name = "" 19. While n = 0

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

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
Student Solutions Manual (Page 62 of 193)

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

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
Student Solutions Manual (Page 63 of 193)

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

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

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
Student Solutions Manual (Page 64 of 193)

35. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click


Const INTEREST_PER_MONTH As Decimal = 0.005D
Const MONTHLY_PAYMENT As Decimal = 290
Dim loanAmount As Decimal = 15000
Dim months As Integer = 0
Dim balance As Decimal = loanAmount
Do Until balance < loanAmount / 2
balance = (1 + INTEREST_PER_MONTH) * balance - MONTHLY_PAYMENT
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 Decimal = 10000
Do Until balance < 600
balance = (1.003D * balance) - 600
months += 1
Loop
txtOutput.Text = months & " months; " & balance.ToString("C")
End Sub

39. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click


'Determine the number of times a letter appears in a sentence.
Dim letter As String = txtLetter.Text.ToUpper
Dim sentence As String = txtSentence.Text.ToUpper
Dim positionOfLetter As Integer
Dim count As Integer = -1
Do
count += 1
positionOfLetter = sentence.IndexOf(letter, positionOfLetter + 1)
Loop Until positionOfLetter = -1
txtNumberOfOccurrences.Text = CStr(count)
End Sub
Student Solutions Manual (Page 65 of 193)

41. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click


'Determine when the population of India will exceed that of China
Dim chinaPop, indiaPop As Double, yr As Integer
chinaPop = 1.37 '2016
indiaPop = 1.31 '2016
yr = 2016
Do Until indiaPop > chinaPop
yr += 1
chinaPop *= 1.0066
indiaPop *= 1.013
Loop
txtYear.Text = CStr(yr)
End Sub

43. Function Sustitute(strVar As String,strVar1 As String, strVar2 As String) As String


Dim n As Integer
Do Until strVar.IndexOf(strVar1) = -1
n = strVar.IndexOf(strVar1)
ListBox1.Items.Add(n)
strVar = strVar.Remove(n, strVar1.Length)
strVar = strVar.Insert(n, strVar2)
ListBox1.Items.Add(strVar)
Loop
Return strVar
End Function

EXERCISES 6.2 For…Next Loops

1. Pass #1 3. 2
Pass #2 4
Pass #3 6
Pass #4 8
Who do we appreciate?

5. 5 7. •••••••••• 9. 4
6
7

11. The loop is never executed since 25 is greater than 1 and the step is negative.
Student Solutions Manual (Page 66 of 193)

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.

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


For num As Integer = 1 To 9 Step 2
lstBox.Items.Add(num)
Next
End Sub

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

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

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
Student Solutions Manual (Page 67 of 193)

23. Private Sub btnAnalyze_Click(...) Handles btnAnalyze.Click


Dim word As String = txtWord.Text.ToUpper
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

25. Private Sub btnCompute_Click(...) Handles btnCompute.Click


Const PERCENT_RAISE As Decimal = 0.05D
Dim name As String, age As Integer, salary As Decimal
Dim earnings As Decimal = 0
name = txtName.Text
age = CInt(txtAge.Text)
salary = CDec(txtSalary.Text)
For i As Integer = age To 65
earnings += salary
salary = salary + (PERCENT_RAISE * salary)
Next
txtOutput.Text = name & " will earn about " &
earnings.ToString("C0") & "."
End Sub
Student Solutions Manual (Page 68 of 193)

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.Clear()
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
Student Solutions Manual (Page 69 of 193)

29. Private Sub btnAnalyzeOptions_Click(...) Handles btnAnalyzeOptions.Click


'Compare salaries
Dim opt1, opt2 As Decimal
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 Decimal


'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

Function Option2() As Decimal


'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
Student Solutions Manual (Page 70 of 193)

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


Dim balance As Decimal = 0
Dim yr As Integer = 2019
For i As Integer = 1 To 108
balance = (1.0025D * balance) + 100
If i Mod 12 = 0 Then
lstOutput.Items.Add(yr & " " & balance.ToString("C"))
yr += 1
End If
Next
End Sub

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
Student Solutions Manual (Page 71 of 193)

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

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
Student Solutions Manual (Page 72 of 193)

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


Dim price, quantity As Decimal
lstOutput.Items.Clear()
quantity = 80 'current crop of soybeans in millions of bushels
lstOutput.Items.Add("YEAR" & " " & "QUANTITY" & " " & "PRICE")
For yr As Integer = 2018 To 2027
price = 20 – (0.1D * quantity)
lstOutput.Items.Add(yr & " " & quantity.ToString("N") &
" " & price.ToString("C"))
quantity = 5 * price - 10
Next
End Sub

41. Private Sub btnCompute_Click(...) Handles btnCompute.Click


'Compare two salary options.
Dim amount1 As Decimal = 0, amount2 As Decimal = 0
Dim salaryPerPeriod1 As Decimal = 20000
Dim salaryPerPeriod2 As Decimal = 10000
'Option 1: each period is one year
For i As Integer = 1 To 10
amount1 += salaryPerPeriod1
salaryPerPeriod1 += 1000
Next
txtOption1.Text = amount1.ToString("C0")
'Option 2: each period is six months
For i As Integer = 1 To 20
amount2 += salaryPerPeriod2
salaryPerPeriod2 += 250
Next
txtOption2.Text = amount2.ToString("C0")
End Sub
Student Solutions Manual (Page 73 of 193)

43. Private Sub btnCount_Click(...) Handles btnCount.Click


'Count the number of odometer readings containing the digit 1.
Dim total As Integer = 0
For i As Integer = 0 To 999999
If CStr(i).IndexOf("1") <> -1 Then
total += 1
End If
Next
txtAnswer.Text = total.ToString("N0")
'Note: The answer is 10^6 - 9^6, the total number of odometer readings
'minus the number of odometer readings that do not contain the digit 1.
End Sub

45. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click


'Calculate the likelihood of two people in a group having the same birthday.
Dim n As Integer = 365
Dim product, prob As Double
lstProbabilities.Items.Add("Number of People Probability")
For r As Integer = 20 To 30
product = 1
For i As Integer = 0 To (r – 1)
product *= (n - i) / n
Next
prob = 1 - product
lstProbabilities.Items.Add(" " & r & " " &
prob.ToString("N3"))
Next
End Sub

EXERCISES 6.3 List Boxes and Loops

1. Mozart 3. Tchaikovsky 5. 3 7. 80 9. 70 11. 300


Student Solutions Manual (Page 74 of 193)

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

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
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
Student Solutions Manual (Page 75 of 193)

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

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

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
Student Solutions Manual (Page 76 of 193)

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
Student Solutions Manual (Page 77 of 193)

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

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
Student Solutions Manual (Page 78 of 193)

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

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


txtOutput.Text = CStr(lstBox.Items(0))
End Sub
Student Solutions Manual (Page 79 of 193)

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


txtOutput.Text = CStr(lstBox.Items(4))
End Sub

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("N2")
txtLowest.Text = CStr(minGrade)
End Sub
Student Solutions Manual (Page 80 of 193)

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
Student Solutions Manual (Page 81 of 193)

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
CHAPTER 7

EXERCISES 7.1 Creating and Using Arrays

1. 101 3. Have a dessert spoon. 5. Yes 7. 12

9. You have a trio. 11. Your average is 80 13. The Artist won in 2012

15. one,two,three 17. 2 even numbers 19. Pearl Harbor: 1941

21. contains a 19th-century date

23. 6 words begin with a vowel 25. 4


6
2

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)

29. (a) 6.7 (greatest population of a New England state)


(b) 0.6 (least population of a New England state)
(c) 3.6 (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)
Student Solutions Manual (Page 82 of 193)

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

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

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

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

39. nums(3) should be changed to nums()


41. Logic error. The values of the array elements cannot be altered inside a For Each loop. The
output will be 6.
43. lstBox.Items.Add(line.Split(" "c).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
Student Solutions Manual (Page 83 of 193)

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

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

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
Student Solutions Manual (Page 84 of 193)

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
Student Solutions Manual (Page 85 of 193)

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
Student Solutions Manual (Page 86 of 193)

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

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
Student Solutions Manual (Page 87 of 193)

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

63. Dim grades(99) As Integer 'stores grades


Dim numGrades As Integer '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
Student Solutions Manual (Page 88 of 193)

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

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


sentence = sentence.Replace(",", "") 'Delete any commas.
sentence = sentence.Replace(":", "") 'Delete any colons.
sentence = sentence.Replace(";", "") 'Delete any semicolons.
Dim words() As String = sentence.Split(" "c), ending As String = ""
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
Student Solutions Manual (Page 89 of 193)

67. Dim mnths(11) As String


Dim dt As Date = #1/1/2017#
For i As Integer = 0 To 11
Dim n As Integer
n = dt.ToString("D").IndexOf(",")
mnths(i) = dt.ToString("D").Substring(n + 2, 3)
dt = dt.AddMonths(1)
Next

EXERCISES 7.2 Using LINQ with Arrays


1. 5 3. going 5. 6 7. 103 9. 8 11. 3 students have a grade of 100
7 offer
can't

13. 15 15. The average after dropping the lowest grade is 80


12

17. 37 is a prime number

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

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
Student Solutions Manual (Page 90 of 193)

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

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

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
Student Solutions Manual (Page 91 of 193)

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
Next
Return True
End If
End Function

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
Student Solutions Manual (Page 92 of 193)

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

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
Student Solutions Manual (Page 93 of 193)

37. Private Sub btnSort_Click(...) Handles btnSort.Click


'ListBox1.Sorted = True
Dim n As Integer = lstOriginalList.Items.Count - 1
Dim numbers(n) As Integer
For i As Integer = 0 To n
numbers(i) = CInt(lstOriginalList.Items(i))
Next
Array.Sort(numbers)
For i = 0 To n
lstSortedList.Items.Add(numbers(i))
Next
End Sub

39. Private Sub btnFind_Click(...) Handles btnDisplay.Click


Dim states() As String = IO.File.ReadAllLines("StatesBFNC.txt")
Dim data(3), line, flowers(49) As String
For i As Integer = 0 To (states.Count - 1)
line = states(i)
data = line.Split(","c)
flowers(i) = data(2)
Next
Dim query = From flr In flowers
Order By flr.Length Ascending
Select flr
Distinct
lstFlowers.DataSource = query.ToArray
lstFlowers.SelectedIndex = -1
txtNumber.Text = CStr(lstFlowers.Items.Count)
End Sub

41. Private Sub btnFind_Click(…) Handles btnFind.Click


Dim states() As String = IO.File.ReadAllLines("StatesBFNC.txt")
Dim query = From st In states
Let data = st.Split(","c)
Where data(4).ToLower.Substring(0, 4) =
data(0).Substring(data(0).Length - 4, 4)
Select data(4) & " " & data(0)
txtResult.Text = query.First
End Sub
Student Solutions Manual (Page 94 of 193)

EXERCISES 7.3 Arrays of Structures


1. The area of a football field is 19200 square yards.

3. Duke was founded in NC in 1838. 5. heights are same 7. Joe: 88


170 Moe: 90
Roe: 95
9. Mr. President lives in Washington, DC

11. In the event procedure, peace should be prize.peace and yr should be prize.yr.

13. The condition (game1 > game2) is not valid. Structures can only be compared one field at a
time.
15. The cities in Texas, along with their populationsin 2010. The cities are ordered by the sizes
of their populations beginning with the most populous city.
17. The population growth of Phoenix from 2000 to 2010.

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") & " sq. miles."
End Sub
Student Solutions Manual (Page 95 of 193)

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
Student Solutions Manual (Page 96 of 193)

23. Structure Player


Dim name As String
Dim team As String
Dim atBats As Integer
Dim hits As Integer
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 = CInt(data(2))
players(i).hits = CInt(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
Student Solutions Manual (Page 97 of 193)

25. Structure Player


Dim name As String
Dim team As String
Dim atBats As Integer
Dim hits As Integer
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 = CInt(data(2))
players(i).hits = CInt(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
Student Solutions Manual (Page 98 of 193)

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 person into the array people.
Dim people() = IO.File.ReadAllLines("Pioneers.txt")
Dim n As Integer = people.Count - 1
ReDim pioneers(n)
Dim line As String
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
Student Solutions Manual (Page 99 of 193)

29. Structure Justice


Dim firstName As String
Dim lastName As String
Dim apptPres As String
Dim state As String 'state abbreviation
Dim yrAppointed As Integer
Dim yrLeft As Integer
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 = CInt(data(4))
justices(i).yrLeft = CInt(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

31. Structure Justice


Dim firstName As String
Dim lastName As String
Dim apptPres As String
Dim state As String 'state abbreviation
Dim yrAppointed As Integer
Dim yrLeft As Integer
End Structure
Student Solutions Manual (Page 100 of 193)

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, 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 = CInt(data(4))
justices(i).yrLeft = CInt(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
Order By person.yrAppointed
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 Integer, leave As Integer) As Integer
If leave = 0 Then
Return (Now.Year - enter)
Else
Return (leave - enter)
End If
End Function
Student Solutions Manual (Page 101 of 193)

33. Structure FamousPerson


Dim name As String
Dim sport As String
Dim nickname 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("SportsStars.txt")
Dim n As Integer = people.Count - 1
ReDim famousPersons(n)
Dim line As String
Dim data(3) 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(3))
Next
End Sub

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


Dim query = From person In famousPersons
Where (person.dateOfBirth >= #1/1/1940#) And
(person.dateOfBirth < #1/1/1950#)
Select person.name
lstOutput.DataSource = query.ToList
lstOutput.SelectedItem = Nothing
End Sub
Student Solutions Manual (Page 102 of 193)

35. Structure Person


Dim name As String
Dim sport As String
Dim nickname As String
Dim dateOfBirth As Date
End Structure

Dim people() As Person

Private Sub frmFamous_Load(...) Handles MyBase.Load


'Place the data for each person into the array people.
Dim group() As String = IO.File.ReadAllLines("SportsStars.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).nickname = data(2)
people(i).dateOfBirth = CDate(data(3))
Next
End Sub

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


Dim query = From individual In people
Let dayOfBirth = DayOfWeek(individual.dateOfBirth)
Where individual.dateOfBirth.AddYears(50) <= Today And
individual.dateOfBirth.AddYears(60) > Today
Select individual.name, individual.nickname, dayOfBirth
dgvOutput.DataSource = query.ToList
dgvOutput.CurrentCell = Nothing
dgvOutput.Columns("name").HeaderText = "Name"
dgvOutput.Columns("nickname").HeaderText = "Nickname"
dgvOutput.Columns("dayOfBirth").HeaderText = "Day of Birth"
End Sub

Function DayOfWeek(dt As Date) As String


Dim d1 As String = dt.ToString("D")
Dim d2() As String = d1.Split(","c)
Return d2.First
End Function
Student Solutions Manual (Page 103 of 193)

37. Structure Person


Dim name As String
Dim sport As String
Dim nickname As String
Dim dateOfBirth As Date
End Structure

Dim people() As Person

Private Sub frmStars_Load(...) Handles MyBase.Load


'Place the data for each person into the array people.
Dim group() As String = IO.File.ReadAllLines("SportsStars.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).sport = data(1)
people(i).nickname = data(2)
people(i).dateOfBirth = CDate(data(3))
lstStars.Items.Add(people(i).name)
Next
End Sub

Private Sub lstStars_SelectedIndexChanged(...) Handles _


lstStars.SelectedIndexChanged
Dim n As Integer
n = lstStars.SelectedIndex
txtSport.Text = CStr(people(n).sport)
txtNickname.Text = CStr(people(n).nickname)
txtBirthDate.Text = (people(n).dateOfBirth).ToString("D")
End Sub
Student Solutions Manual (Page 104 of 193)

39. Structure Pictures


Dim name As String
Dim genre As String
End Structure
Dim films() As Pictures
Private Sub frmOscars_Load(...) Handles MyBase.Load
'Place the data for each picture into the array films.
Dim flicks() As String = IO.File.ReadAllLines("Oscars.txt")
Dim n As Integer = flicks.Count - 1
ReDim films(n)
Dim line As String 'holds data for a single film
Dim data(1) As String
For i As Integer = 0 To n
line = flicks(i)
data = line.Split(","c)
films(i).name = data(0)
films(i).genre = data(1)
Next
Dim query = From pic In films
Select pic.genre
Distinct
For Each film As String In query
lstGenre.Items.Add(film)
Next
End Sub

Private Sub lstGenre_SelectedIndexChanged(...) Handles _


lstGenre.SelectedIndexChanged
lstFilms.Items.Clear()
Dim query = From pic In films
Where pic.genre = CStr(lstGenre.SelectedItem)
Select pic.name
For Each film As String In query
lstFilms.Items.Add(film)
Next
End Sub
Student Solutions Manual (Page 105 of 193)

41. Structure Stock


Dim company As String
Dim symbol As String
Dim exchange As String
Dim industry As String
Dim price2013 As Decimal 'price at end of 2013
Dim price2014 As Decimal 'price at end of 2014
Dim earningsPerShare As Decimal
Dim dividend As Decimal
End Structure

Dim stocks(29) As Stock

Private Sub frmDOW_Load(...) Handles MyBase.Load


Dim line As String
Dim data(7) As String
Dim securities() As String = IO.File.ReadAllLines("DOW2014.txt")
For i As Integer = 0 To 29
line = securities(i)
data = line.Split(","c)
stocks(i).company = data(0)
stocks(i).symbol = data(1)
stocks(i).exchange = data(2)
stocks(i).industry = data(3)
stocks(i).price2013 = CDec(data(4))
stocks(i).price2014 = CDec(data(5))
stocks(i).earningsPerShare = CDec(data(6))
stocks(i).dividend = CDec(data(7))
lstStocks.Items.Add(stocks(i).symbol)
Next
End Sub

Private Sub lstStocks_SelectedIndexChanged(...) Handles _


lstStocks.SelectedIndexChanged
Dim n As Integer
n = lstStocks.SelectedIndex
txtCompany.Text = stocks(n).company
txtIndustry.Text = stocks(n).industry
txtExchange.Text = stocks(n).exchange
txtGrowth.Text = ((stocks(n).price2014 - stocks(n).price2013) /
stocks(n).price2013).ToString("P")
txtPEratio.Text = (stocks(n).price2014 /
stocks(n).earningsPerShare).ToString("N")
End Sub
Student Solutions Manual (Page 106 of 193)

43. Structure Stock


Dim company As String
Dim symbol As String
Dim exchange As String
Dim industry As String
Dim price2013 As Decimal 'price at end of 2013
Dim price2014 As Decimal 'price at end of 2014
Dim earningsPerShare As Decimal
Dim dividend As Decimal
End Structure
Dim stocks(29) As Stock
Private Sub frmDOW_Load(...) Handles MyBase.Load
Dim line As String
Dim data(7) As String
Dim securities() As String = IO.File.ReadAllLines("DOW2014.txt")
For i As Integer = 0 To 29
line = securities(i)
data = line.Split(","c)
stocks(i).company = data(0)
stocks(i).symbol = data(1)
stocks(i).exchange = data(2)
stocks(i).industry = data(3)
stocks(i).price2013 = CDec(data(4))
stocks(i).price2014 = CDec(data(5))
stocks(i).earningsPerShare = CDec(data(6))
stocks(i).dividend = CDec(data(7))
Next
End Sub
Private Sub btnDetermine_Click(...) Handles btnDetermine.Click
Dim query = From equity In stocks
Let ratio = equity.dividend / equity.price2014
Order By ratio Descending
Let ratioPercent = ratio.ToString("P")
Select equity.company, equity.symbol, ratioPercent
Dim queryAsArray() = query.ToArray
ReDim Preserve queryAsArray(9)
dgvStocks.DataSource = queryAsArray
dgvStocks.Columns("company").HeaderText = "Company"
dgvStocks.Columns("symbol").HeaderText = "Symbol"
dgvStocks.Columns("ratioPercent").HeaderText = "Yield as of 12/31/2014"
dgvStocks.CurrentCell = Nothing
End Sub
Student Solutions Manual (Page 107 of 193)

45. 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

47. 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

EXERCISES 7.4 Two-Dimensional Arrays


1. 1 3. 3 5. 55 7. 14 9. 2 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

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)

17. 12
Student Solutions Manual (Page 108 of 193)

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

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
Student Solutions Manual (Page 109 of 193)

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
Student Solutions Manual (Page 110 of 193)

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
Student Solutions Manual (Page 111 of 193)

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
Student Solutions Manual (Page 112 of 193)

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
Student Solutions Manual (Page 113 of 193)

'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
Student Solutions Manual (Page 114 of 193)

CHAPTER 8

EXERCISES 8.1 Managing Text Files

1. Samuel Alito,NJ 3. Alito was appointed by Bush


Henry Baldwin,PA Baldwin was appointed by Jackson

5. Alito,Samuel,2006
Baldwin,Henry,1830

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.
9. The new file is the same as the original file except that the last three fields have been deleted
from each record.
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.
13. The new file contains the names of the people who subscribe to the New York Times but not
the Wall Street Journal.
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

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
Student Solutions Manual (Page 115 of 193)

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

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
Student Solutions Manual (Page 116 of 193)

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
Student Solutions Manual (Page 117 of 193)

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

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
Student Solutions Manual (Page 118 of 193)

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

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

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
Student Solutions Manual (Page 119 of 193)

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 StreamReaders, StreamWriters, Structured Exception handling

1. Hello 3. Bon Jour 5. You must enter a number. 7. Error occurred.

9. File Ages.txt contains an invalid age.

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

13. The filespec Greetings.txt should be delimited with quotation marks.

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

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.
Student Solutions Manual (Page 120 of 193)

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

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
Student Solutions Manual (Page 121 of 193)

23. Private Sub btnAdd_Click(...) Handles btnAdd.Click


Dim item As String, price As Decimal
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, 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 = CDec(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

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
Student Solutions Manual (Page 122 of 193)

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 Integer
Do Until sr.EndOfStream
num = CInt(sr.ReadLine)
counter += 1
Loop
txtOutput.Text = CStr(counter)
sr.Close()
End Sub

29. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click


Dim sr As IO.StreamReader = IO.File.OpenText("Numbers.txt")
Dim num As Integer
Dim min As Integer = CInt(sr.ReadLine)
Do Until sr.EndOfStream
num = CInt(sr.ReadLine)
If (num < min) Then
min = num
End If
Loop
txtOutput.Text = CStr(min)
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 Integer = 0
Dim num As Integer
Do Until sr.EndOfStream
num = CInt(sr.ReadLine)
counter += 1
total += num
Loop
txtOutput.Text = (total / counter).ToString("N")
sr.Close()
End Sub
Student Solutions Manual (Page 123 of 193)

33. Private Sub frmStates_Load(...) Handles MyBase.Load


Dim sr As IO.StreamReader = IO.File.OpenText("StatesBFNC.txt")
Dim line As String, n As Integer
Do
line = sr.ReadLine
n = line.IndexOf(",")
lstStates.Items.Add(line.Substring(0, n))
Loop Until sr.EndOfStream
sr.Close()
End Sub

Private Sub lstStates_SelectedIndexChanged(...) Handles _


lstStates.SelectedIndexChanged
Dim sr As IO.StreamReader = IO.File.OpenText("StatesBFNC.txt")
Dim state, line As String
state = CStr(lstStates.SelectedItem)
line = sr.ReadLine
Do Until line.StartsWith(state) Or sr.EndOfStream
line = sr.ReadLine
Loop
Dim data(4) As String
data = line.Split(","c)
txtBird.Text = data(1)
txtFlower.Text = data(2)
txtNickname.Text = data(3)
txtCapital.Text = data(4)
sr.Close()
End Sub

35. Private Sub btnFind_Click(...) Handles btnDisplay.Click


Dim sr As IO.StreamReader = IO.File.OpenText("StatesBFN.txt")
Dim bird, line As String
Dim data(3) As String
Do
line = sr.ReadLine
data = line.Split(","c)
bird = data(1)
If lstBirds.Items.IndexOf(bird) = -1 Then
lstBirds.Items.Add(bird)
End If
Loop Until sr.EndOfStream
sr.Close()
txtNumber.Text = CStr(lstBirds.Items.Count)
End Sub
Student Solutions Manual (Page 124 of 193)

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


Dim srVar As IO.StreamReader = IO.File.OpenText("Gettysburg.txt")
Dim contents As String = srVar.ReadLine
srVar.Close()
MessageBox.Show(contents, "Gettysburg Address")
End Sub

39. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click


Dim sr As IO.StreamReader = IO.File.OpenText("Temperatures.txt")
Dim num, sum, high, low As Double
num = CDbl(sr.ReadLine)
sum += num
high = num
low = num
Do Until sr.EndOfStream
num = CDbl(sr.ReadLine)
sum += num
If num > high Then
high = num
End If
If num < low Then
low = num
End If
Loop
txt24hrs.Text = (sum / 24).ToString("N2")
txtHigh_Low.Text = ((high + low) / 2).ToString("N2")
sr.Close()
End Sub
Student Solutions Manual (Page 125 of 193)

EXERCISES 8.3 XML

1. No 3. No 5. No 7. No 9. N

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>
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

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
Student Solutions Manual (Page 126 of 193)

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

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
Student Solutions Manual (Page 127 of 193)

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

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
Student Solutions Manual (Page 128 of 193)

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
Student Solutions Manual (Page 129 of 193)

25(a).
Private Sub btnSenate_Click(...) Handles btnSenate.Click
Dim sr As IO.StreamReader = IO.File.OpenText("Senate116.txt")
Dim sw As IO.StreamWriter = IO.File.CreateText("Senate116.xml")
sw.WriteLine("<?xml version='1.0'?>")
sw.WriteLine("<!-- This file contains data on the 116th Senate -->")
sw.WriteLine("<Senate116>")
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("</Senate116>")
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("Senate116.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
Student Solutions Manual (Page 130 of 193)

CHAPTER 9

EXERCISES 9.1 List Boxes and Combo Boxes

1. Chopin is deleted from the list.

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

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

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

9. cboBox.Text = "Dante" 11. cboBox.Items.Remove("Shakespeare")

13. cboBox.Items.RemoveAt(cboBox.Items.Count - 1)

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

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
Student Solutions Manual (Page 131 of 193)

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
Student Solutions Manual (Page 132 of 193)

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

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
Student Solutions Manual (Page 133 of 193)

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 Eight Additional Controls and Objects


1. The Tick event will be triggered every 5 seconds (5000 milliseconds).
3. The tooltip will appear one second after the cursor is hovered over a control.
5. A check mark appears in front of the mnuOrderAsc menu item.
7. The Tick event will be triggered every intVar seconds.
9. The name of one of the U.S. states is selected at random and displayed in txtBox.
11. Two states are selected at random and displayed in the list box.
13. The contents of the Clipboard are deleted.
15. The text currently selected in txtBox, if any, is copied into the Clipboard.
17. The text “el” is copied into the Clipboard.
19. “Hxxlo” is displayed in txtBox.
21. The contents of the Clipboard are assigned to the variable strVar.
23. A picture of an airplane will be placed in the picture box.
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.
27. Timer1.Enabled = False
29. Dim randomNum As New Random()
txtBox.Text = CStr(randomNum.Next(1, 13))
Student Solutions Manual (Page 134 of 193)

31. Dim sr As IO.StreamReader = IO.Files.ReadText("Towns.txt")


Dim randomNum As New Random()
Dim num As Integer = randomNum.Next(1, 26), city As String
For i As Integer = 1 To num
city = sr.ReadLine
Next
txtBox.Text = city
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
35. Clipboard.Clear 37. txtBox.Copy() 39. Dim amount As Integer
amount = CInt(Clipboard.GetText)
41. mnuOrderDesc.Checked = False 43. VScrollBar2.Value = VScrollBar2.Minimum

45. The menu item mnuOrderAsc is grayed out and cannot be selected.
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
Student Solutions Manual (Page 135 of 193)

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

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
Student Solutions Manual (Page 136 of 193)

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

55. (no code)


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
Student Solutions Manual (Page 137 of 193)

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

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
Student Solutions Manual (Page 138 of 193)

63. Private Sub Button1_Click(...) Handles Button1.Click


Dim ranNum As New Random
Dim outcome(31), face As String
Dim numOfRuns As Integer = 0
Dim temp As Integer, result As String = ""
Dim runOfFive As Boolean = False
For i = 0 To 31
temp = ranNum.Next(0, 2)
If temp = 0 Then
outcome(i) = "H"
Else
outcome(i) = "T"
End If
result &= outcome(i)
Next
txtResult.Text = result
For i = 0 To 27
face = outcome(i)
If outcome(i + 1) = face And outcome(i + 2) = face And
outcome(i + 3) = face And outcome(i + 4) = face Then
runOfFive = True
numOfRuns += 1
End If
Next
If runOfFive Then
txtOutcome.Text = "Yes"
Else
txtOutcome.Text = "No"
End If
End Sub
Student Solutions Manual (Page 139 of 193)

EXERCISES 9.3 Multiple-Form Programs

1. $106.00 3. Your last name begins with K.

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
Student Solutions Manual (Page 140 of 193)

7. 'Code for frmMillionaire


Public numberOfYrs As Integer
Public Const INTEREST_RATE As Decimal = 0.06D

Private Sub btnCalculate_Click(...) Handles btnCalculate.Click


Dim balance As Decimal, numYears As Integer
balance = CDec(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 Decimal
End Structure

Private Sub frmBalance_Activated(...) Handles Me.Load


Dim a(frmMillionaire.numberOfYrs) As Year
a(0).num = 0
a(0).amount = CDec(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
Student Solutions Manual (Page 141 of 193)

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 Decimal '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 = CDec(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 = CDec(data(2))
lastCkNum = CInt(data(3))
lastDpNum = CInt(data(4))
End If
Student Solutions Manual (Page 142 of 193)

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 = CDec(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 Decimal
Dim transType As String
'Only store if all required fields are filled and valid
If DataValid() Then
amt = CDec(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
Student Solutions Manual (Page 143 of 193)

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 (Decimal)
Try
If CDec(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
Student Solutions Manual (Page 144 of 193)

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
Student Solutions Manual (Page 145 of 193)

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 = (CDec(data(5))).ToString("C")
Let Balance = (CDec(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
Student Solutions Manual (Page 146 of 193)

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

'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
Student Solutions Manual (Page 147 of 193)

EXERCISES 9.4 Graphics


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

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
Student Solutions Manual (Page 148 of 193)

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
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
Student Solutions Manual (Page 149 of 193)

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

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


Dim legend() As String = {"Soft Drinks", "Beer",
"Bottled Water", "Other"}
Dim quantity() As Decimal = {52.9D, 14.7D, 11.1D, 21.3D}
Dim percent(quantity. Count - 1) As Decimal
Dim sumOfQuantities As Decimal = 0
Dim sumOfSweepAngles As Decimal = 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
Student Solutions Manual (Page 150 of 193)

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


Dim gr As Graphics = picOutput.CreateGraphics
Dim smokers() As Decimal = {7.4D, 6.4D, 5.3D, 4.4D, 3.7D, 2.6D, 1.7D}
gr.DrawLine(Pens.Black, 30, 70, picOutput.Width, 70) 'x-axis
gr.DrawLine(Pens.Black, 30, 70, 30, 0) 'y-axis
gr.DrawLine(Pens.Black, 27, 70 - 7.4 * 7, 33, 70 - 7.4 * 7) 'tick mark
gr.DrawString("7.4", Me.Font, Brushes.Black, 0, 70 - 7.4 * 7 - 6)
gr.DrawString("2002 2004 2006 2008 2010 2012 2014",
Me.Font, Brushes.Black, 35, 78)
gr.DrawString("Percentage of College Freshmen Who Smoke", Me.Font,
Brushes.Blue, 30, 95)
gr.DrawString("Source: Higher Education Research Institute", Me.Font,
Brushes.Blue, 30, 110)
For i As Integer = 0 To smokers.Count - 2
gr.DrawLine(Pens.Blue, 50 + i * 35, 70 - smokers(i) * 7,
50 + (i + 1) * 35, 70 - smokers(i + 1) * 7)
Next
For i As Integer = 0 To smokers.Count - 1
gr.DrawLine(Pens.Black, 50 + i * 35, 75, 50 + i * 35, 65)
gr.FillEllipse(Brushes.Blue, 50 + i * 35 - 3,
70 - smokers(i) * 7 - 3, 6, 6)
Next
End Sub
Student Solutions Manual (Page 151 of 193)

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


Dim quantity() As Decimal = {8.1D, 4.8D, 4.4D, 3.9D, 3D, 3D}
Dim gr As Graphics = picOutput.CreateGraphics
Dim legend As String
'The picture box has width 310 and height 170
gr.DrawLine(Pens.Black, 10, 150, picOutput.Width - 10, 150) x-axis
Me.Text = "Popular Majors"
For i As Integer = 0 To quantity.Count - 1
gr.FillRectangle(Brushes.Tan, 20 + i * 60,
(150 - quantity(i) * 15), 30, quantity(i) * 15)
gr.DrawString(((quantity(i)).ToString("N1") & "%"),
Me.Font, Brushes.DarkBlue, 19 + i * 60, 135)
Next
legend = "Biology Nursing Psyc." &
“ Computer Mechanical Political"
gr.DrawString(legend, Me.Font, Brushes.Blue, 15, 152)
legend = "(general ) &
“ Engineering Science"
gr.DrawString(legend, Me.Font, Brushes.Blue, 12, 164)
gr.DrawString("Popular Majors for College Freshmen in Fall 2016",
Me.Font, Brushes.Blue, 5, 185)
End Sub
Student Solutions Manual (Page 152 of 193)

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 Decimal = {183, 335, 78, 260, 122, 848,
203, 167, 414, 72}
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 - 84.8, 45, 100 - 84.8) 'Tick mark
gr.DrawString("848", 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
Student Solutions Manual (Page 153 of 193)

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
Student Solutions Manual (Page 154 of 193)

21. Const ONE_INCH As Integer = 100 'number of pixels in an inch


Const LINE_HEIGHT As Integer = 20 '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("Norway", font2, Brushes.Black, x2, y)
gr.DrawString((0.950).ToString("P1"), font2, Brushes.Black, x3, y)
y += LINE_HEIGHT
gr.DrawString("2", font2, Brushes.Black, x1, y)
gr.DrawString("USA", font2, Brushes.Black, x2, y)
gr.DrawString((0.842).ToString("P1"), font2, Brushes.Black, x3, y)
y += LINE_HEIGHT
gr.DrawString("3", font2, Brushes.Black, x1, y)
gr.DrawString("China", font2, Brushes.Black, x2, y)
gr.DrawString((0.458).ToString("P1"), font2, Brushes.Black, x3, y)
End Sub

Private Sub btnPreview_Click(...) Handles btnPreview.Click


PrintPreviewDialog1.Document = PrintDocument1
PrintPreviewDialog1.ShowDialog()
End Sub
% That uses
Rank Country the Internet
1 Norway 95.0%
2 USA 84.2%
3 China 45.8%
Student Solutions Manual (Page 155 of 193)

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
Student Solutions Manual (Page 156 of 193)

CHAPTER 10

EXERCISES 10.1 An Introduction to Databases

1. (e) 3. (d) 5. (b)

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.pop2030 - city.pop2014) / 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
Student Solutions Manual (Page 157 of 193)

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.pop2030 > 20
Order By city.pop2030 Descending
Select city.name
lstOutput.DataSource = query.ToList
lstOutput.SelectedItem = Nothing
End Sub

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 perIncrease = 100*(city.pop2030 - city.pop2014) / city.pop2014
Order By perIncrease 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.pop2014, city.pop2030
dgvOutput.DataSource = query2.ToList
dgvOutput.CurrentCell = Nothing
dgvOutput.Columns("name").HeaderText = "City"
dgvOutput.Columns("country").HeaderText = "Country"
dgvOutput.Columns("pop2014").HeaderText = "Population in 2014"
dgvOutput.Columns("pop2030").HeaderText = "Population in 2030"
End Sub
Student Solutions Manual (Page 158 of 193)

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.pop2014 / country.pop2014
Where city.name = lstCities.Text
Select cityPer
txtOutput.Text = (query.First).ToString("P")
End Sub

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.pop2014 & "," & city.pop2030
IO.File.WriteAllLines("Megacities.txt", query.ToArray)
MessageBox.Show("File Created")
End Sub
Student Solutions Manual (Page 159 of 193)

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.country
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.country
lstCountriesArea.DataSource = queryArea.ToList
lstCountriesArea.SelectedItem = Nothing
End Sub
Student Solutions Manual (Page 160 of 193)

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 nation In UNDataSet.Nations
Select nation.area
Dim max As Double = query.Max
Dim min As Double = query.Min
Dim queryOutput = From nation In UNDataSet.Nations
Where nation.area = max Or
nation.area = min
Order By nation.area Descending
Select nation.country, nation.continent,
nation.population, nation.area
dgvOutput.DataSource = queryOutput.ToList
dgvOutput.CurrentCell = Nothing
End Sub

21. Private Sub frmCurrencies_Load(...) Handles MyBase.Load


Me.RatesTableAdapter.Fill(Me.ExchrateDataSet.Rates)
Dim query = From money In ExchrateDataSet.Rates
Order By money.USdollarRate 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.USdollarRate
txtCurrency.Text = query.First.monetaryUnit
txtRate.Text = CStr(Math.Round(query.First.USdollarRate,3))
End Sub
Student Solutions Manual (Page 161 of 193)

23. Private Sub frmBaseball_Load(...) Handles MyBase.Load


Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams)
Dim query = From club In BaseballDataSet.Teams
Order By club.team
Select club.team
lstTeams.DataSource = query.ToList
End Sub

Private Sub lstTeams_SelectedIndexChanged(...) Handles _


lstTeams.SelectedIndexChanged
Dim query = From club In BaseballDataSet.Teams
Where club.team = lstTeams.Text
Select club.stadium
txtStadium.Text = query.First
End Sub

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 person In BaseballDataSet.Players
Order By person.hits Descending
Select person.hits
Dim mostHits As Double = query1.Max
Dim query2 = From person In BaseballDataSet.Players
Where person.hits = mostHits
Select person.player
lstOutput.DataSource = query2.ToList
lstOutput.SelectedItem = Nothing
End Sub
Student Solutions Manual (Page 162 of 193)

27. Private Sub frmBaseball_Load(...) Handles MyBase.Load


Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams)
Me.PlayersTableAdapter.Fill(Me.BaseballDataSet.Players)
Dim query = From club In BaseballDataSet.Teams
Order By club.team
Select club.team
lstTeams.DataSource = query.ToList
End Sub

Private Sub lstTeams_SelectedIndexChanged(...) Handles _


lstTeams.SelectedIndexChanged
Dim query = From person In BaseballDataSet.Players
Where person.team = lstTeams.Text
Let battingAve = person.hits / person.atBats
Let formattedBattingAve = battingAve.ToString("N3")
Order By battingAve Descending
Select person.player, formattedBattingAve
dgvOutput.DataSource = query.ToList
dgvOutput.CurrentCell = Nothing
dgvOutput.Columns("player").HeaderText = "Name"
dgvOutput.Columns("formattedBattingAve").HeaderText =
"Batting Average"
End Sub

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 club In BaseballDataSet.Teams
Where club.league = "American"
Select club.hits
Dim query2 = From club In BaseballDataSet.Teams
Where club.league = "American"
Select club.atBats
txtBattingAve.Text = (query1.Sum / query2.Sum).ToString("N3")
End Sub
Student Solutions Manual (Page 163 of 193)

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 person In BaseballDataSet.Players
Join club In BaseballDataSet.Teams
On person.team Equals club.team
Where club.league = "National"
Select person.player
txtNational.Text = (query.Count).ToString("N0")
End Sub

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 club In BaseballDataSet.Teams
Let battingAve = club.hits / club.atBats
Let formattedBattingAve = battingAve.ToString("N3")
Where club.league = group
Order By battingAve Descending
Select club.team, formattedBattingAve
dgvOutput.DataSource = query.ToList
dgvOutput.CurrentCell = Nothing
dgvOutput.Columns("team").HeaderText = "Team"
dgvOutput.Columns("formattedBattingAve").HeaderText = "Batting Average"
End Sub
Student Solutions Manual (Page 164 of 193)

35. Private Sub frmBaseball_Load(...) Handles MyBase.Load


Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams)
Me.PlayersTableAdapter.Fill(Me.BaseballDataSet.Players)
Dim query = From club In BaseballDataSet.Teams
Order By club.team
Select club.team
lstTeams.DataSource = query.ToList
End Sub

Private Sub lstTeams_SelectedIndexChanged(...) Handles _


lstTeams.SelectedIndexChanged
Dim query = From player In BaseballDataSet.Players
Join club In BaseballDataSet.Teams
On player.team Equals club.team
Let playerBattingAve = player.hits / player.atBats
Let teamBattingAve = club.hits / club.atBats
Where club.team = lstTeams.Text And
playerBattingAve > teamBattingAve
Order By playerBattingAve Descending
Select person.player
lstPlayers.DataSource = query.ToList
lstPlayers.SelectedItem = Nothing
End Sub
Student Solutions Manual (Page 165 of 193)

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 person In BaseballDataSet.Players
Join club In BaseballDataSet.Teams
On person.team Equals club.team
Where club.league = "National" And person.atBats > 100
Let playerBattingAve = person.hits / person.atBats
Select playerBattingAve
Dim highestAve As Double = query1.Max
Dim query2 = From person In BaseballDataSet.Players
Join club In BaseballDataSet.Teams
On person.team Equals club.team
Let playerBattingAve = person.hits / person.atBats
Where club.league = "National" And
playerBattingAve = highestAve
Select person.player
lstPlayers.DataSource = query2.ToList
lstPlayers.SelectedItem = Nothing
End Sub

39. 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
Student Solutions Manual (Page 166 of 193)

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

EXERCISES 10.2 Editing and Designing Databases

7. Add a record to the Cities table whose name field is empty or contains the same name as an
already existing record.
9. BindingSource1.Find("name", strVar) = -1

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

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

17. Apollo 13 does not appear in the key field of the Actors table. Thus the Rule of Referential
Integrity would be violated.
Student Solutions Manual (Page 167 of 193)

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.
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.

CHAPTER 11
EXERCISES 11.1 Classes and Objects

1. Any negative grade will be recorded as 0 and any grade greater than 100 will be recorded as
100.

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

5. The properties Midterm and Final are write-only.

7. The property SocSecNum is initialized to the value 999-99-9999.

9. The keyword New is missing from the third line of the event procedure.

11. The statement nom = m_name is not valid. m_name would need to be Public and referred to
by scholar.m_name.

13. The statements pupil.Midterm = scholar.Midterm and the statement


lstGrades.Items.Add(pupil.Midterm) are not valid. The Midterm property is write-
only; it can be set, but cannot return a value.
15. Country: Canada
Capital: Ottawa
Pop: 31 million

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
Student Solutions Manual (Page 168 of 193)

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
Student Solutions Manual (Page 169 of 193)

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
Student Solutions Manual (Page 170 of 193)

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
Student Solutions Manual (Page 171 of 193)

25. Public Class frmCashRegister


Dim register As New CashRegister()

Private Sub btnAdd_Click(...) Handles btnAdd.Click


'Add an amount to the balance.
register.Add(CDec(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(CDec(txtAmount.Text))
txtBalance.Text = (register.Balance).ToString("C")
txtAmount.Clear()
txtAmount.Focus()
End Sub
End Class 'frmCashRegister

Class CashRegister
Private m_balance As Decimal

Public ReadOnly Property Balance() As Decimal


Get
Return m_balance
End Get
End Property

Sub Add(amount As Decimal)


If (m_balance + amount) >= 0 Then 'Ensure balance stays nonnegative
m_balance += amount
End If
End Sub

Sub Subtract(amount As Decimal)


If (m_balance - amount) >= 0 Then 'Ensure balance stays nonnegative
m_balance = m_balance - amount
End If
End Sub
End Class 'CashRegister

27. Public Class frmFICA


Private Sub btnCalculate_Click(...) Handles btnCalculate.Click
Dim tax As New FICA()
tax.PreviousEarnings = CDec(txtToDate.Text)
tax.CurrentEarnings = CDec(txtCurrent.Text)
txtTax.Text = (tax.CalculateFICA).ToString("C")
End Sub
End Class 'frmFICA
Student Solutions Manual (Page 172 of 193)

Class FICA
'Member variables store property values.
Private m_previousEarnings As Decimal 'Previous year-to-date earnings
Private m_currentEarnings As Decimal

Public WriteOnly Property PreviousEarnings() As Decimal


Set(Value As Decimal)
m_previousEarnings = Value
End Set
End Property

Public WriteOnly Property CurrentEarnings() As Decimal


Set(Value As Decimal)
m_currentEarnings = Value
End Set
End Property

Function CalculateFICA() As Decimal


'Calculate social security benefits tax and medicare tax
'for a single employee
Const WAGE_BASE As Decimal = 128400D 'There is no social security
' benefits tax on income above this level.
Const SOCIAL_SECURITY_RATE As Decimal = 0.062D
Const MEDICARE_RATE As Decimal = 0.0145D
'Dim ytdEarnings, curEarnings, totalEarnings As Decimal
Dim totalEarnings, socialSecurityBenTax, medicareTax As Decimal
totalEarnings = m_previousEarnings + m_currentEarnings
'Calculate the Social Security Benefits tax.
If totalEarnings <= WAGE_BASE Then
socialSecurityBenTax = SOCIAL_SECURITY_RATE * m_currentEarnings
ElseIf m_previousEarnings < WAGE_BASE Then
socialSecurityBenTax = SOCIAL_SECURITY_RATE *
(WAGE_BASE - m_previousEarnings)
End If
'Calculate the FICA tax.
medicareTax = MEDICARE_RATE * m_currentEarnings
If totalEarnings >= 200000D Then
medicareTax += 0.009D * (totalEarnings - 200000D)
End If
Return socialSecurityBenTax + medicareTax 'FICA tax
End Function
End Class 'FICA
Student Solutions Manual (Page 173 of 193)

29. Public Class frmMortgage

Private Sub btnCalculate_Click(...) Handles btnCalculate.Click


Dim loan As New Mortgage
loan.Principal = CDec(txtPrincipal.Text)
loan.InterestRate = CDec(txtInterestRate.Text)
loan.Years = CInt(txtYears.Text)
txtMonthlyPayment.Text = (loan.calculateMonthlyPayment).ToString("C2")
End Sub
End Class 'frmMortgage

Class Mortgage
Private m_principal As Decimal
Private m_interestRate As Decimal
Private m_years As Integer

Public WriteOnly Property Principal() As Decimal


Set(value As Decimal)
m_principal = value
End Set
End Property

Public WriteOnly Property InterestRate() As Decimal


Set(value As Decimal)
m_interestRate = value
End Set
End Property

Public WriteOnly Property Years() As Integer


Set(value As Integer)
m_years = value
End Set
End Property

Function calculateMonthlyPayment() As Decimal


Dim i As Decimal
i = m_interestRate / 1200
Return ((i / (1 - ((1 + i) ^ (-12 * m_years)))) * m_principal)
End Function
End Class 'Mortgage
Student Solutions Manual (Page 174 of 193)

EXERCISES 11.2 Working with Objects


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
Student Solutions Manual (Page 175 of 193)

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
Student Solutions Manual (Page 176 of 193)

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
Student Solutions Manual (Page 177 of 193)

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

Public ReadOnly Property Abbreviation() As String


Get
Return m_abbr
End Get
End Property
Student Solutions Manual (Page 178 of 193)

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

7. Public Class frmCashRegister


Dim WithEvents register As New CashRegister()

Private Sub btnAdd_Click(...) Handles btnAdd.Click


'Add an amount to the balance.
register.Add(CDec(txtAmount.Text))
'Display the new result.
txtBalance.Text = (register.Balance).ToString("C")
txtAmount.Clear()
txtAmount.Focus()
End Sub
Student Solutions Manual (Page 179 of 193)

Private Sub btnSubtract_Click(...) Handles btnSubtract.Click


'Subtract an amount from the balance.
register.Subtract(CDec(txtAmount.Text))
'Display the new result.
txtBalance.Text = (register.Balance).ToString("C")
txtAmount.Clear()
txtAmount.Focus()
End Sub

Private Sub AttemptToOverdraw(amt As Decimal) 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 Decimal

Public Event AttemptToOverdraw(amt As Decimal)

Public ReadOnly Property Balance() As Decimal


Get
Return m_balance
End Get
End Property

Sub Add(amount As Decimal)


If (m_balance + amount) >= 0 Then 'Make sure balance does not go negative.
m_balance += amount
Else
RaiseEvent AttemptToOverdraw(amount - m_balance)
End If
End Sub

Sub Subtract(amount As Decimal)


If (m_balance - amount) >= 0 Then 'Make sure balance does not go negative.
m_balance = m_balance - amount
Else
RaiseEvent AttemptToOverdraw(amount - m_balance)
End If
End Sub
End Class 'CashRegister
Student Solutions Manual (Page 180 of 193)

9. Public Class frmAdd


Dim WithEvents x As New Fraction() 'Left fraction
Dim WithEvents y As New Fraction() 'Middle fraction
Dim WithEvents z As New 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

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
Student Solutions Manual (Page 181 of 193)

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
Student Solutions Manual (Page 182 of 193)

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 'First player
Private m_second As PairOfDice '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
Student Solutions Manual (Page 183 of 193)

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

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 Decimal
'Store input into properties
emp.Name = txtName.Text
Student Solutions Manual (Page 184 of 193)

emp.Hours = CDec(txtHours.Text)
emp.Salary = CDec(txtSalary.Text)
emp.YearToDate = CDec(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
'Member variables hold property values
Private m_hours As Decimal
Private m_salary As Decimal

Dim tax As New Tax() 'Represents the tax for this employee

Public Property Name() As String

Public Property Hours() As Decimal


Get
Return m_hours
End Get
Set(Value As Decimal)
m_hours = Value
'Update the tax property also
tax.Wages = CDec(m_hours * m_salary)
End Set
End Property

Public Property Salary() As Decimal


Get
Return m_salary
End Get
Set(Value As Decimal)
m_salary = Value
'Update the tax property also
tax.Wages = CDec(m_hours * m_salary)
End Set
End Property

Public Property YearToDate() As Decimal


Get
'Return the tax property
Return tax.YearToDate
End Get
Set(Value As Decimal)
'Update the tax property
Student Solutions Manual (Page 185 of 193)

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 Decimal
'Return the tax property
Return tax.FICA
End Function

Function Withholding() As Decimal


'Return the tax property
Return tax.Withholding
End Function
End Class 'Employee
Class Tax
Public Property Wages() As Decimal
Public Property YearToDate() As Decimal
Public Property Withhold() As Integer
Public Property Married() As Boolean
Function FICA() As Decimal
'Calculate 2018 social security benefits tax and medicare tax
'for a single employee
Const WAGE_BASE As Decimal = 128400D 'There is no social
'security benefits tax on income above this level.
Const SOCIAL_SECURITY_RATE As Decimal = 0.062D
Const MEDICARE_RATE As Decimal = 0.0145D
Dim totalEarnings, socialSecurityBenTax, medicareTax As Decimal
'ytdEarnings = CDec(txtToDate.Text)
'curEarnings = CDec(txtCurrent.Text)
totalEarnings = YearToDate + Wages
'Calculate the Social Security Benefits tax.
If totalEarnings <= WAGE_BASE Then
socialSecurityBenTax = SOCIAL_SECURITY_RATE * Wages
ElseIf YearToDate < WAGE_BASE Then
socialSecurityBenTax = SOCIAL_SECURITY_RATE *
(WAGE_BASE - YearToDate)
End If
'Calculate the FICA tax.
Student Solutions Manual (Page 186 of 193)

medicareTax = MEDICARE_RATE * Wages


If (Not Married) And YearToDate >= 200000D Then
medicareTax += 0.009D * (totalEarnings - 200000D)
End If
If Married And YearToDate > 250000 Then
medicareTax += 0.009D * (totalEarnings - 250000D)
End If
Return socialSecurityBenTax + medicareTax
End Function

Function Withholding() As Decimal


Dim adjPay As Decimal
'Subtract exemptions from wages
adjPay = CDec(Wages - (79.80 * Withhold))
'Branch depending upon status
If Married Then
Select Case adjPay
Case 0 To 222
Return 0
Case 222 To 588
Return 0.1D * (adjPay - 222)
Case 588 To 1711
Return 36.6D + 0.12D * (adjPay - 588)
Case 1711 To 3395
Return 171.36D + 0.22D * (adjPay - 1711)
Case 3395 To 6280
Return 541.84D + 0.24D * (adjPay - 3395)
Case 6280 To 7914
Return 1234.24D + 0.32D * (adjPay - 6280)
Case 7914 To 11761
Return 1757.12D + 0.35D * (adjPay - 7914)
Case Is > 11761
Return 3103.57D + 0.37D * (adjPay - 11761)
End Select
Else
'Withholding table for single earners
Select Case adjPay
Case 0 To 71
Return 0
Case 71 To 254
Return (0.1D * (adjPay - 71))
Case 254 To 815
Return 18.3D + 0.12D * (adjPay - 254)
Case 815 To 1658
Return 85.96D + 0.22D * (adjPay - 815)
Case 1658 To 3100
Return 271.08D + 0.24D * (adjPay - 1658)
Case 3100 To 3917
Return 617.16D + 0.32D * (adjPay - 3100)
Case 3917 To 9687
Return 878.6D + 0.35D * (adjPay - 3917)
Case Is > 9687
Return 2898.1D + 0.37D * (adjPay - 9687)
End Select
End If
End Function
End Class 'Tax
Student Solutions Manual (Page 187 of 193)

EXERCISES 11.3 Inheritance

1. 4 3. 64 5. Can move Has jointed limbs and no backbone

7. The keyword Overrides should be Inherits.

9. The Hi function should be declared with the Overridable keyword in class Hello and with the
keyword Overrides keyword in class Aussie.
11. The Hi function should be declared with the Overrides keyword in class Cowboy.

13. The Hello class should be declared with the MustInherit keyword, and the function Hi
should be declared with the MustOverride keyword.
15. The Hello class should be declared with the MustInherit keyword, not MustOverride.

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
Student Solutions Manual (Page 188 of 193)

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
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
Student Solutions Manual (Page 189 of 193)

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

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
Student Solutions Manual (Page 190 of 193)

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 Decimal
Sub Deposit(amount As Decimal)
m_balance += amount
End Sub
Sub WithDrawal(amount As Decimal)
m_balance = m_balance - amount
End Sub
Public ReadOnly Property Balance() As Decimal
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
Student Solutions Manual (Page 191 of 193)

21. Public Class frmBookstore


Dim books(10) As Book 'Stores books
Dim count As Integer '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 = CDec(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 Decimal = 0
Dim value As Decimal = 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

MustInherit Class Book


Public Property Name() As String
Public Property Cost() As Decimal
Public Property Quantity() As Integer
'Children must override this property
MustOverride ReadOnly Property Price() As Decimal
End Class 'Book
Student Solutions Manual (Page 192 of 193)

Class Tradebook
Inherits Book

Overrides ReadOnly Property Price() As Decimal


Get
Return 1.4D * Cost '40% markup
End Get
End Property
End Class 'Tradebook

Class Textbook
Inherits Book

Overrides ReadOnly Property Price() As Decimal


Get
Return 1.2D * Cost '20% markup
End Get
End Property
End Class 'Textbook
Student Solutions Manual (Page 193 of 193)

23. Public Class frmInterestOnlyMortgage


Private Sub btnCalculate_Click(...) Handles btnCalculate.Click
Dim loan As New InterestOnlyMortgage
loan.Principal = CDec(txtPrincipal.Text)
loan.InterestRate = CDec(txtInterestRate.Text)
loan.Years = CInt(txtYears.Text) - CInt(txtInterestOnlyYears.Text)
loan.InterestOnlyYears = CInt(txtInterestOnlyYears.Text)
txtMonthlyPayment1.Text =
(loan.calculateInitialMonthlyPayment).ToString("C2")
txtMonthlyPayment2.Text =
(loan.calculateMonthlyPayment).ToString("C2")
End Sub
End Class 'frmInterestOnlyMortgage
Class Mortgage
Private m_years As Integer
Public Property Principal() As Decimal
Public Property InterestRate() As Decimal
Public WriteOnly Property Years() As Integer
Set(value As Integer)
m_years = value
End Set
End Property
Function calculateMonthlyPayment() As Decimal
Dim i As Decimal
i = _InterestRate / 1200
Return ((i / (1 - ((1 + i) ^ (-12 * m_years)))) * _Principal)
End Function
End Class 'Mortgage
Class InterestOnlyMortgage
Inherits Mortgage
Private m_numberOfInterestOnlyYears As Integer
Public WriteOnly Property InterestOnlyYears() As Integer
Set(value As Integer)
m_numberOfInterestOnlyYears = value
End Set
End Property
Function calculateInitialMonthlyPayment() As Decimal
Return CDec(Principal * InterestRate / 1200)
End Function
End Class 'InterestOnlyMortgage

You might also like