Student Solutions Manual (Page 1 of 211

)

STUDENT SOLUTIONS MANUAL
to accompany An Introduction to Programming Using Visual Basic 2010, 8th Edition by David I. Schneider

Student Solutions Manual (Page 2 of 211)

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

Student Solutions Manual (Page 3 of 211)

CONTENTS
Chapter Comments Chapter 2 Visual Basic Controls and Events Exercises 2.2 Visual Basic Controls 11 Exercises 2.3 Visual Basic Events 15 Chapter 3 Variables, Input, and Output Exercises 3.1 Numbers 18 Exercises 3.2 Strings 21 Exercises 3.3 Input and Output 26 Chapter 4 Decisions Exercises 4.1 Relational and Logical Operators 30 Exercises 4.2 If Blocks 31 Exercises 4.3 Select Case Blocks 38 Exercises 4.4 Input via User Selection 42 Chapter 5 General Procedures Exercises 5.1 Function Procedures 47 Exercises 5.2 Sub Procedures, Part I 50 Exercises 5.3 Sub Procedures, Part II 55 Chapter 6 Repetition Exercises 6.1 Do Loops 57 Exercises 6.2 For…Next Loops 62 Exercises 6.3 List Boxes and Loops 68 Chapter 7 Arrays Exercises 7.1 Creating and Accessing Arrays 77 Exercises 7.2 Using LINQ with Arrays 85 Exercises 7.3 Arrays of Structures 89 Exercises 7.4 Two-Dimensional Arrays 99 Chapter 8 Text Files Exercises 8.1 Managing Text Files 106 Exercises 8.2 StreamReaders, StreamWriters, Structured Exception Handling 111 Exercises 8.3 XML 115 Chapter 9 Additional Controls and Objects Exercises 9.1 List Boxes and Combo Boxes 120 Exercises 9.2 Eight Additional Controls and Objects 125 Exercises 9.3 Multiple-Form Programs 132 Exercises 9.4 Graphics 142

Student Solutions Manual (Page 4 of 211)

Chapter 10 Databases Exercises 10.1 An Introduction to Databases 151 Exercises 10.2 Editing and Designing Databases 164 Chapter 11 Object-Oriented Programming Exercises 11.1 Classes and Objects 165 Exercises 11.2 Working with Objects 172 Exercises 11.3 Inheritance 186 Chapter 12 Web Applications Exercises 12.1 Programming for the Web, Part 1 193 Exercises 12.2 Programming for the Web, Part 2 199 Exercises 12.3 Using Databases in Web Programs 204

ByVal e As System. You might find the Properties window easier to use if you undock it while setting properties. I recommend that you configure Windows to show all file extensions. However. After you have finished using the Properties window. If so. Also. the window will become undocked and larger. For instance. a program will run if the phrase is simply deleted. look at the discussion of "Displaying File Extensions" on pages 5 and 6. The folders “Ch10” and "Ch12" have a subfolder named “Databases” containing all the databases needed for the exercises. All of these files are contained in the folders “Ch02”. Chapter 2 1. the code will execute after you delete the ellipses.. 3. On page 44 you are asked to run a program that was downloaded from the Pearson website for the book.Student Solutions Manual (Page 5 of 211) Chapter Comments Chapter 1 1. Your instructor might skip this chapter. There is never any need for you to manually type in the code for a program in this textbook. .EventArgs". 2. and pictures needed for the exercises.) as place holders for the phrase "ByVal sender As System.Object. “Ch03”. Each chapter file contains a subfolder named “Text_Files_for_Exercises” which contains the text files needed for that chapter’s exercises. and so on. By default. Note: This process also can be used to undock (and redock) the Toolbar and the Solution Explorer window. Section 1. Example 2 is contained in the folder “3-1-2”. At the top of page 44. Each program is contained in a folder with a name in the form chapter–section– example number. databases. if you use Ctrl+C to copy code from this Student Solutions Manual and paste it into your own program. Every program you write requires use of the Properties window. The folder “Ch09” has a subfolder named “Pictures” that contains picture files. 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. “Ch04”. the program in Chapter 3. Therefore. If you double-click on the Properties window’s title bar. right-click on its title bar and click on Dock. the Properties window is docked to the right side of the IDE. All of the programs appearing in Examples and Case Studies can be downloaded from that website. we explain our use of ellipses (. I recommend that you take a quick look at two items from the chapter. Many of the programs make use of a text file in the subfolder Debug of the program’s bin subfolder. The website also contains all the text files.. A program will not run when the phrase is replaced with an ellipsis.

Option Infer. the underscore character was needed to continue a statement onto another line.Student Solutions Manual (Page 6 of 211) Chapter 3 1. Strict. the CheckedChanged event is raised. However.1 on page 70 shows the settings for Options Explicit. (The default setting is On. In Chapter 3 we used list boxes to display data. when the line ends with a comma or an arithmetic operator) and therefore will seldom be needed in the programs you write.3. Beginning with VB2010. This was necessary due to the fact that we must limit the length of lines in a printed page.4. Most instructors will recommend that the first two Options be set to On. If your instructor decides to skip this topic. 2. you might want to take a quick look (just a few minutes) to see what's involved in printing the output of a program. we show how list boxes are used to allow the user to make selections. Another control used to make a selection from a list. Figure 3. The first two sentences after Figure 4. is controversial. a combo box. will be discussed in Chapter 9. . 3. I included it at the request of some instructors. This material is not needed in the textbook. In earlier versions of Visual Basic. This material is optional. Chapter 4 1. 2. and Infer set to On. Underscore characters frequent appear in the answer section of the book and in the Student Solutions Manual following the word "Handles".12 on page 149 should read as follows: When you click on an unselected item in a list box.1 is unusual in that you will not be asked to write any programs in the exercise set. the underscore character can be omitted when a line that obviously has a continuation (such as. Section 4. When you click on a check box or on an unchecked radio button. we discuss line continuation. In Section 4. take a quick look at the discussion of local type inference on page 236.) If you want to learn more about the effect of Option Infer. On page 77. A discussion of sending output to the printer is presented at the end of Section 3. 3. the concepts presented in this section will be fundamental to the rest of the textbook. the SelectedIndexChanged event is raised. on the other hand.

called a For Each loop. After the loop has executed. Loops have traditionally been used to process lists of data. Whenever a number is greater than the current value of max. the maximum value of the numbers in a list box are calculated with the following algorithm: (a) Declare a variable named max. if you find Sub procedures somewhat confusing at first. The algorithms for calculating sums and averages is obvious.3. In Example 4 of Section 6. One possibility is to set the value of max equal to the first number in the list. The above comment is not intended to diminish the importance of Sub procedures. Function procedures appear in many more programs than Sub procedures. However. 2. A third type of loop.. loops can be used with a list of numbers to compute the sum of the numbers. They are a fundamental component of good program design. For instance. (c) Use a loop to examine the numbers one at a time. the largest number in the list and the smallest number in the lists. a method for processing lists without using loops will be presented. change the value of max to be that number. In Section 7.Student Solutions Manual (Page 7 of 211) Chapter 5 1.3 presents techniques for processing lists of data with loops.2. There are two types of loops presented in this chapter—Do loops and For.1. You will eventually become comfortable with Sub procedures after seeing them used in subsequent chapters. However. the value of max will be the largest number in the list. don't worry.. but it is not essential. there are a number of programs in this textbook that would be very difficult to write without Function procedures. Another possibility requires some knowledge of the number in the list. . Chapter 6 1. Example 4 uses an analogous algorithm to find the smallest number in the list box. the initial value of max can be set to 0. You will still be able to work the exercises. The use of Sub procedures is part of good programming practice. Any computer program can be written without Sub procedures. Section 6. (b) Assign a value to the variable that is guaranteed to be less than or equal to the maximum value in the list. if the number are all grades on an exam. the average of the numbers. These two algorithms appear several times in the textbook in both examples and exercises. will be presented in Section 7. 3.Next loops. Except for the three case studies. 2. For instance.

txt: contains statistics for all of the players in the major league who had at least 350 at bats in 2009.1 can be omitted if you covered Section 8.1 in a slightly different form. In earlier versions of Visual Basic.Jefferson.txt").Student Solutions Manual (Page 8 of 211) Chapter 7 1. c.1 is that there are four ways to fill an array. The two sections in this chapter are independent of each other. (c) Dim strVar As String = "Washington. b. Chapter 8 1. A very important idea to take away from Section 7. Section 7. the array is declared and sized automatically at the same time it is filled.1.S. Let's illustrate the ways by filling an array with the names of the first three presidents. However.3."c) (d) Dim pres(2) As String pres(0) = "Washington" pres(1) = "Jefferson" pres(2) = "Adams" In the first three ways.3 is perhaps the most challenging section in the book.Adams" Dim pres() As String = strVar. 3. the techniques presented in this section are very powerful and are heavily used later in the book with text files and databases.1 shows some modern techniques for combining lists of data. The techniques also are presented in Section 8. The preliminaries section at the beginning of Section 8. The techniques presented in the preliminaries will take a fair amount of effort to master. SBWinners.txt is located in the program's bin\Debug folder of the program and contains three lines (each containing the name of a president). Baseball. The second and third ways will be the most used in this book. . Justices. 2.txt: contains all Super Bowl winners up to and including 2010. these tasks could only be carried out with complicated algorithms involving loops. "Jefferson". (a) Dim pres() As String = {"Washington". However. the payoff will be substantial. 3. "Adams} (b) Dim pres() As String = IO. 2. Section 8.3 and rely solely on Section 8.txt: contains all people who served on the U.ReadAllLines("Pres.Split(". Supreme Court prior to May 2010. where the text file Pres. Some instructors will skip Section 7.File. Some important text files used in this chapter are as follows: a.

However. USPres. c. However. Chapter 10 1. d. Some important data files used in this chapter are as follows: a. Supreme Court prior to the summer of 2010. Section 9.accdb: contains currency exchange rates in December 2009.txt: contains the names of all U.accdb: contains statistics for all of the players in the major league who had at least 350 at bats in 2009.S. Programs written by professional programmers often use more than one form. all programs outside of Section 9. b. the chapter shows how to use several tools that are familiar to you from major programs you have used. Justices. Some important databases used in this chapter are as follows: a. b. Most of Chapter 9 is not needed in the remainder of the book. you can just bind the database once and write a different event procedure for each exercise. Also. UN.txt: contains all people who served on the U.accdb: contains all people who served on the U. Baseball. after you get used to it you will find it easy and quick to carry out. 2010. This chapter is independent of the rest of the book.3 shows how this is done. The steps for binding a database to a program may look complicated at first.Student Solutions Manual (Page 9 of 211) 4.txt: contains the composition of the U.S.S. Senate as of May 1. Justice Stevens retired in the summer of 2010. . Supreme Court prior to the summer of 2010. since this is an introductory book.accdb: contains the composition of the United Nations as of May 1.S. when you work several exercises using the same database. 2010. Chapter 9 1. Justices. However. If you want to update the file after his replacement is named.3 use only one form. 2. Baseball. 2. c. Chapter 11 1. Senate111.xml: contains statistics for all of the players in the major league who had at least 350 at bats in 2009. d. change the last entry in his record to 2010 and add a record for the person replacing him. Exchrate.

Be sure to read the solution to the practice problem in Section 12. The Visual Studio File menu contains the items New Web Site and Open Web Site that you can use to create and access Web programs.Student Solutions Manual (Page 10 of 211) Chapter 12 1. you do not have to install Visual Web Developer. if you have a complete version of Visual Studio. However. . It shows you how to save a lot of time when writing the programs for the exercise set. Most people will use Visual Web Developer that is contained on the DVD packaged with this book. The programs in the chapter are not created with Visual Basic. 2.3.

Student Solutions Manual (Page 11 of 211)

CHAPTER 2 EXERCISES 2.2 1. After a button is clicked it has a 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". 5. Double-click the TextBox icon in the Toolbox. Activate the Properties window. Select the BackColor property. Click on the down-arrow to the right of the Settings box. Click on the Custom tab, and then click on the desired yellow in the palette. Click on the form to see the empty yellow text box. 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 2010". Select the Font property and click on the ellipsis to the right of the Settings box. Scroll up the Font list box, and click on Courier New in the Font box. Click OK. Widen the text box to accommodate its text. 11. Double-click on the Button icon in the Toolbox. Activate the Properties window, and select the BackColor property. Click on the down-arrow button to the right of the Settings box. Click on the Custom tab, and then click on the white square in upper-left corner of the palette. Select the Text property and type "PUSH". Select the Font property, and click on the ellipsis. Click on Italic (with XP or Vista) or Oblique (with Windows 7) in the "Font style" list. Click on 24 in the Size box and click OK. Resize the button.

Student Solutions Manual (Page 12 of 211)

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 Italic (with XP or Vista) or Oblique (with Windows 7) in the "Font style" list. Click OK. Select the TextAlign property, click on the down-arrow box to the right of the Settings box, and click on one of the center rectangles. 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 select the Font property. Click on the ellipsis to the right of the Settings box. Click on Wingdings in the Font box. Click on the largest size available (72) in the Size box. Click OK. Select the Text property and change the setting to a less than sign (<). Click on the label. (Note: If you didn't know that the less than symbol corresponded to a diskette in the Wingdings font, you could double-click on the diskette character in the Character Map, click the Copy button, select the Text property, and press Ctrl+V. The less than character will appear in the Text settings box.) 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 to see the yellow list box.

Student Solutions Manual (Page 13 of 211) 23. In the Solution Explorer window, right click on “Form1.vb” and select Rename from the context menu. Type “frmYellow.vb”. Right-click on the form in the Form Designer, and select Properties from the context menu. Click on BackColor property in the Properties window. Click on the down-arrow button in the right part of the Settings box, click on the Custom tab, and click on a yellow square. 25. Begin a new project. 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 project. Change the text in the form's title bar to "Fill the Blank". Place a label, a text box, and another label on the form at appropriate locations. Change the Text setting of the first label to "I’m the king of the" and the Text setting of the second label to "A Quote by Leonardo DiCaprio". 29. Begin a new project. Change the text in the form's title bar to "Uncle's Advice". Place five labels and three buttons on the form. 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.

Student Solutions Manual (Page 14 of 211)

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 plus sign (in XP) or the right-pointing triangle (Vista or Windows 7) to the left of the Font property. Click on the Size property, change the setting to 12, and press the Enter key. (Alternative: Replace the last three lines with the following steps.) In the Properties window, select the Font property. Click on the ellipsis button to the right of the Settings box. Click on 12 in the Size list and click OK. 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: middles of the two controls are aligned Second blue snap line: bottoms of the two controls are aligned 47. The setting is cycling through the different available colors.

.T.DoubleClick lstOutput. txtBoxTwo..Text = "The stuff that dreams are made of.Visible = False 27.) Handles btnRight.Text = txtBox. 17.Items.Text = "Left Justify" txtBox.Size.Red. The statement txtOutput.) Handles btnCenter..TextAlign = HorizontalAlignment. txtBox.. Font. lblTwo.Text = "E.Click lstOutput.Left End Sub Private Sub btnCenter_Click(.Click txtBox." 19.TextAlign = HorizontalAlignment.Enabled = True 23.TextAlign = HorizontalAlignment..) Handles Label1.Right End Sub . lblTwo. 13.Font. The word "Hello" 3.Text should be Me.) Handles btnLeft. The Enter event occurs when a control gets the focus. 9. The word "Hello" on an orange-colored background 7.Focus() 29.Student Solutions Manual (Page 15 of 211) EXERCISES 2. btnOutcome.. 5. Private Sub btnLeft_Click(. 15. txtBox. 33.Items.ForeColor = Color. the Click event is also raised.Font.Click txtBox.Red txtBox.Add("Double Click") End Sub Whenever the DoubleClick event is raised.Size is a read-only property.Size is valid since it is reading the value of txtBox. Private Sub Label1_Click(." 21.Font. 31.. Red should be replaced with Color.Text.Center End Sub Private Sub btnRight_Click(.Text = "Center" txtBox.Size = 20 is not valid since it is setting the value of txtBox..3 1. The text box vanishes.Enabled = False 25.. phone home. However. The word "Hello" on a gold background. txtBox. Form1.Size.Text = "Right Justify" txtBox..Click txtBox.Font. The word "Hello" in green letters 11.Add("Click") End Sub Private Sub Label1_DoubleClick(.) Handles Label1.

Visible = True btnTwo.Visible = True btnTwo.) Handles btnWhite.Enter txtQuote..Red End Sub Private Sub btnBlue_Click(.Visible = True End Sub Private Sub btnTwo_Click(..." End Sub 39.BackColor = Color..Text = "I like life.ForeColor = Color.) Handles txtTruth.Enter txtQuote.Blue End Sub Private Sub btnWhite_Click(.Visible = False btnFour.White End Sub Private Sub btnYellow_Click(.Visible = True btnTwo.Visible = True btnThree.Visible = True btnFour. it's something to do..Visible = True End Sub Private Sub btnFour_Click(.Visible = True btnThree.ForeColor = Color.Click txtBox..BackColor = Color.Text = "The future isn't what it used to be.....Click txtBox.) Handles btnYellow.Enter txtQuote..Visible = False btnTwo..Visible = True btnThree. Private Sub txtLife_Enter(.Visible = False btnThree.Click btnOne." End Sub Private Sub txtFuture_Enter(. Private Sub btnOne_Click(.Visible = True btnFour.Click txtBox..Visible = False End Sub ..) Handles btnThree.Text = "Tell the truth and run...Student Solutions Manual (Page 16 of 211) 35.) Handles txtFuture." End Sub Private Sub txtTruth_Enter(.Click btnOne. Private Sub btnRed_Click(.Click txtBox.) Handles txtLife.Visible = True End Sub Private Sub btnThree_Click(..Yellow End Sub 37.) Handles btnTwo...) Handles btnOne..) Handles btnFour.Click btnOne.) Handles btnBlue.) Handles btnRed..Click btnOne..Visible = True btnFour.

.Click..Visible = False End Sub Private Sub btnReappear_Click(.) Handles btnVanish.Click txtOutput.Click lblFace. btnTwo.." End Sub ..) Handles btnOne.Visible = True End Sub 43. Private Sub btnAny_Click(. Private Sub btnVanish_Click(.Click lblFace..) Handles btnReappear.Text = "You just clicked on a button..Student Solutions Manual (Page 17 of 211) 41.

3. The second assignment statement should not contain a dollar sign.Clear() lstResults.Items.Add((7 * 8) + 5) End Sub 25. Valid 3.Click lstOutput.) Handles btnCompute. 9 15.1 1. 47. 0 57.Add(0.Add(x + 4) y = y + 1 End Sub 31. 2 15 0 2 2 11 11 11 11 y 0 0 6 6 6 6 7 39..Click lstOutput.Items.Click lstOutput. Not valid 23.Click Dim x. 8 7. 6 33. y As Double x = 2 y = 3 * x x = y + 5 lstResults. 10 9.Add(17 * (3 + 162)) End Sub 29. 6 51. Private Sub btnCompute_Click(.. x Private Sub btnEvaluate_Click(..Items.. Not valid 19..) Handles btnEvaluate.128 45.Items. 10 49. . 43. Dim quantity As Integer = 12 53.) Handles btnCompute. –3 55. 9W is not a valid variable name. 2 17. 1 11.Student Solutions Manual (Page 18 of 211) CHAPTER 3 EXERCISES 3. Private Sub btnCompute_Click(... 6 . 1 8 9 35. 16 21. The first assignment statement should not contain a comma. Private Sub btnCompute_Click(.Items.125 5..055 * 20) End Sub 27. The third line should read c = a + b 41. 12 13. 1 64 37.) Handles btnCompute.

Items.. 2)) End Sub 63..Click Dim revenue.95 discountPercent = 30 markdown = (discountPercent / 100) * price price = price ...) Handles btnCompute.Add(Math.) Handles btnCompute. discountPercent.Add(corn) End Sub .Click Dim balance As Double balance = 100 balance += 0..Round(price.costs lstOutput.) Handles btnCompute.Student Solutions Manual (Page 19 of 211) 59. yieldPerAcre.Items.Items.Click Dim price. Private Sub btnCompute_Click(.Click Dim balance As Double balance = 100 balance = balance * (1.) Handles btnCompute..Click Dim acres.05 * balance balance += 0.Add(Math.) Handles btnCompute.Round(balance.05 * balance lstOutput.05 ^ 10) lstOutput. markdown As Double price = 19. Private Sub btnCompute_Click(..Items. 2)) End Sub 65.Add(profit) End Sub 61. profit As Double revenue = 98456 costs = 45000 profit = revenue .. Private Sub btnCompute_Click(..05 * balance balance += 0.Add(Math. Private Sub btnCompute_Click(.Items.markdown lstOutput. Private Sub btnCompute_Click(. 2)) End Sub 67.Round(balance.. costs. corn As Double acres = 30 yieldPerAcre = 18 corn = yieldPerAcre * acres lstOutput.

averageSpeed As Double distance = 233 elapsedTime = 7 . people.Items.Student Solutions Manual (Page 20 of 211) 69.2 averageSpeed = distance / elapsedTime lstOutput..Add(averageSpeed) End Sub 71.) Handles btnCompute..Add(waterUsed) End Sub .. elapsedTime.. Private Sub btnCompute_Click(.Click Dim distance.Click Dim waterPerPersonPerDay.Items. waterUsed As Double waterPerPersonPerDay = 1600 people = 315000000 days = 365 waterUsed = waterPerPersonPerDay * people * days lstOutput.) Handles btnCompute. days. Private Sub btnCompute_Click(.

Text = firstName & " " & middleName & " " & lastName & "." txtOutput. Visual Basic 3. End is a keyword and cannot be used as a variable name. middleName.Student Solutions Manual (Page 21 of 211) EXERCISES 3... 33. 29. Your age is 21.Text = "(c) " & publisher End Sub 37. " & yearOfBirth End Sub 35. 5. Private Sub btnDisplay_Click(. Inc.. goodbye (0 through 7) 27.Click Dim firstName. ABC 2 4 55 mph STU 21. 17.5 23. Ernie 5. WALLAWALLA 25. only a string. 12 MUNICIPALITY city 6 15.Click Dim publisher As String publisher = "Prentice Hall. not Double. 8 7. True 11.. The variable phoneNumber should be declared as type String. lastName As String Dim yearOfBirth As Integer firstName = "Thomas" middleName = "Alva" lastName = "Edison" yearOfBirth = 1847 txtOutput.2 1. 31. A ROSE IS A ROSE IS A ROSE 19. flute 13.) Handles btnDisplay.) Handles btnDisplay. 123 9. Dim str As String 'Place in the Declarations section of the program . The IndexOf method cannot be applied to a number. Private Sub btnDisplay_Click(.

Text) income = revenue .. expenses. 2) txtOutput.Click Dim cycling.Round(pounds.Text = "The distance of the storm is " & distance & " miles.) Handles btnCompute. income As Double revenue = CDbl(txtRevenue.Text) / 5 distance = Math." End Sub 43.) Handles btnCompute..Round(distance.Text) swimming = CDbl(txtSwim..Text = CStr(income) End Sub . running.Text) pounds = (200 * cycling + 475 * running + 275 * swimming) / 3500 pounds = Math." End Sub 41. Private Sub btnCompute_Click(.Text) expenses = CDbl(txtExpenses.Click Dim revenue.. Private Sub btnCompute_Click(..Text) running = CDbl(txtRun.) Handles btnCompute.Text = pounds & " pounds were lost.Student Solutions Manual (Page 22 of 211) 39.expenses txtNetIncome.. pounds As Double cycling = CDbl(txtCycle. 1) txtWtLoss. swimming.Click Dim distance As Double distance = CDbl(txtNumSec. Private Sub btnCompute_Click(.

Text = CStr(Math.) Handles btnCompute.) Handles btnPressMe.Text) tip = amount * (percentage / 100) txtTip.Click Dim amount. Dim number As Integer = 100 'in Declarations section 'Note: the Text property of txtOutput was set to 100 at design time Private Sub btnPressMe_Click(.Round(tip... percentage.1 'decrease number by 1 txtOutput.. 2)) End Sub 47.Text = CStr(number) End Sub .Click number = number .Student Solutions Manual (Page 23 of 211) 45.. tip As Double amount = CDbl(txtAmount. Private Sub btnCompute_Click(.Text) percentage = CDbl(txtPercentage.

IndexOf(oldWord) txtOutput..Click Dim sentence. oldWord. Private Sub btnModifySentence_Click(. Private Sub btnDisplay_Click(.Text oldWord = txtOriginalWord.Click Dim speed. 2) txtEstimatedSpeed.Text position = sentence.Substring(position + oldWord..Sqrt(24 * distance) speed = Math.Substring(0.Student Solutions Manual (Page 24 of 211) 49.Round(speed. newWord As String Dim position As Integer sentence = txtSentence. distance As Double distance = CDbl(txtDistanceSkidded.Text newWord = txtReplacementWord.Text = sentence.Text = speed & " mph" End Sub .) Handles btnDisplay..Text) speed = Math. position) & newWord & sentence.) Handles btnModifySentence..Length) End Sub 51.

Click num += 1 sum += CDbl(txtScore.Text) txtScore.) Handles btnCalculate. Private Sub btnCompute_Click(..Text = CStr(sum) End Sub Private Sub txtEitherNum_TextChanged(.TextChanged.Click Dim num1. Dim sum As Double Dim num As Integer 'sum of the scores entered 'number of scores entered Private Sub btnRecord_Click(. num2. txtSecondNum..Clear() txtScore.Click txtAverage...Text) num2 = CDbl(txtSecondNum.) Handles btnCompute.TextChanged txtSum.) Handles btnRecord.Focus() End Sub Private Sub btnCalculate_Click(. sum As Double num1 = CDbl(txtFirstNum.) Handles _ txtFirstNum...Student Solutions Manual (Page 25 of 211) 53..Text) sum = num1 + num2 txtSum..Clear() End Sub .Text = CStr(sum / num) End Sub 55.

S. 31. Pay to France $27. 53. 55. FormatNumber(123456) is a string and therefore cannot be assigned to a numeric variable.Show("First solve the problem.50% 21. "Good Advice") 65. endOfYearCost As Double Dim percentIncrease As Double begOfYearCost = 200 endOfYearCost = CDbl(InputBox("Enter cost at the end of the year:")) percentIncrease = (endOfYearCost . Private Sub btnDisplay_Click(. 47. 12. The likelihood of Heads is 50% 33. November 25. 4/5/2013 39. MessageBox.67% 3.235 13. 2010 41.Show. after the word MessageBox. $0.0 15. $12.. 1. LLL000 61.Student Solutions Manual (Page 26 of 211) EXERCISES 3. ($0. -0.begOfYearCost) / begOfYearCost txtOutput. 49.80 19. 100.6% of the U.) Handles btnDisplay.0 7. 66.. 29 43. 12 17. 57." End Sub .". 51.67 9. 0. Then write the code. 10/23/2010 35. population 25+ years old are college graduates. Hello John Jones 45. The second line should use CDbl to convert the right-hand side to type Double. 0-00-000000-& 63. Thursday.622.267. You might win 360 dollars.00% 25. 000 59.Text = "The increase in cost for the year is " & FormatPercent(percentIncrease) & ". 7. 29.Click Dim begOfYearCost.000 11. 10/2/2011 37.23) 5.234. 25.3 1. $106.00 Prints the words Hello World using a 10-point bold Courier New font in blue letters 2 inches from the left side of the page and 2 inches from the top of the page.00 27. 1. The statement n += 1 is not valid since the value of a named constant cannot be changed. You must insert .346.346 23.

Day...AddMonths(1) numDays = DateDiff(DateInterval. Private Sub Determine_Click(. firstDayOfYr.Substring(0.Text = dayOfWeek End Sub 71. dt2) txtNumDays.) Handles btnDisplay.Text = CStr(numDays) End Sub . firstDayOfNextYr) txtNumDays. firstDayOfNextYr As Date Dim numDays As Double firstDayOfYr = CDate("1/1/" & mtbYear..) Handles btnDetermine.) Handles btnDetermine. position) txtDayOfWeek.LongDate) Dim position As Integer = fullDate. Private Sub Determine_Click(. DateFormat.Student Solutions Manual (Page 27 of 211) 67. yr As Integer 'month given as 1 through 12 Dim dt.Text) Dim fullDate As String = FormatDateTime(dt.Click Dim month. dt.Click Dim dt As Date = CDate(mtbDate..Text) dt = CDate(month & "/1/" & yr) dt2 = dt.Text) firstDayOfNextYr = firstDayOfYr.") Dim dayOfWeek As String = fullDate.Text) yr = CInt(mtbYear.Text = CStr(numDays) End Sub 69. dt2 As Date Dim numDays As Double month = CInt(txtMonth..Click Dim firstDayOfYr.IndexOf("..AddYears(1) numDays = DateDiff(DateInterval. Private Sub btnDisplay_Click(.Day.

Text) intRate = CDbl(txtIntRate.Add("for " & yrs & " years.Clear() principal = CDbl(txtPrincipal. "Reminder") End Sub 75. yrs.Add("balance is " & FormatCurrency(amt) & ". intRate.Click Dim principal.) Handles btnCompute..") End Sub .Text) yrs = 10 amt = principal * (1 + intRate) ^ yrs lstOutput.Enter MessageBox..Add("invested at " & FormatPercent(intRate)) lstOutput. the ") lstOutput.Show("Be sure to include the area code!".Items. Private Sub btnCompute_Click(.Items. amt As Double lstOutput.Items..) Handles txtPhoneNumber.Student Solutions Manual (Page 28 of 211) 73.. Private Sub txtPhoneNumber_Enter(.Items.Items.Add("When " & FormatCurrency(principal) & " is") lstOutput.

. font2. 10.DrawString("1". font2.DrawString("Japan". FontStyle. Brushes.Black. x3.Black.ShowDialog() End Sub .Black. Const ONE_INCH As Integer = 100 Const LINE_HEIGHT As Integer = 20 'number of pixels in an inch 'one-quarter of an inch Private Sub btnPrint_Click(.Student Solutions Manual (Page 29 of 211) 77.Document = PrintDocument1 PrintPreviewDialog1. font2. font2.DrawString("China". font2. x3.Print() End Sub Private Sub PrintDocument1_PrintPage(.DrawString("2". y) gr. 1).Regular) gr. Brushes. Brushes.DrawString("WW Users". x3. 1).Black.Black.DrawString("Country".. x2. x2.) Handles PrintDocument1. x1.Black. y) gr.Black. y) y += LINE_HEIGHT gr. x2.. x1. Brushes. y) y += LINE_HEIGHT gr.. Brushes. x3. Brushes.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".Graphics Dim x1 As Integer = ONE_INCH 'use one inch beyond left margin Dim x2 As Integer = CInt(1. x2.DrawString("USA". y) y += LINE_HEIGHT gr.Black. Brushes. x3.PrintPage Dim gr As Graphics = e. font1.Black.DrawString(FormatPercent(0.) Handles btnPrint. 10. Brushes. font2.DrawString(FormatPercent(0. y) gr.DrawString(FormatPercent(0.Click PrintPreviewDialog1.DrawString("Rank". y) End Sub Private Sub btnPreview_Click(. y) y += LINE_HEIGHT gr. y) gr. font1. y) gr.DrawString("3".) Handles btnPreview. Brushes. Brushes. Brushes.5 * ONE_INCH) 'offset for second column Dim x3 As Integer = CInt(2. y) gr.Black.Underline) Dim font2 As New Font("Courier New"..DrawString("% of". font1.Black.119. font2..Black. x1. FontStyle.065.Black. 1). font2. y) gr. x1. y) gr.Click PrintDocument1. Brushes.16. Brushes. font2. font2.

True 15. True 13. True 23. execute a statement of the form txtOutput. (a >= b) Or (c = d) 45.] 47. False 27. False 17.Text = Boolean expression. False 59. a <= b 43. "We're all in this alone. True 55.Student Solutions Manual (Page 30 of 211) CHAPTER 4 EXERCISES 4. False 9." . The letter before G is F 5. Not Equivalent 35. False 29. True 57. True 25. Equivalent 33. True . Not Equivalent 39.Length >= 5) [In Exercises 46 through 49. True 11. False 51. False 53. hi 3. True 31. True 49. Equivalent 37. Equivalent 41. False 19. (a = "") Or (a >= b) Or (a.1 1.Lily Tomlin 7. True 21.

. or not to be. Syntax error.25 * num '25 cents each Else cost = 0.2 1. Private Sub btnCompute_Click(. 9.Text = "Wrong" End If 21.15 If tip < 1 Then tip = 1 End If txtOutput. 13..Text = "The cost is " & FormatCurrency(cost) & ". cost As Double num = CDbl(InputBox("Number of widgets:")) If num < 100 Then cost = 0.Click Dim num.) Handles btnCompute..) Handles btnCompute. You are old enough to vote in 7 days. 10 7.Substring(0.Click Dim cost. tomorrow is another day. 1). message = "Is Alaska bigger than Texas and California combined?" answer = InputBox(message) If (answer.ToUpper = "Y") Then txtOutput." End Sub 23. Third line should be If ((1 < num) And (num < 3)) Then 15..2 * num '20 cents each End If txtOutput. Private Sub btnCompute_Click(.Student Solutions Manual (Page 31 of 211) EXERCISES 4.Text = "Leave " & FormatCurrency(tip) & " for the tip. tip As Double cost = CDbl(InputBox("Enter cost of meal:")) tip = cost * 0. Fourth line should be If ((major = "Business") Or (major = "Computer Science")) Then 17. a = 5 19. 11. To be. Less than ten. Hi 5." End Sub . 3.Text = "Correct" Else txtOutput. Syntax error.

Private Sub btnAskQuestion_Click(.Text = CStr(avg) End Sub .")) s2 = CDbl(InputBox("Enter the second of the three scores. s2.Text = "Nice try.) Handles btnCompute.")) s3 = CDbl(InputBox("Enter the third of the three scores.ToUpper If name = "WILLARD SCOTT" Then txtOutput." Else txtOutput. s3 As Double '3 scores Dim avg As Double 'average of the two highest scores s1 = CDbl(InputBox("Enter the first of the three scores.Student Solutions Manual (Page 32 of 211) 25. Private Sub btnCompute_Click(..")) 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 = "Correct..Click Dim s1..) Handles btnAskQuestion." End If End Sub 27.Click Dim name As String name = (InputBox("Who was the first Ronald McDonald?"))..

Text = "I need " & FormatCurrency(cost .Text) amount = CDbl(txtAmount. cost. Private Sub btnCompute_Click(." Else txtOutput. amount..Text = "Your change is " & FormatCurrency(change) & ".Text = FormatCurrency(grossPay) End Sub .Click Dim weight. grossPay As Double wage = CDbl(txtHourlyWage.) Handles btnCompute.40)) End If txtGrossPay.Student Solutions Manual (Page 33 of 211) 29. change As Double weight = CDbl(txtWeight...) Handles btnCompute.amount) & " more." End If End Sub 31. Private Sub btnCompute_Click(.5 * wage * (hours .7 If (amount >= cost) Then change = amount .Click Dim wage. hours.Text) 'Hourly pay hours = CDbl(txtHoursWorked.Text) 'Hours worked If hours <= 40 Then grossPay = wage * hours Else grossPay = (wage * 40) + (1..cost txtOutput.Text) cost = weight * 1.

Items.) Handles btnBogart..Student Solutions Manual (Page 34 of 211) 33.) Handles btnRaines.") numLines += 1 ElseIf numLines = 2 Then lstOutput.Click If numLines = 0 Then lstOutput..Items. Dim numLines As Integer = 0 'In Declarations section of Code Editor 'numLines tells the number of lines that have been displayed.Add("But we're in the middle of the desert..") numLines += 1 End If End Sub .Add("I came to Casablanca for the waters.. Private Sub btnBogart_Click(.") numLines += 1 End If End Sub Private Sub btnRaines_Click(.Click If numLines = 1 Then lstOutput.Items.Add("I was misinformed.

Dim numGuesses As Integer = 0 Private Sub btnEvaluate_Click(..Visible = False btnDisplay.Close() ElseIf CInt(numGuesses) = 10 Then msg = "Calvin Coolidge was born on July 4.".Student Solutions Manual (Page 35 of 211) 35." MessageBox.Show(msg.'" Else msg = "Sorry!" End If MessageBox. "Correct") Me..." & " you won't be called upon to repeat it.) Handles btnDisplay.) Handles btnEvaluate.Click 'Assume that the Text property of txtNumberOfGuesses 'was set to 0 in the Form Designer numGuesses += 1 txtNumberOfGuesses. 'If you don't say anything..'" ElseIf CInt(numGuesses) = 7 Then msg = "His nickname was 'Silent Cal.Click If lblLanguage.Show("Calvin Coolidge was born on July 4.Show(msg.2 Exercise 35 4.Close() Else If CInt(numGuesses) = 3 Then msg = "He once said.Text = "Show Name of Language" Else lblLanguage.Visible Then lblLanguage.Visible = True btnDisplay. 1872. Private Sub btnDisplay_Click(.Text = CStr(numGuesses) Dim msg As String If txtAnswer. "You've Run Out of Guesses") Me.Clear() txtAnswer.Focus() End Sub 4.Text = "Hide Name of Language" End If End Sub .Text.IndexOf("COOLIDGE") <> -1 Then MessageBox.2 Exercise 37 37. 1872.ToUpper. "Incorrect") End If txtAnswer.

Click Dim day As String Dim day1. day2) If numDays = 366 Then txtLeapYear.Text = "YES" Else txtLeapYear.Text = CStr(approximateAge) End If End Sub .Day. Private Sub Determine_Click(. day2 As Date Dim numDays As Double day = "1/1/" & txtYear.Text = "NO" End If End Sub 41. Private Sub btnCompute_Click(.Text) approximateAge = DateDiff(DateInterval.) Handles lblDetermine.AddYears(CInt(approximateAge)) If Today < dt2 Then txtAge. day1.Text = CStr(approximateAge ... Today) dt2 = dt.) Handles btnDetermine.Text day1 = CDate(day) day2 = day1..1) Else txtAge.Click Dim dt. dt2 As Date Dim approximateAge As Double dt = CDate(mtbDate..Student Solutions Manual (Page 36 of 211) 39.AddYears(1) numDays = DateDiff(DateInterval. dt.Year.

3 <= gpa) And (gpa < 3." End If If (3.Student Solutions Manual (Page 37 of 211) 43..Text) Dim honors As String = "" If gpa >= 3.9 Then honors = " summa cum laude." End If txtOutput.9) Then honors = " magna cum laude." End If If (3.) Handles btnDetermine." End If If (2 <= gpa) And (gpa < 3.6) Then honors = " cum laude. Private Sub btnDetermine_Click(.6 <= gpa) And (gpa < 3.Text = "You graduated" & honors End Sub .Click Dim gpa As Double = CDbl(txtGPA..3) Then honors = ".

Text = "two" End Select 21. 9. Select Case a Case 2 txtOutput. The equation has no real solutions.Text = "yes" Case Is < 5 txtOutput. Invalid 17. The equation has two solutions. Valid 15. 13.Text = "one" Case Is > 5 txtOutput. The equation has exactly one solution.75 3. Logic error: >= "Peach" should be >= "PEACH".Student Solutions Manual (Page 38 of 211) EXERCISES 4. Select Case a Case 1 txtOutput. Mesozoic Era Paleozoic Era ? 5. Should have a Case clause before the 4th line. Case nom = "Bob" should be Case "Bob" 11.Text = "no" End Select .3 1. The price is $3. 7. Syntax error: "ORANGE TO PEACH" should be "ORANGE" To "PEACH".75 The price is $3. Valid 19.

"..Text) 'Mask is 0 Select Case shapeNum Case 1 radius = CDbl(InputBox("Input the radius of the circle: ")) txtArea.Text = "Overcast" Case Else txtOutput.) Handles btnDescribe. Kite shapeNum = CInt(mtbSelection.Click Dim shapeNum As Integer Dim radius. width As Double 'Input choice of shape and its dimensions '1.Text = CStr(3... Private Sub btnCompute_Click(.Text = "Clear" Case 31 To 70 txtOutput.Focus() End Sub ." End Select End Sub 25. Parallelogram 3.Student Solutions Manual (Page 39 of 211) 23.Text = "Percentage must be between 0 and 100..Text = CStr((length * width) / 2) Case Else MessageBox. length.Click Dim percent As Double percent = CDbl(InputBox("Percentage of cloud cover:")) Select Case percent Case 0 To 30 txtOutput.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.141593 * radius ^ 2) Case 2 length = CDbl(InputBox("Input the length of the parallelogram: ")) height = CDbl(InputBox("Input the height of the parallelogram: ")) txtArea. height.Clear() End Select mtbSelection.Text = "Cloudy" Case 100 txtOutput.Show("Your choice is not valid.) Handles btnCompute. Private Sub btnDescribe_Click(. "Try Again. Circle 2.") mtbSelection.Text = "Partly cloudy" Case 71 To 99 txtOutput.

1 * amountRecovered Case Is <= 100000 payment = 7500 + 0.Click Dim score As Integer.Student Solutions Manual (Page 40 of 211) 27. Private Sub btnDescribe_Click(. letterGrade As String score = CInt(InputBox("What is the score?")) 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." End Sub .) Handles btnAssign. Private Sub btnAssign_Click(.01 * (amountRecovered .Text = "The amount given as reward is " & FormatCurrency(payment) & ".05 * (amountRecovered .Text = "The letter grade is " & letterGrade & "." End Sub 29.Click Dim amountRecovered..75000) Case Is > 100000 payment = 8750 + 0..100000) If payment > 50000 Then payment = 50000 End If End Select txtOutput.. payment As Double amountRecovered = CDbl(InputBox("How much was recovered?")) Select Case amountRecovered Case Is <= 75000 payment = 0..) Handles btnDetermine.

) Handles btnDisplay.Student Solutions Manual (Page 41 of 211) 31.Items." End Select Case "CLINTON" state = "Arkansas" trivia = "In college he did a good imitation of Elvis Presley.ToUpper Case "CARTER" state = "Georgia" trivia = "The only soft drink served in the Carter " & "White House was Coca-Cola.. state.Items.Items. Private Sub btnDisplay_Click(." Case "REAGAN" state = "California" trivia = "His secret service code name was Rawhide. whichBush As String pres = txtLastName.Click Dim pres.Text Select Case pres." Case "BUSH" state = "Texas" whichBush = InputBox("Are his middle initials HW or W?") Select Case whichBush.Clear() lstOutput.Add("President " & pres & "'s" & " home state was " & state & "." Case Else state = "" trivia = "" End Select If state <> "" Then lstOutput." Case "W" trivia = "He once owned the Texas Rangers baseball team." Case "OBAMA" state = "Illinois" trivia = "He was the eighth left-handed president.Add(trivia) End If End Sub .") lstOutput. trivia..ToUpper Case "HW" trivia = "He celebrated his 85th birthday by parachuting " & "out of an airplane.

Checked Then cost += 120 End If txtTotalCost..CheckedChanged If radDeluxe. RadioButton1.Checked Or radSuper. 17.Checked Then cost += 1000 Else 'Super model cost += 1500 End If If chkUpgradedVideo.4 1. radSuper. chkModem. 7. chkMemory.CheckedChanged. The radio button becomes (or remains) unselected. RadioButton2 is on and RadioButton1 is off.Student Solutions Manual (Page 42 of 211) EXERCISES 4. The word "Income" becomes the caption embedded in the top of GroupBox1. The CheckBox1 check box becomes (or remains) unchecked.Text = FormatCurrency(cost) Else MessageBox. Yes 13. If radDeluxe. The radio button’s caption becomes "Clear All".Checked = True 15.Show("You must first select a model!") End If End Sub .Checked Then cost += 30 End If If chkMemory. chkUpgradedVideo.. 3.) Handles _ radDeluxe. 9.Checked Then cost += 200 End If If chkModem. Private Sub CheckedChanged(.CheckedChanged.Text = "Yes" 11.Checked Then Dim cost As Double = 0 'Add amounts to the cost based upon selections.CheckedChanged. 5.CheckedChanged. CheckBox1.

Private Sub btnVote_Click(." ElseIf radCandidate2.) Handles btnClear.Checked = False End Sub .Text = "You voted for Nixon.Checked Then txtVote...Student Solutions Manual (Page 43 of 211) 19.Text = "You voted for Kennedy.) Handles btnVote..Checked Then txtVote." End If End Sub Private Sub btnClear_Click(..Click radCandidate1.Text = "You voted for neither.Checked = False radCandidate2.Click If radCandidate1." Else txtVote.

") Else MessageBox.Show("You must select a Major.Checked Or radSenior.Checked Or radJunior.Student Solutions Manual (Page 44 of 211) 21.Show("Information Processed") ElseIf Not majorSelected Then If Not yearSelected Then MessageBox.Click Dim majorSelected As Boolean Dim yearSelected As Boolean If lstMajors.") End If End Sub ..Show("You must select a Year.Checked Or radSoph.Checked) Then yearSelected = True Else yearSelected = False End If If majorSelected And yearSelected Then MessageBox. Private Sub btnRecord_Click(.") End If Else MessageBox..) Handles btnRecord.Text = "" Then majorSelected = False Else majorSelected = True End If If (radFrosh.Show("You must select a Major and a Year.

CheckedChanged Dim count As Integer = 0 If chkSenior.CheckedChanged..) Handles _ chkSenior.Checked Then count += 1 End If If chkBlind. chkBlind.Checked Then count += 1 End If If chkSpouse. chkSpouseBlind.Student Solutions Manual (Page 45 of 211) 23.CheckedChanged.CheckedChanged. chkSpouse.Checked Then count += 1 End If txtOutput.Text = CStr(count) End Sub . Private Sub CheckedChanged(..Checked Then count += 1 End If If chkSpouseBlind.

Click Dim fee As Double = 0 If radAdult.Show("You must select a membership category.Checked Then numExtras += 1 End If If chkLocker.Checked Then numExtras += 1 End If If radAdult.. Private Sub btnCalculate_Click(.Text = FormatCurrency(fee) Else MessageBox.Checked Then fee = 100 + numExtras * 25 Else fee = 75 + numExtras * 25 End If txtFee.Student Solutions Manual (Page 46 of 211) 25.Checked Or radSenior..Checked Then numExtras += 1 End If If chkLaundry.Checked Then Dim numExtras As Integer = 0 If chkTennis.) Handles btnCalculate.") End If End Sub .

Items.) Handles btnDetermine.Text) Dim height As Double = CDbl(txtHeight. The function header should end with "As String".Round((703 * w) / (h ^ 2)) End Function ..) Handles btnCalculate.Text) txtBMI.Click Dim weight As Double = CDbl(txtWeight. Private Sub btnDetermine_Click(. 7. The population will double in 24 years. age before beauty 11.. height) & " square centimeters") lstOutput. height)) End Sub Function BMI(ByVal w As Double. Return 6. ByVal ht As Double) As Double 'Calculate surface area of a cylindrical can..1 1. 203 3. height As Double lstOutput.Click Dim radius. Your state income tax is $150. ByVal h As Double) As Double Return Math.Add("requires " & TinArea(radius.Text = CStr(BMI(weight. 5.Student Solutions Manual (Page 47 of 211) CHAPTER 5 EXERCISES 5. 9.283 * (radius ^ 2 + radius * ht) End Function 15. 13.Add("of tin.Add("A can of radius " & radius & " and height " & height) lstOutput. not "As Integer"..00.") End Sub Function TinArea(ByVal radius As Double. Private Sub btnCalculate_Click(.Items.Items.Items.Clear() radius = CDbl(InputBox("Enter radius of can (in centimeters):")) height = CDbl(InputBox("Enter height of can (in centimeters):")) lstOutput. 27 is an odd number.

Click Dim popcorn..) Handles btnDetermine." End Sub Function Ceil(ByVal x As Double) As Double Return -Int(-x) End Function Function Cost(ByVal weight As Double) As Double Return 0.1) End Function . Private Sub btnDetermine_Click(.) Handles btnCompute. bucket.Click Dim weight As Double weight = CDbl(txtWeight.05 + 0. price As Double 'amount in dollars popcorn = CDbl(InputBox("What is the cost of the popcorn kernels?")) butter = CDbl(InputBox("What is the cost of the butter substitute?")) bucket = CDbl(InputBox("What is the cost of the bucket?")) price = CDbl(InputBox("What is the sale price?")) txtProfit.1 * Ceil(weight .Text) txtOutput. ByVal butter As Double. ByVal price As Double) As Double 'Calculate the profit on a bucket of popcorn Return price . butter.Text = "The cost of mailing the letter was " & FormatCurrency(Cost(weight)) & ". Private Sub btnCompute_Click(. price)) End Sub Function Profit(ByVal popcorn As Double.. bucket.Text = FormatCurrency(Profit(popcorn. butter.Student Solutions Manual (Page 48 of 211) 17..(popcorn + butter + bucket) End Function 19.. ByVal bucket As Double.

) Handles btnAddressNGreet.") End Sub Function LastName(ByVal name As String) As String Dim spacePos As Integer spacePos = name.Click If IsLeapYear(CInt(mtbYear.Text = mtbYear..Click Dim name As String name = InputBox("Enter the senator's name:") lstOutput.Add("") lstOutput. DC 20001") lstOutput..Text & " is a leap year.Add("The Honorable " & name) lstOutput.Items." Else txtOutput. date1.Add("Dear Senator " & LastName(name) & ".Text = mtbYear.Day.Student Solutions Manual (Page 49 of 211) 21.Items..Items." End If End Sub Function IsLeapYear(ByVal 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.) Handles btnDetermine.IndexOf(" ") Return name.Add("Washington.Add("United States Senate") lstOutput.Text & " is not a leap year.. Private Sub btnDetermine_Click(.Items. Private Sub btnAddressNGreet_Click(.Text)) Then 'mask is 0000 txtOutput.Items.Substring(spacePos + 1) End Function 23. date2) = 366 Then Return True Else Return False End If End Function .

24 blackbirds baked in a pie." End Sub 27. it cannot be used as the name of a Sub procedure..Items. 7. It was the worst of times. is " & ht & " feet. 9..00 19. Private Sub btnDisplay_Click(. It was the best of times. 362) Tallest("pine".00 Shipping cost: $15.00 Total cost: $265. divorced beheaded died divorced beheaded survived 13. ByVal ht As Double) lstBox. Private Sub btnDisplay_Click(. 17. You look dashing in blue. The first 6 letters are Visual.. but no argument in the statement calling the Sub procedure. There is a parameter in the Sub procedure. 21.Click Dim num As Integer = 7 Lucky(num) End Sub Sub Lucky(ByVal num As Integer) txtOutput.") End Sub .Click Tallest("redwood".2 1. 25. 23.Text = num & " is a lucky number..) Handles btnDisplay.Student Solutions Manual (Page 50 of 211) EXERCISES 5. 1440 minutes in a day 3. You passed with a grade of 92.) Handles btnDisplay. 223) End Sub Sub Tallest(ByVal tree As String. Cost: $250. Why do clocks run clockwise? Because they were invented in the northern hemisphere where sundials go clockwise.Add("The tallest " & tree & " tree in the U. Since Handles is a keyword.S. 88 keys on a piano 5. 15. 11.

"computer science") End Sub Sub DisplaySource() Dim phrase As String phrase = "According to a 2008 survey of college freshmen" & " taken by" lstOutput.Click Dim num As Double num = CDbl(txtBox.") End Sub 31..Items.") End Sub .0.Add(phrase & (num * num) & ".") End Sub Sub Product(ByVal num As Double) Dim phrase As String phrase = "The product of your favorite number with itself is " lstOutput..Items. Private Sub btnDisplay_Click(.Add(percentOfStudents & " percent said they intend to major in " & field & ".7..Items.Text) Sum(num) Product(num) End Sub Sub Sum(ByVal num As Double) Dim phrase As String phrase = "The sum of your favorite number with itself is " lstOutput..Student Solutions Manual (Page 51 of 211) 29. ByVal field As String) lstOutput.Click DisplaySource() Majors(16.Add("the Higher Education Research Institute:") End Sub Sub Majors(ByVal percentOfStudents As Double. Private Sub btnDisplay_Click(.Add(phrase & (num + num) & ".Items.) Handles btnDisplay.Add(phrase) lstOutput.Items.) Handles btnDisplay. "business") Majors(1.

and a " & sound & " " & sound & " there. there a " & sound & ". everywhere a " & sound & " " & sound & ". Eyi eyi oh.Click ShowVerse("lamb".") lstOutput.") lstOutput. "blink") End Sub Sub ShowVerse(ByVal animal As String.Items.Student Solutions Manual (Page 52 of 211) 33.Add("") End Sub .Add("Old McDonald had a farm.Add("And on his farm he had a " & animal & ". "baa") ShowVerse("duck".") lstOutput.Items.Add("Here a " & sound & ". Eyi eyi oh.") lstOutput.Items.Items.Add("Old McDonald had a farm.. Eyi eyi oh.Items..) Handles btnDisplay.Add("With a " & sound & " " & sound & " here. "quack") ShowVerse("firefly". ByVal sound As String) 'Display a verse from Old McDonald Had a Farm lstOutput. Private Sub btnDisplay_Click(.") lstOutput.Items.

Text) Dim grade3 As Double = CDbl(txtGrade3.Text) DisplayHighestTwo(grade1. Private Sub btnDetermine_Click(. grade2. second As Double first = Max(grade1.) Handles btnDetermine.Text = "The highest two grades are " & first & " and " & second & ". ByVal grade2 As Double. grade2) If first = grade1 Then second = Max(grade2.. grade3) End Sub Sub DisplayHighestTwo(ByVal grade1 As Double.Text) Dim grade2 As Double = CDbl(txtGrade2.. grade3) End If txtOutput.Click Dim grade1 As Double = CDbl(txtGrade1. ByVal num2 As Double) As Double If num1 <= num2 Then Return num2 Else Return num1 End If End Function . grade3) Else second = Max(grade1." End Sub Function Max(ByVal num1 As Double. ByVal grade3 As Double) Dim first.Student Solutions Manual (Page 53 of 211) 35.

Text Dim word2 = txtWord2.Click Dim word1 = txtWord1.Student Solutions Manual (Page 54 of 211) 37.Add(second) End Sub . Private Sub btnAlphabetize_Click(. word2) End Sub Sub DisplayWords(ByVal word1 As String.Items.Items. second As String If word1 <= word2 Then first = word1 second = word2 Else first = word2 second = word1 End If lstOutput.Text DisplayWords(word1.. ByVal word2 As String) Dim first..Add(first) lstOutput.) Handles btnAlphabetize.

5. Gabriel was born in the year 1980. newSalary As Double) salary for " & firstName & " " & lastName & " & FormatCurrency(newSalary) & ". ByVal lastName As String. Private Sub btnDisplay_Click(. newSalary As Double InputData(firstName. ByRef salary As Double) firstName = txtFirstName. salary) newSalary = RaisedSalary(salary) DisplayOutput(firstName. lastName. 7. purchase cancelled.Click Dim firstName As String = "" Dim lastName As String = "" Dim salary. The second click also produces the message "Insufficient inventory.. 3.Student Solutions Manual (Page 55 of 211) EXERCISES 5.05 * salary Else Return salary + 2000 + 0.Text) End Sub Function RaisedSalary(ByVal salary As Double) As Double If salary <= 40000 Then Return 1." .Text salary = CDbl(txtCurrentSalary. Current inventory: 2 is displayed both times the button is clicked. sum = 4 difference = 2 11. ByRef lastName As String.") 9.3 1.. newSalary) End Sub Sub InputData(ByRef firstName As String. lastName. The state flower of Alaska is the Forget Me Not.Text lastName = txtLastName.02 * (salary . The first 3 letters of EDUCATION are EDU.40000) End If End Function Sub DisplayOutput(ByVal ByVal txtOutput.) Handles btnDisplay.Text = "New " is End Sub firstName As String.

Private Sub btnCalculate_Click(.Text = FormatCurrency(endBalance) End Sub . ByRef begBalance As Double) annualRateOfInterest = CDbl(txtAnnualRateOfInterest..Text) begBalance = CDbl(txtBegBalance. begBalance As Double Dim intForMonth. ByRef redOfPrincipal As Double. ByVal endBalance) txtIntForMonth. monthlyPayment.Student Solutions Manual (Page 56 of 211) 13.Text) monthlyPayment = CDbl(txtMonthlyPayment.. redOfPrincipal. redOfPrincipal. ByRef endBalance As Double) Dim monthlyRateOfInterest As Double = annualRateOfInterest / 12 intForMonth = (monthlyRateOfInterest / 100) * begBalance redOfPrincipal = monthlyPayment . ByVal redOfPrincipal.Click Dim annualRateOfInterest.Text = FormatCurrency(intForMonth) txtRedOfPrincipal. monthlyPayment. redOfPrincipal. endBalance) DisplayData(intForMonth. begBalance. ByRef intForMonth As Double. ByRef monthlyPayment As Double.Text) End Sub Sub Calculate(ByVal annualRateOfInterest As Double. ByVal begBalance As Double.Text = FormatCurrency(redOfPrincipal) txtEndBalance. begBalance) Calculate(annualRateOfInterest. ByVal monthlyPayment As Double. monthlyPayment. intForMonth.) Handles btnCalculate.redOfPrincipal End Sub Sub DisplayData(ByVal intForMonth. endBalance As Double InputData(annualRateOfInterest.intForMonth endBalance = begBalance . endBalance) End Sub Sub InputData(ByRef annualRateOfInterest As Double.

(To end the program.) 9.Add(name) num +=1 'Add 1 to value of num.1 1.Student Solutions Manual (Page 57 of 211) CHAPTER 6 EXERCISES 6. Until name = "" 17. Loop End Sub 11. Do and Loop are interchanged 15. 10 5.. Private Sub btnDisplay_Click(. Dim name As String. Until (a <= 1) Or (a >= 3) 19. num As Integer = 0 Do While num < 3 name = InputBox("Enter a name:") lstOutput. While n = 0 21.. 18 3. While num >= 7 13. click on the Stop Debugging button on the Toolbar.) Handles btnDisplay.Click 'Request and display three names. Maximum number: 7 7. Until response <> "Y" .Items. Infinite loop.

Show("That word does not contain both r and n.Click Dim word As String = "" Dim rPlace.IndexOf("r") nPlace = word.Items... nPlace As Integer Do InputWord(word) rPlace = word.".) Handles btnLocate.Student Solutions Manual (Page 58 of 211) 23.IndexOf("n") If (rPlace = -1) Or (nPlace = -1) Then MessageBox.Add(" " & celsius & " " & Fahrenheit(celsius)) celsius += 5 Loop End Sub Function Fahrenheit(ByVal celsius As Double) As Double 'Convert Celsius to Fahrenheit Return (9 / 5) * celsius + 32 End Function 25.) Handles btnDisplay.. nPlace) End Sub . Private Sub btnLocate_Click(.Add("Celsius Fahrenheit") Do While celsius <= 95 lstOutput. "") End If Loop Until (rPlace > -1) And (nPlace > -1) ShowFirst(rPlace. Private Sub btnDisplay_Click(.Click Dim celsius As Double = 10 lstOutput.Items..

r or n." 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. " & "Enter -1 to terminate entering numbers.Text = "The letter r is first. ByVal nPlace As Integer) 'Tell which letter..Text = CStr(max .min) Else MessageBox.Click Dim num.Text = "The letter n is first.Student Solutions Manual (Page 59 of 211) Sub InputWord(ByRef word As String) Dim prompt As String prompt = "Enter a word containing the letters 'r' and 'n'. "Enter Word") End Sub Sub ShowFirst(ByVal rPlace As Integer. comes first.Show("No numbers were entered.." End If End Sub 27." Else txtOutput.") End If End Sub .) Handles btnCompute." word = InputBox(prompt. max. If nPlace > rPlace Then txtOutput. Private Sub btnCompute_Click(. min As Double Dim count As Double = 0 Dim prompt As String = "Enter a nonnegative number.

. ByRef n As Integer) = CInt(txtM..Text) = CInt(txtN.) Handles btnDetermine.Click Dim m.) Handles btnDetermine.) Handles btnCompute... Private Sub btnCompute_Click(.Text = months & " months" End Sub .Text = age & " years old" End Sub 33.Text) Sub 31.Click Dim age As Integer = 1 Do While 1980 + age <> age ^ 2 age += 1 Loop txtOutput.005 Dim loanAmount As Double = 15000 Dim months As Integer = 0 Dim balance As Double = loanAmount Do Until balance < loanAmount / 2 balance = (1 + INTEREST_PER_MONTH) * balance . t As Integer InputIntegers(m.Student Solutions Manual (Page 60 of 211) 29. Private Sub btnDetermine_Click(.Click Dim amount As Double = 100 Dim yrs As Integer = 0 Do Until amount < 1 amount = 0. Private Sub btnFind_Click(..) Handles btnFind.Text = yrs & " years" End Sub 35.290 months += 1 Loop txtOutput.Click Const INTEREST_PER_MONTH As Double = 0. Private Sub btnDetermine_Click(. n) Do While n <> 0 t = n n = m Mod n 'Remainder after m is divided by n m = t Loop txtOutput.5 * amount yrs += 28 Loop txtOutput. n...Text = CStr(m) End Sub Sub m n End InputIntegers(ByRef m As Integer..

. Private Sub btnDetermine_Click(.003 * balance ..) Handles btnDetermine.Click Dim months As Integer = 0 Dim balance As Double = 10000 Do Until balance < 600 balance = 1.600 months += 1 Loop txtOutput.Student Solutions Manual (Page 61 of 211) 37.Text = months & " months. " & FormatCurrency(balance) End Sub .

The For ...) Handles btnDisplay.Add(i) Next End Sub 19.Click Dim sum As Double = 0..Text = FormatNumber(sum / 5. 2) End Sub .. 15. Next loop will not execute since 20 is greater than 0.) Handles btnFind. Private Sub btndisplay_Click(..Items. •••••••••• 11. Pass Pass Pass Pass #1 #2 #3 #4 3.Student Solutions Manual (Page 62 of 211) EXERCISES 6.) Handles btndisplay. The loop is never executed since 25 is greater than 1 and the step is negative.. Private Sub btnFind_Click(. 5 6 7 7...Click For num As Integer = 1 To 9 Step 2 lstBox. Private Sub btnDisplay_Click(.Click For i As Integer = 2 To 100 Step 2 lstOutput. You must add Step 1 to the end of the For statement.2 1. num as Double = 0 For i As Integer = 1 To 5 num = CDbl(InputBox("Enter #" & i)) sum += num Next txtAverage.Items. 4 5. 2 4 6 8 Who do we appreciate? 9.Add(num) Next End Sub 17. 13.

Private Sub btnCompute_Click(. age As Integer.Click Dim PERCENT_RAISE As Double = 0.Text age = CInt(txtAge.Text) For i As Integer = age To 64 earnings += salary salary = salary + (PERCENT_RAISE * salary) Next txtOutput. salary As Double Dim earnings As Double = 0 name = txtName..Text = name & " will earn about " & FormatCurrency(earnings.Items.Text = FormatNumber(sum. 5) End Sub 23.05 Dim name As String..) Handles btnCompute.Student Solutions Manual (Page 63 of 211) 21....Text) salary = CDbl(txtSalary.." End Sub .Click Dim value As Double = 20000 For i As Integer = 1 To 5 value = 0. Private Sub btnCalculate_Click(.) Handles btnCompute. 0) & ".Add(i & ": " & FormatCurrency(value)) Next End Sub 25.) Handles btnCalculate.85 * value lstOutput. Private Sub btnCompute_Click(.Click Dim sum As Double = 0 For denominator As Double = 1 To 100 sum += 1 / denominator Next txtOutput.

Clear() InputBounds(lower.5 * height .. upper As Integer lstWeightTable. 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(ByVal lower As Integer. 1)) Next End Sub .Items. ByVal upper As Integer) lstWeightTable. upper) ShowWeights(lower.Items.Add(" " & "WEIGHT " & " " & "WEIGHT") lstWeightTable.Click Dim lower.Add(height & " " & FormatNumber(IdealWoman(height). 1) & " " & FormatNumber(IdealMan(height)..) Handles _ btnComputeIdealWeights.Items.108 End Function Sub InputBounds(ByRef lower As Integer.Items. upper) End Sub Function IdealMan(ByVal height As Integer) As Double 'Compute the ideal weight of a man given his height Return 4 * height . Private Sub btnComputeIdealWeights_Click(.128 End Function Function IdealWoman(ByVal height As Integer) As Double 'Compute the ideal weight of a woman given her height Return 3.Add("HEIGHT" & " " & "WOMEN " & " " & "MEN") For height As Integer = lower To upper lstWeightTable.Student Solutions Manual (Page 64 of 211) 27.

Items.Student Solutions Manual (Page 65 of 211) 29.Click Const DECAY_RATE As Double = 0.) Handles btnAnalyze.Click Dim balance As Double = 0 Dim yr As Integer = 2010 For i As Integer = 1 To 120 balance = (1.") End Sub . Private Sub btnDisplay_Click(.Add(FormatNumber(grams) & " grams remain after 5 years.Add("Beginning with 10 grams of cobalt 60.DECAY_RATE) * grams Next lstOutput.Items...0025) * balance + 100 If i Mod 12 = 0 Then lstOutput.Add(yr & " " & FormatCurrency(balance)) yr += 1 End If Next End Sub 31. Private Sub btnAnalyze_Click(.12 Dim grams As Double grams = 10 For yearNum As Integer = 1 To 5 grams = (1 ..) Handles btnDisplay.") lstOutput..Items.

Click Dim price.Items. Else lstOutput.. opt2 As Double opt1 = Option1() opt2 = Option2() lstOutput.Add("Option 1 = " & FormatCurrency(opt1)) lstOutput.Add("Options pay the same..Items.Add("Option 2 pays better..Items.Items.") End If End Sub Function Option1() As Double 'Compute the total salary for 10 days.Add("Option 1 pays better.") ElseIf opt1 = opt2 lstOutput. quantity As Double lstOutput..Click 'Compare salaries Dim opt1.Add("Option 2 = " & FormatCurrency(opt2)) If opt1 > opt2 Then lstOutput.) Handles btnAnalyzeOptions.Clear() quantity = 80 'current crop of soybeans in millions of bushels lstOutput.Items. Private Sub btnDisplay_Click(.Items.Add("YEAR" & " " & "QUANTITY" & " " & "PRICE") For yr As Integer = 2010 To 2020 price = 20 .10 Next End Sub 35.Items.Add(yr & " " & FormatNumber(quantity) & " " & FormatCurrency(price)) quantity = 5 * price .) Handles btnDisplay.0.Items. '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 .Student Solutions Manual (Page 66 of 211) 33.1 * quantity lstOutput. Private Sub btnAnalyzeOptions_Click(.

Click Dim dt As Date = CDate("#1/1/" & mtbYear.Items. Private Sub btnDetermine_Click(.StartsWith("Tuesday") Then Return d.. DateFormat.LongDate).AddMonths(i) lstOutput.) Handles btnDetermine..AddDays(i) End If Next End Function .Text & "#") Dim d As Date For i As Integer = 0 To 11 d = dt.Student Solutions Manual (Page 67 of 211) Function Option2() As Double 'Compute the total salary for 10 days.Add(FirstTuesday(d)) Next End Sub Function FirstTuesday(ByVal d As Date) As Date For i As Integer = 0 To 6 If FormatDateTime(d.AddDays(i). daySalary As Integer = 1 For i As Integer = 1 To 10 sum += daySalary daySalary = 2 * daySalary Next Return sum End Function 37. 'starting at $1 and doubling each day Dim sum As Integer = 0.

70 11.Items..Items(i)) = "USC" Then numWon += 1 End If Next txtOutput..3 1. Tchaikovsky 5.Clear() For i As Integer = 0 To lstBox.Click Dim numWon As Integer = 0 For i As Integer = 0 To lstBox.Student Solutions Manual (Page 68 of 211) EXERCISES 6..Items.) Handles btnCount..Text = "YES" Exit For End If Next If txtOutput.Text txtOutput.Text = "" Then txtOutput.) Handles btnDetermine. 80 9.1 If CStr(lstBox. 300 13. Private Sub btnCount_Click(. Mozart 3.Items(i)) = college Then txtOutput. 3 7.Click Dim college As String = txtCollege. Private Sub btnCount_Click(.Text = "NO" End If End Sub or .Count .1 If CStr(lstBox.Count .Text = CStr(numWon) End Sub 15.

Items..Items.) Handles btnDetermine.Count .Items(i)) = college Then found = True End If i += 1 Loop If found Then txtOutput..Text = "YES" Else txtOutput..Count) If CStr(lstBox.Click Dim college As String = txtCollege.) Handles btnReverse..Items.Click Dim highestIndex As Integer = lstBox.Student Solutions Manual (Page 69 of 211) Private Sub btnCount_Click(.Text Dim i As Integer = 0 Dim found As Boolean = False Do Until (found = True) Or (i = lstBox.1 For i As Integer = highestIndex To 0 Step -1 lstBox2. Private Sub btnReverse_Click(.Items(i)) Next End Sub .Text = "NO" End If End Sub 17.Add(lstBox.

Count .) Handles btnAlphabetize..Items(i)) Next End Sub 21.Add(state) End If Next End Sub .Student Solutions Manual (Page 70 of 211) 19.Sorted = True Dim highestIndex As Integer = lstBox.1 For i As Integer = 0 To highestIndex lstBox2. Private Sub btnDisplay_Click(.Add(lstBox.Items.Click Dim highestIndex As Integer = lstBox.Length = 7 Then lstBox2.Count ..Items.Items(i)) If state.Items...Click lstBox2.1 Dim state As String For i As Integer = 0 To highestIndex state = CStr(lstBox.Items. Private Sub btnAlphabetize_Click(.) Handles btnDisplay.

) Handles btnDisplay.Click Dim highestIndex As Integer = lstBox.Items(i)) If state.StartsWith("New") Then txtOutput.Length > maxLength Then maxLength = state..Length End If Next For i As Integer = 0 To highestIndex state = CStr(lstBox.Items(i)) If state.) Handles btnDetermine.Length = maxLength Then lstBox2.Add(state) End If Next End Sub .Items(i)) If state.Count .Items. Private Sub btnDisplay_Click(..1 Dim maxLength As Integer = 0 Dim state As String For i As Integer = 0 To highestIndex state = CStr(lstBox..1 Dim state As String For i As Integer = 0 To highestIndex state = CStr(lstBox.Items.Count .Student Solutions Manual (Page 71 of 211) 23..Items. Private Sub btnDetermine_Click(.Text = state Exit For End If Next End Sub 25.Click Dim highestIndex As Integer = lstBox.

Count .Items.Substring(i.Length For i As Integer = 0 To (numLetters ..1 Dim state As String For i As Integer = 0 To highestIndex state = CStr(lstBox.Click Dim highestIndex As Integer = lstBox.ToUpper Dim letter As String Dim numLetters As Integer = word.1) letter = word.Items(i)) If NumberOfVowels(state) = 4 Then lstBox2. Private Sub btnDetermine_Click(.) Handles btnDetermine.Add(state) End If Next End Sub Function NumberOfVowels(ByVal word As String) As Integer Dim numVowels As Integer = 0 word = word..Student Solutions Manual (Page 72 of 211) 27.Items. 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 .

Items.Text = CStr(maxNumOfVowels) End Sub Function NumberOfVowels(ByVal word As String) As Integer Dim numVowels As Integer = 0 word = word. 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.Items(0)) End Sub .Text = CStr(lstBox..Click txtOutput.ToUpper Dim letter As String Dim numLetters As Integer = word.Items(i)) If NumberOfVowels(state) > maxNumOfVowels Then maxNumOfVowels = NumberOfVowels(state) End If Next txtOutput.. Private Sub btnDisplay_Click(.1 Dim state As String Dim maxNumOfVowels = 0 For i As Integer = 0 To highestIndex state = CStr(lstBox.Click Dim highestIndex As Integer = lstBox.Student Solutions Manual (Page 73 of 211) 29.) Handles btnDetermine.) Handles btnDisplay.1) letter = word.Length For i As Integer = 0 To (numLetters ...Substring(i. Private Sub btnDetermine_Click(.Count .

Click txtOutput.Count > 0 Then For i As Integer = 0 To lstGrades.Text = FormatNumber(sum / lstGrades. Private Sub btnRecord_Click(.Items.") End If txtAverage..Items.Click lstGrades..) Handles btnDisplay.) Handles btnRecord.Focus() End Sub Private Sub btnCalculate_Click(.Click Dim sum As Double = 0 Dim minGrade As Double = 100 If lstGrades.Text) txtGrade.Items(i)) End If Next Else MessageBox. 2) txtLowest.1 sum += CDbl(lstGrades..Text = CStr(minGrade) End Sub ..Student Solutions Manual (Page 74 of 211) 33.) Handles btnCalculate.Items(4)) End Sub 35.Count .Text = CStr(lstBox.Show("You must first enter some grades..Items(i)) < minGrade Then minGrade = CDbl(lstGrades.Add(txtGrade.Clear() txtGrade.Items.Items(i)) If CDbl(lstGrades. Private Sub btnDisplay_Click(..Count.Items.

Student Solutions Manual (Page 75 of 211)
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 = FormatNumber(sum / lstGrades.Items.Count, 2) txtRange.Text = CStr(maxGrade - minGrade) End Sub

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

Student Solutions Manual (Page 77 of 211)

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

9. You have a trio.

11. Your average is 80 15. one,two,three

13. Slumdog Millionaire won in 2009 17. 2 even numbers

19. Pearl Harbor: 1941 23. 6 words begin with a vowel

21. contains a 19th-century date 25. 4 6 2 27. (a) (b) (c) (d) (e) (f) (g) 29. (a) (b) (c) (d) (e) (f) (g) Superior Erie Huron Superior 5 Ontario 3 6.5 0.7 3.5 1.3 6 1.1 3

(last name in alphabetical order) (first name in alphabetical order) (first name in the array) (last name in the array) (number of names in the array) (second name in the array) (first array subscript whose element is Erie)

(greatest population of a New England state) (least population of a New England state) (first population in the array) (last population in the array) (number of numbers in the array) (fourth population in the array) (first array subscript whose element is 1.1)

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

Student Solutions Manual (Page 78 of 211)
33. Function Task(ByVal 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(ByVal 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(ByVal 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) 41.

should be changed to nums()

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)

Add(dups(i)) Next End If End Sub ..Student Solutions Manual (Page 79 of 211) 45.. Private Sub btnDisplay_Click(.Items.Click Dim numStr() As String = IO.Items.1 nums(i) = CInt(numStr(i)) Next lstOutput.Count .Add("No duplicates.Count .Add("Sum of integers in the file: " & nums. names(i)) = -1) Then dups(n) = names(i) n += 1 End If Next If n = 0 Then lstOutput.Count .) Handles btnDetermine.Items.txt") Dim nums(numStr..ReadAllLines("Numbers.) Handles btnDisplay.File. Private Sub btnDetermine_Click(.File.Count) lstOutput.1) As String Dim n As Integer = 0 'index for dups For i As Integer = 0 To names.Add("Number of integers in the file: " & nums.1 lstOutput.2 If (names(i + 1) = names(i)) And (Array.txt") Dim dups(names.") Else For i As Integer = 0 To n .1) As Integer For i As Integer = 1 To nums.Click Dim names() As String = IO.Items..ReadAllLines("Names2.Count .IndexOf(dups.Sum) End Sub 47.

Add(" " & i & " " & freq(i)) Next End Sub 51. Private Sub btnDisplay_Click(.Items.File.1 freq(CInt(strDigits(i))) += 1 Next lstOutput.Count .Add("Digit Frequency") For i As Integer = 0 To 9 lstOutput..txt") Dim freq(9) As Integer For i As Integer = 0 To strDigits. Function Sum(ByVal nums() As Integer) As Integer Dim total As Integer = 0 For i As Integer = 1 To nums.1 Step 2 total += nums(i) Next Return total End Function .Student Solutions Manual (Page 80 of 211) 49.Items..ReadAllLines("Digits.) Handles btnDisplay.Count .Click Dim strDigits() As String = IO.

Items. large.Add(small & " Small eggs") If lightest <> 100 Then lstOutput.txt") Dim eggs(strEggs..) Handles btnProcessEggs.Items.Items. med.Items.1 eggs(i) = CDbl(strEggs(i)) Next For i As Integer = 0 To eggs.File. 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.5 'too small & cannot be sold Case Is < 1.Add(xLarge & " Extra Large eggs") lstOutput.75 small += 1 Case Is < 2 med += 1 Case Is < 2.Add("Lightest egg: " & lightest & " ounces") lstOutput.Add("File is empty") End If End Sub .Count . lightest. xLarge. Private Sub btnProcessEggs_Click(.Count . ounces As Double Dim jumbo.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 xLarge += 1 Case Else jumbo += 1 End Select Next lstOutput.Items.1) As Double For i As Integer = 0 To eggs.Add(jumbo & " Jumbo eggs") lstOutput.25 large += 1 Case Is < 2.Student Solutions Manual (Page 81 of 211) 53.Items.Add(large & " Large eggs") lstOutput.Click Dim heaviest.Add(med & " Medium eggs") lstOutput..Count .Items.Items.ReadAllLines("Eggs.Items.Add("Heaviest egg: " & heaviest & " ounces") Else lstOutput.Clear() lstOutput.

Click Dim letter As String = mtbLetter.Click Dim letter As String = mtbLetter..Clear() For Each hue As String In SmallerArray(letter) lstColors.txt") Private Sub btnDisplay_Click(. Dim colors() As String = IO. Dim colors() As String = IO.Student Solutions Manual (Page 82 of 211) 55.Items.1) As String Dim counter As Integer = 0 For Each hue As String In colors If hue.File.Clear() For Each hue As String In colors If hue..Count .) Handles btnDisplay.ReadAllLines("Colors.StartsWith(letter) Then lstColors.Items.ToUpper 'mask L lstColors.File.txt") Private Sub btnDisplay_Click(.) Handles btnDisplay.Add(hue) End If Next End Sub 57.Items.Text.Items.1) Return smArray End Function ...Text.StartsWith(letter) Then smArray(counter) = hue counter += 1 End If Next ReDim Preserve smArray(counter .Add(hue) Next End Sub Function SmallerArray(ByVal letter As String) As String() Dim smArray(colors.ReadAllLines("Colors.ToUpper 'mask is L lstColors.

Sum) End Sub 61. Private Sub btnDisplay_Click(.Items.".1) lstOutput.Items.Click 'Display average of grades and the number of above average grades Dim temp() As Integer = grades ReDim Preserve temp(numGrades .Focus() End If End Sub Private Sub btnDisplay_Click(.Items.Click 'Add a score to the array 'If no more room.Clear() txtScore.Add("Total number of words: " & numWords.") lstOutput.") Else grades(numGrades) = CInt(txtScore.Click Dim lines() As String = IO. "No more room.Clear() lstOutput.Add("The average grade is " & FormatNumber(temp.Student Solutions Manual (Page 83 of 211) 59.Add("Average number of words per line: " & FormatNumber(numWords.1 Dim numWords(n) As Integer For i As Integer = 0 To n numWords(i) = lines(i).Split(" "c).) Handles btnDisplay.Items.") End Sub . 2) & ". then display error message. 2)) lstOutput.) Handles btnRecord.Text) numGrades += 1 lstOutput....File.Clear() txtScore.Count Next lstOutput.Add(NumAboveAverage(temp) & " students scored above the average..txt") Dim n = lines.Items. Dim grades(99) As Integer Dim numGrades As Integer 'stores grades 'number of grades stored Private Sub btnRecord_Click(.. If numGrades >= 100 Then MessageBox.Items.Show("100 scores have been entered..) Handles btnDisplay.Count .Average.ReadAllLines("Sonnet.Average.

ToUpper Then Return False 'If ending does not match beginning of next word.Substring(0.2). removing commas first words = txtSentence.Length ..Text = "This sentence is not a chain-link sentence.ToUpper If ending <> words(i + 1). ending As String 'Split the sentence into words.Substring(words(i).Text.Split(" "c) For i As Integer = 0 To words.Text = "This sentence is a chain-link sentence.) Handles btnDisplay.Length < 2) Then Return False 'If any word has is less than two letters." End If End Sub Function IsChainLink(ByVal sentence As String) As Boolean 'Analyze a sentence to see whether it is a chain-link sentence." Else txtOutput. End If ending = words(i).".Student Solutions Manual (Page 84 of 211) Function NumAboveAverage(ByVal temp() As Integer) As Integer 'Count the number of scores above the average grade Dim avg As Double = temp. End Function .Count .Average Dim num As Integer = 0 For Each grade In temp If grade > avg Then num += 1 End If Next Return num End Function 63. "").Length < 2) Or (words(i + 1). Private Sub btnDisplay_Click(.Click If IsChainLink(txtSentence.2 If (words(i).Text) Then txtOutput.. End If Next Return True 'If all words are ok. then it is a chain-link sentence.Replace(". 2). Dim words().

" Else txtOutput.Text = query." End If End Sub 23..txt") Dim query = From yr In dates Where (CInt(yr) >= 1800) And (CInt(yr) <= 1899) Select yr If query.ReadAllLines("Dates.Click Dim dates() As String = IO. 103 9. 21} Dim query = From num In nums Where num Mod 2 = 0 Select num txtOutput. 6 7..Text = "contains a 19th century date.) Handles btnDisplay.Student Solutions Manual (Page 85 of 211) EXERCISES 7.Click Dim nums() As Integer = {3. Private Sub btnDisplay_Click(. 5 7 3.) Handles btnDisplay.IndexOf(nums. 4} Dim query = From num In nums Order By Array. 8 11.2 1. 6. 10. 8...Count > 0 Then txtOutput. num) Descending For Each num As Integer In query lstOutput..count & " even numbers" End Sub 21.Add(num) Next End Sub .Text = "does not contains a 19th century date. 5. going offer can't 5.) Handles btnDisplay.File.. 15 12 15. 3 students have a grade of 100 13.Items. Private Sub btnDisplay_Click(.Click Dim nums() As Integer = {2. Private Sub btnDisplay_Click(. The average after dropping the lowest grade is 80 17. 37 is a prime number 19.

Click 'Display the number of Super Bowls won by the team in the text box Dim query = From team In teamNames Where team.File.) Handles btnDisplay.Count) End Sub 7.txt") Where CInt(grade) > avg Select grade txtAverage.ReadAllLines("SBWinners.Text.Student Solutions Manual (Page 86 of 211) 25.File.2 Exercise 29 29.Add(team) Next End Sub 27.Click Dim teams() As String = IO. Dim teamNames() As String = IO.ReadAllLines("Final.) Handles btnDisplay.txt") Select CInt(grade) Dim avg As Double = query1.Items.ToUpper Select team txtNumWon.ReadAllLines("SBWinners..Text = CStr(query..2 Exercise 27 7.txt") Dim query = From team In teams Order By team Ascending Distinct For Each team As String In query lstOutput.) Handles btnDetermine. Private Sub btnDisplay_Click(..Count) End Sub .txt") Private Sub btnDetermine_Click(.ReadAllLines("Final.Text = FormatPercent(query2.File..Click Dim query1 = From grade In IO.Count / query1.Text = FormatNumber(avg) txtAboveAve.File.ToUpper = txtName.Average Dim query2 = From grade In IO. Private Sub btnDisplay_Click(...

File.File..ReadAllLines("States.Student Solutions Manual (Page 87 of 211) 31.Click Dim states() As String = IO.txt") Let lastName = pres.) Handles btnDisplay..Add(state) Next End Sub 33.Last Order By lastName Select pres For Each pres As String In query lstOutput.. Private Sub btnDisplay_Click(.Items.) Handles btnDisplay. Private Sub btnDisplay_Click(.Add(pres) Next Distinct End Sub ..ReadAllLines("USPres.Items.Click Dim query = From pres In IO.Split(" "c).txt") ReDim Preserve states(12) Dim query = From state In states Order By state Select state For Each state As String In query lstOutput.

Text) Select nation lstNations.) Handles lstNations.DataSource = nations lstNations.txt") Private Sub frmNations_Load(.Text End Sub .Text = lstNations.) Handles MyBase.File.Student Solutions Manual (Page 88 of 211) 35.TextChanged Dim query = From nation In nations Where nation. Dim nations() As String = IO.Click txtNation......StartsWith(txtNation.ReadAllLines("Nations.ToList lstNations.) Handles txtNation.DataSource = query.SelectedItem = Nothing End Sub Private Sub txtNations_TextChanged(.Load lstNations.SelectedItem = Nothing End Sub Private Sub lstNations_Click(..

The area of a football field is 19200 square yards.3 1. In the event procedure. Mr. 13. DC 11.name = data(0) states(i). The population growth of Phoenix from 2000 to 2010.. 15.txt") Dim n As Integer = stateRecords. Duke was founded in NC in 1838.1 ReDim states(n) Dim line As String Dim data() As String For i As Integer = 0 To n line = stateRecords(i) data = line. peace should be prize. President lives in Washington. 7. along with their populations. 17. Structures can only be compared one field at a time.Count . Joe: 88 Moe: 90 Roe: 95 5. The condition (game1 > game2) is not valid. 3. 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(.pop = CDbl(data(3)) Next End Sub .abbreviation = data(1) states(i). The cities in Texas. heights are same 170 9.Load Dim stateRecords() As String = IO.area = CDbl(data(2)) states(i). The cities are ordered by the sizes of their populations beginning with the most populous city.File.Split(".) Handles MyBase.Student Solutions Manual (Page 89 of 211) EXERCISES 7.yr."c) states(i)..ReadAllLines("USStates.peace and yr should be prize. 19.

.pop / state. formattedDensity dgvOutput." End Sub 7.ToList dgvOutput.Student Solutions Manual (Page 90 of 211) Private Sub btnFind_Click(.name & " is " & FormatNumber(query.3 Exercise 21 (Begin with the code from Exercise 19 and replace the Click event procedure with the following.Click Dim stateAbbr As String = mtbAbbrev.area txtOutput.Text = "The area of " & query.) Private Sub btnDisplay_Click(.name.First.CurrentCell = Nothing dgvOutput.Columns("formattedDensity").First.) Handles btnFind. 7.name.area. 2) Order By density Descending Select state.. 0) & " square miles..Columns("name").HeaderText = "State" dgvOutput.DataSource = query.area Let formattedDensity = FormatNumber(density. state..abbreviation = stateAbbr Select state.3 Exercise 19 21.HeaderText = "People per Square Mile" End Sub .Text.Click Dim query = From state In states Let density = state.ToUpper Dim query = From state In states Where state.) Handles btnDisplay.

ToList dgvOutput.Columns("name").team = data(1) players(i).name = data(0) players(i).) Handles MyBase.1 ReDim players(n) Dim line As String Dim data() As String For i As Integer = 0 To n line = playerStats(i) data = line. person.SelectedIndexChanged Dim selectedTeam = lstTeams.Split(".Student Solutions Manual (Page 91 of 211) 23.Text Dim query = From person In players Where person.) Handles _ lstTeams.HeaderText = "Player" dgvOutput.CurrentCell = Nothing dgvOutput.name.Count ..hits = CDbl(data(3)) Next Dim query = From person In players Order By person."c) players(i)..File.Load Dim playerStats() As String = IO.hits Descending Select person. Structure Player Dim name As String Dim team As String Dim atBats As Double Dim hits As Double End Structure Dim players() As Player Private Sub frmBaseball_Load(.atBats = CDbl(data(2)) players(i).ReadAllLines("Baseball.team Ascending Select person.DataSource = query.team Distinct lstTeams.ToList End Sub Private Sub lstTeams_SelectedIndexChanged(.team = selectedTeam Order By person...HeaderText = "Hits" End Sub .Columns("hits").hits dgvOutput.DataSource = query.txt") Dim n As Integer = playerStats.

3) Dim query2 = From person In players Where person..Columns("team").name = data(0) players(i).hits = CDbl(data(3)) Next End Sub Private Sub btnDisplay_Click(.Student Solutions Manual (Page 92 of 211) 25..Load Dim playerStats() As String = IO.atBats = CDbl(data(2)) players(i).ToList dgvOutput.1 ReDim players(n) Dim line As String Dim data() As String For i As Integer = 0 To n line = playerStats(i) data = line.team dgvOutput.Text = FormatNumber(best.ReadAllLines("Baseball.Count . Structure Player Dim name As String Dim team As String Dim atBats As Double Dim hits As Double End Structure Dim players() As Player Private Sub frmBaseball_Load(..CurrentCell = Nothing dgvOutput.atBats = best Select person.) Handles MyBase.Split(".hits / person.team = data(1) players(i).atBats Select ave Dim best As Double = query.Max txtBestAverage.) Handles btnDisplay..DataSource = query2.File."c) players(i).txt") Dim n As Integer = playerStats.hits / person.HeaderText = "Player" dgvOutput.name.HeaderText = "Team" End Sub . person.Click Dim query = From person In players Let ave = person.Columns("name").

firstName = data(0) justices(i).1 ReDim justices(n) Dim line As String Dim data() As String For i As Integer = 0 To n line = justiceRecords(i) data = line.) Handles btnDisplay.yrAppointed Select person.yrAppointed = CDbl(data(4)) justices(i).File. Structure Justice Dim firstName As String Dim lastName As String Dim apptPres As String Dim state As String 'state abbreviation Dim yrAppointed As Double Dim yrLeft As Double End Structure Dim justices() As Justice Private Sub frmJustices_Load(..lastName = data(1) justices(i)..yrLeft = 0 Order By person.SelectedItem = Nothing End Sub .ToList lstOutput.Split(".Count .yrLeft = CDbl(data(5)) Next End Sub Private Sub btnDisplay_Click(.firstName & " " & person.txt") Dim n As Integer = justiceRecords.DataSource = query.state = data(3) justices(i).Student Solutions Manual (Page 93 of 211) 27..Click Dim query = From person In justices Where person.lastName lstOutput.ReadAllLines("Justices.."c) justices(i).apptPres = data(2) justices(i).) Handles MyBase.Load Dim justiceRecords() As String = IO.

Text Let fullName = person.yrLeft) Let presLastName = person. yrs If query.DataSource = query. (Begin with the code from Exercise 27 and replace the Click event procedure with the following.HeaderText = "Appointing President" dgvOutput.Columns("presLastName").Focus() Else dgvOutput..) Handles btnDisplay.apptPres.HeaderText = "Justice" dgvOutput.) Private Sub btnDisplay_Click(.Count = 0 Then MessageBox.HeaderText = "Years Served" End If End Sub Function YearsServed(ByVal enter As Double.firstName & " " & person.Year .Student Solutions Manual (Page 94 of 211) 29.Show("No justices appointed from that state.CurrentCell = Nothing dgvOutput.Click Dim query = From person In justices Where person.enter) Else Return (leave . ByVal leave As Double) As Double If leave = 0 Then Return (Now..ToList dgvOutput. person. presLastName.Split(" "c).. "NONE") mtbState.state = mtbState.lastName Let yrs = YearsServed(person.Last Select fullName.enter) End If End Function .Columns("yrs").yrAppointed.Columns("fullName").".

) Handles btnDisplayGifts.ReadAllLines("Gifts.Student Solutions Manual (Page 95 of 211) 31.Items."c) days(i).Clear() lstOutput.Click Dim dayNum = CInt(txtDayNum.Add("") lstOutput.File.num) Next lstOutput.Count ...Items.Add(days(i)..Text) Dim cost As Double = 0 Dim totalCost As Double = 0 lstOutput.1) lstOutput.num * days(i).txt") Dim n As Integer = gifts.Add("Total cost for the first " & dayNum & " days: " & FormatCurrency(totalCost)) End Sub .Items.present = data(1) days(i).1 ReDim days(n) Dim data() As String For i As Integer = 0 To n data = gifts(i).Add("The gifts for day " & dayNum & " are") For i As Integer = 0 To (dayNum .present) cost += days(i).num * days(i).num & " " & days(i).price totalCost += days(i).Items.price * (dayNum + 1 .Load Dim gifts() As String = IO.Items.num = CInt(data(0)) days(i).) Handles MyBase.days(i).Items..Add("Cost for day " & dayNum & ": " & FormatCurrency(cost)) lstOutput.price = CDbl(data(2)) Next End Sub Private Sub btnDisplayGifts_Click(. Structure Day Dim num As Integer Dim present As String Dim price As Double End Structure Dim days() As Day Private Sub frmXmas_Load(.Split(".

Load 'Place the data for each person into the array people.Count .dateOfBirth = CDate(data(1)) Next End Sub .Split("."c) famousPersons(i).dateOfBirth < #1/1/1980#) Select person.Count .name = data(0) people(i)..dateOfBirth = CDate(data(1)) Next End Sub Private Sub btnDisplay_Click(.ReadAllLines("Famous...Load Dim people() As String = IO."c) people(i).1 ReDim famousPersons(n) Dim line As String Dim data() As String For i As Integer = 0 To n line = people(i) data = line.DataSource = query.ToList lstOutput.name lstOutput.SelectedItem = Nothing End Sub 35. Dim group() As String = IO.File.txt") Dim n As Integer = group.ReadAllLines("Famous.name = data(0) famousPersons(i). Structure FamousPerson Dim name As String Dim dateOfBirth As Date End Structure Dim famousPersons() As FamousPerson Private Sub frmFamous_Load(. Dim people() As Person Private Sub frmFamous_Load(.dateOfBirth >= #1/1/1970#) And (person.Click Dim query = From person In famousPersons Where (person.) Handles MyBase....) Handles btnDisplay.1 ReDim people(n) Dim data() As String For i As Integer = 0 To n data = group(i).File.) Handles MyBase.txt") Dim n As Integer = people.Student Solutions Manual (Page 96 of 211) 33.Split(".

Count = 3 Then lstOutput.Items..Items.Count .Clear() For i As Integer = 0 To club."c) Return First End Function 37. Private Sub btnDisplay_Click(. Today). ageInDays.dateOfBirth) Where individual.ToList dgvOutput.CurrentCell = Nothing End Sub Function DayOfWeek(ByVal d As Date) As String Dim d1 As String = FormatDateTime(d. dayOfBirth dgvOutput.name) End If Next End Sub . 0) Let dayOfBirth = DayOfWeek(individual.dateOfBirth.name.) Handles btnDisplay.DataSource = query.Day.Add(club(i).) Handles btnDisplay.Student Solutions Manual (Page 97 of 211) Private Sub btnDisplay_Click(.courses.Split(".Click Dim query = From individual In people Let ageInDays = FormatNumber(DateDiff(DateInterval.AddYears(40) <= Today And individual..dateOfBirth.LongDate) Dim d2() As String = d1.AddYears(50) > Today Select individual.1 If club(i).dateOfBirth.. individual.. DateFormat.Click lstOutput.

.Items.) Handles btnDisplay.name) End If Next End Sub .courses.Student Solutions Manual (Page 98 of 211) 39.Count .1 Dim checkList(ub) As Boolean For i As Integer = 0 To ub For j As Integer = 0 To club(i). Private Sub btnDisplay_Click(.1 If club(i).Count ..Click 'Displays the students who are not enrolled in CMSC 100 Dim subject = "CMSC 100" Dim ub = club.courses(j) = subject Then checkList(i) = True End If Next Next For i As Integer = 0 To ub If Not checkList(i) Then lstOutput.Add(club(i).

Student Solutions Manual (Page 99 of 211)

EXERCISES 7.4
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 100 of 211)
19. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display a company's inventory from its two stores 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 'Display the store's inventory and totals 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

Student Solutions Manual (Page 101 of 211)
21. 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 102 of 211)
23. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Load golf data, cumulate totals, and display results 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 = 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 & ": " & FormatNumber(roundTotal(round) / 4)) Next End Sub

ReadAllLines("Ranking.txt") Dim data() As String For field As Integer = 0 To 2 data = table(field). 2) = CInt(txtExam3.Text = result End If End Sub 27.Clear() txtExam4.Text) scores(count ..) Handles btnAdd.. 1) = CInt(txtExam2.File.1..Text) 'Reset input txtName.Focus() End If End Sub .1.ToUpper Then 'Append category name to result result &= disciplines(category) & " " End If Next Next If result = "" Then txtOutput. rank).1.Text) scores(count .1. 3) = CInt(txtExam4. Dim scores(14.Clear() txtExam2. 4) As String Dim disciplines(2) As String Dim table() As String = IO." Else txtOutput.Text = "None.Text) scores(count . 4) = CInt(txtExam5.1. 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.Student Solutions Manual (Page 103 of 211) 25.". Private Sub btnDisplay_Click(.Clear() txtName. 4) As Integer Dim count As Integer Dim names(14) As String 'Stores students' exam scores 'Current number of students stored 'Stores students' names Private Sub btnAdd_Click(.Click Dim ranking(2..) Handles btnDisplay.Text scores(count . 0) = CInt(txtExam1.Split(".1) = txtName.ToUpper = ranking(category.Text) scores(count .Clear() txtExam1.Show("Fifteen students already stored. "Warning") Else count += 1 names(count .Clear() txtExam5.Clear() txtExam3.Click If (count = 15) Then MessageBox.Text."c) disciplines(field) = data(0) For rank As Integer = 0 To 4 ranking(field.

1 sum = 0 For exam As Integer = 0 To 4 sum += scores(i. exam.Items. exam) Next lstOutput..Add(names(i) & ": " & FormatNumber(sum / 5)) Next 'Display median on the exams lstOutput.Add("Semester Averages") For i As Integer = 0 To count . count.Items.Items.Click Dim sum As Double..) Handles btnDisplay.Items. even As Boolean lstOutput.Add(exam + 1 & ": " & Median(scores. even)) Next End Sub .Student Solutions Manual (Page 104 of 211) Private Sub btnDisplay_Click(.Clear() lstOutput.Items.Add("Exam Medians") even = (Int(count / 2) = count / 2) For exam As Integer = 0 To 4 lstOutput.

23. 86.95. {12. 17. 95.5. 45.Items.Items. storing grand total in totals(0) lstOutput. 64. Private Sub btnDisplay_Click(..Items. 22. 17. 43.Student Solutions Manual (Page 105 of 211) 29.) Handles btnDisplay.Add("Sales per store") For store As Integer = 0 To 2 lstOutput. item) * price(item) Next Next 'Display report. 34.. 63}.Click 'Load data into an array. 82.Add(store + 1 & ": " & FormatCurrency(totals(store))) totalSales += totals(store) Next lstOutput. 78} 'Cumulate totals Dim totals(2) As Double For store As Integer = 0 To 2 For item As Integer = 0 To 4 totals(store) += sales(store.Add("Total sales: " & FormatCurrency(totalSales)) End Sub . 35}} Dim price() As Double = {12. 19.) As Integer = {{25. {54. 14}. and display a report Dim totalSales As Double Dim sales(. cumulate totals.

1 1. Alito. 9.File.Union(vicePres).ReadAllLines("USPres. both) MessageBox. Private Sub btnXor_Click(.ReadAllLines("VPres.File.WriteAllLines("Xor.Samuel. The new file is the same as the original file except that the last three fields have been deleted from each record.txt") Dim eitherOr() As String = presidents.ToArray Dim both() As String = presidents.ToArray Dim exclusiveOr() As String = eitherOr. 11. 15.Except(both).ToArray IO. 13.File.2006 Baldwin.) Handles btnXor.Show(exclusiveOr. Samuel Alito.Show(both. The new file contains the names of the people who subscribe to the New York Times but not the Wall Street Journal..ReadAllLines("VPres.File..Intersect(vicePres).File.) Handles btnBoth.1830 3.txt". The new file contains the names of the people who subscribe to either the New York Times or the Wall Street Journal.Student Solutions Manual (Page 106 of 211) CHAPTER 8 EXERCISES 8. exclusiveOr) MessageBox. but not both".txt") Dim presidents() As String = IO.Click 'Create a file of people who were pres or VP but not both Dim vicePres() As String = IO. Private Sub btnBoth_Click(. "File Created") End Sub ..ReadAllLines("USPres.Henry.Intersect(vicePres).WriteAllLines("Both.PA 5.txt") Dim both() As String = presidents.txt") Dim presidents() As String = IO. Alito was appointed by Bush Baldwin was appointed by Jackson 7.Count & " presidents".NJ Henry Baldwin.File. 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. "File Created") End Sub 17.Count & " presidents or vice presidents..Click 'Create a file of presidents who were also vice presidents Dim vicePres() As String = IO. The justices are ordered by the year they were appointed.txt". or both.ToArray IO.

Student Solutions Manual (Page 107 of 211)
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 = FormatNumber(100000 * pops.Sum, 0) End Sub

Student Solutions Manual (Page 108 of 211)
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

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 = FormatPercent(area / totalArea) 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

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

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

Student Solutions Manual (Page 110 of 211)
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(ByVal 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 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 = FormatNumber(data(2), 0) Let pop = FormatNumber(data(3), 0) Order By name Select name, abbrev, area, pop dgvStates.DataSource = query.ToList dgvStates.CurrentCell = Nothing End Sub

WriteLine("Levi Strauss jeans.20") sw.WriteLine("Stetson. The variable age is declared within the Try-Catch-Finally block. You must enter a number. Private Sub btnAdd_Click(.10.".Student Solutions Manual (Page 111 of 211) EXERCISES 8. 7.Close() MessageBox. Error occurred.txt") sw..00") sw.File... "DONE") End Sub .2.50") sw..40.txt should be delimited with quotation marks.2 1.1.txt contains an invalid age.) Handles btnCreate. Bon Jour 5.txt") sw.WriteLine("Colt Peacemaker. Private Sub btnCreate_Click(.12. "Done") End Sub 21.Click 'Create a text file and populate it Dim sw As IO.00") sw.00") sw.WriteLine("Holster.20. Therefore it has block-level scope and is not available below the line End Try.WriteLine("Winchester Rifle.CreateText("Cowboy. MessageBox.txt is created and has the following lines: Hello Bon Jour 13. 19. 9.AppendText("Cowboy.WriteLine("Saddle.StreamWriter = IO. File Ages.35") sw.". 11.StreamWriter = IO. 17. Hello 3.) Handles btnAdd.Click 'Append item to a text file Dim sw As IO.Show("The item has been added to the file.File.Close() 'Always close the writer when finished. The file Welcome. The filespec Greetings.Show("The file has been created. There should be no quotations around the variable name as the argument to the CreateText method. 15.

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

.txt") Dim lines(4) As String For i As Integer = 0 To 4 lines(i) = sr."c) Let item = data(0) Let cost = FormatCurrency(data(1)) Select item.File.ToList dgvOutput.StreamReader = IO..OpenText("Numbers.EndOfStream num = CDbl(sr. cost dgvOutput.Student Solutions Manual (Page 113 of 211) 25.OpenText("Cowboy. Private Sub btnDetermine_Click(.Split(".StreamReader = IO.ReadLine Next Dim query = From line In lines Let data = line.DataSource = query.ReadLine) counter += 1 Loop txtOutput.) Handles btnDetermine.Click Dim sr As IO.File.Click Dim sr As IO.txt") Dim counter As Integer = 0 Dim num As Double Do Until sr. Private Sub btnDisplay_Click(.CurrentCell = Nothing End Sub 27.Text = CStr(counter) sr...Close() End Sub .) Handles btnDisplay.

OpenText("Numbers.File..Student Solutions Manual (Page 114 of 211) 29.) Handles btnCalculate.ReadLine) If num < min Then min = num End If Loop txtOutput.ReadLine) Do Until sr. Private Sub btnCalculate_Click(.Close() End Sub 31.EndOfStream num = CDbl(sr.Click Dim sr As IO. Private Sub btnCalculate_Click(..Text = CStr(min) sr..Text = FormatNumber(total / counter) sr.ReadLine) counter += 1 total += num Loop txtOutput.Click Dim sr As IO.StreamReader = IO.) Handles btnCalculate.File.txt") Dim num As Double Dim min As Double = CDbl(sr..OpenText("Numbers.StreamReader = IO.txt") Dim counter As Integer = 0 Dim total As Double = 0 Dim num As Double Do Until sr.Close() End Sub .EndOfStream num = CDbl(sr.

Load("USStates.Student Solutions Manual (Page 115 of 211) EXERCISES 8.<population>. No 3.0'?> <!-. Private Sub btnDisplay_Click(. <?xml version='1.Sum / queryArea.Load("USStates.Click Dim stateData As XElement = XElement.3 1.<population>.. No 9. Private Sub btnDisplay_Click(.Descendants("state") Let area = CInt(st.Value) Select pop txtOutput..This file contains the ages of the presidents when inaugurated.) Handles btnDisplay.--> <Presidents> <president> <name>George Washington</name> <ageAtInauguation>57</ageAtInauguation> </president> <president> <name>John Adams</name> <ageAtInauguation>61</ageAtInauguation> </president> </Presidents> 13..Click Dim stateData As XElement = XElement.Value) Select pop Dim queryArea = From st In stateData.Value) Select area txtOutput. No 11.Text = FormatNumber(query.Sum. No 7.xml") Dim query = From st In stateData. No 5.) Handles btnDisplay. 0) End Sub 15.Sum) & " people per square mile" End Sub .Descendants("state") Let pop = CInt(st.Text = FormatNumber(queryPop..Descendants("state") Let pop = CInt(st.xml") Dim queryPop = From st In stateData.<area>.

0) Where area > 100000 Order By area Descending Select name.Value Let numVowels = NumberOfVowels(name) Order By numVowels Descending Select numVowels Dim maxVowels As Integer = query1..HeaderText = "Area" End Sub 19.Descendants("state") Let name = st. Private Sub btnDisplay_Click(.First Dim query2 = From st In stateData.DataSource = query2.Value Where NumberOfVowels(name) = maxVowels Select name lstOutput.Load("USStates.Descendants("state") Let name = st.) Handles btnDisplay.<name>.Click Dim stateData As XElement = XElement.DataSource = query.) Handles btnDisplay.<name>.Descendants("state") Let name = st.ToList dgvStates.Load("USStates.HeaderText = "State" dgvStates.ToList lstOutput. formattedArea dgvStates. Private Sub btnDisplay_Click(..Columns("name").Value) Let formattedArea = FormatNumber(area.Value Let area = CDbl(st.<name>.SelectedItem = Nothing End Sub .xml") Dim query1 = From st In stateData.CurrentCell = Nothing dgvStates.xml") Dim query = From st In stateData.Student Solutions Manual (Page 116 of 211) 17...Columns("formattedArea").<area>.Click Dim stateData As XElement = XElement.

) Handles btnDisplay.IndexOf("I") <> -1 Then num += 1 End If If word. Dim colleges As XElement = XElement.DataSource = query.<state>.Value Let yearFounded = col.ToUpper 'mask LL Dim query = From col In colleges.Text.Value Where state = chosenState Order By name Ascending Select name & " " & yearFounded lstColleges.Click 'Display the colleges in Colleges.Load("Colleges..xml located in the given state Dim chosenState As String = mtbState.ToList lstColleges.ToUpper Dim num As Integer = 0 If word.Value Let state = col.SelectedItem = Nothing End Sub .IndexOf("A") <> -1 Then num += 1 End If If word.<name>.IndexOf("O") <> -1 Then num += 1 End If If word..xml") Private Sub btnDisplay_Click(.IndexOf("U") <> -1 Then num += 1 End If Return num End Function 21.Descendants("college") Let name = col.IndexOf("E") <> -1 Then num += 1 End If If word.<yearFounded>.Student Solutions Manual (Page 117 of 211) Function NumberOfVowels(ByVal word As String) As Integer word = word.

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

ReadLine sw.WriteLine("</Senate111>") sr.Value Let state = st.Split(".0'?>") sw. Private Sub btnSenate_Click(."c)(2) & "</party>") sw.<state>.ToList dgvSenators.StreamReader = IO.Descendants("senator") Let name = st.Click Dim sr As IO."c)(0) & "</name>") sw.Close() MessageBox.CreateText("Senate111.Show("File Created") End Sub 25(b).) Handles btnDisplay..txt") Dim sw As IO.WriteLine(" <name>" & temp.WriteLine("<?xml version='1."c)(1) & "</state>") sw.HeaderText = "Senator" dgvSenators.Value Order By state.XML") Dim query = From st In senateData..This file contains data on the 111th Senate -->") sw.<name>.WriteLine(" <senator>") sw.Value Let party = st.Student Solutions Manual (Page 119 of 211) 25(a).File..Columns("state").DataSource = query.HeaderText = "Party Affiliation" End Sub .File.Click Dim senateData As XElement = XElement.Split(".WriteLine("<!-. party dgvSenators.) Handles btnSenate.Columns("party").Close() sw..EndOfStream temp = sr.WriteLine(" </senator>") Loop sw.WriteLine("<Senate111>") Dim temp As String = "" Do Until sr.WriteLine(" <state>" & temp.Load("Senate111. name Ascending Select name.HeaderText = "State" dgvSenators. Private Sub btnDisplay_Click(.xml") sw.CurrentCell = Nothing dgvSenators.<party>.Columns("name").OpenText("Senate111.WriteLine(" <party>" & temp. state.Split(".StreamWriter = IO.

Remove("Shakespeare") 13.Items. Mozart.1) 15.RemoveAt(cboBox.1 1. Chopin is deleted from the list.Count If CStr(cboBox. cboBox.Text = "Dante" 11. 5. The item Haydn is inserted into lstBox between Chopin and Mozart.Items. The currently selected item in lstBox. 1) = "M" Then cboBox. is deleted. cboBox. 9.Items.Items(i)).Items. 3. 7. Dim i As Integer = 0 Do While i < cboBox.Count .Student Solutions Manual (Page 120 of 211) CHAPTER 9 EXERCISES 9.RemoveAt(i) Else i += 1 End If Loop .Items. cboBox. The names in the list box will appear in descending alphabetical order.Substring(0.

Student Solutions Manual (Page 121 of 211) 17.Items(i)) Next IO.File..txt".ReadAllLines("PopularName. "Done") End Sub .Items.Show("The ordered file has been created.DataSource = names lstOutput.1 names(i) = CStr(lstOutput.txt") lstOutput.".SelectedItem = Nothing For i As Integer = 0 To lstOutput.WriteAllLines("SortedNames.File.Click Dim names() As String = IO.. names) MessageBox.Sorted = True lstOutput.Count . Private Sub btnSort_Click(.) Handles btnSort.

6 at design time Dim n As Integer = lstBox.. 5..Student Solutions Manual (Page 122 of 211) 19. 3. 17.1 Dim nums(n) As Double For i As Integer = 0 To n nums(i) = CDbl(lstBox.SelectedItem = Nothing End Sub .DataSource = query. 9.Items.Items(i)) Next Dim query = From num In nums Order By num Ascending Select num lstBox. 2.) Handles btnSort. Private Sub btnSort_Click(.Count .Click 'Assume the String Collection Editor was filled with the numbers '4.ToList lstBox. 11.

1 lstOutput.Clear() lstOutput.1 lstOutput.1) first(i) = CStr(lstOutput. Private Sub frmList_Load(.Items.Add(first(i)) Next Else ReDim first(location .Items.Add(newItem) For i As Integer = 0 To first.1 first(i) = CStr(lstOutput.Items(i)) Next ReDim last(lstOutput.Text = CStr(lstOutput.) Handles btnDelete.Items.Count .Add(first(i)) Next lstOutput. Dim location As Integer = lstOutput.1) For i As Integer = 0 To (lstOutput.Count . add the new item to the top of the list.Items.1) last(i) = CStr(lstOutput.Items.Items. last() As String Dim location As Integer = lstOutput.SelectedIndex Dim newItem As String = InputBox("Enter item to add to list:"...Text = CStr(lstOutput.Count . ReDim first(lstOutput..) Handles MyBase.Clear() For i As Integer = 0 To first.Count .Count .Load lblCount.location .1) For i As Integer = 0 To (location .Count . Dim first().Count) 'Update the counter.Items.Items.Count) End Sub Private Sub btnAdd_Click(.Items.Items..Add(last(i)) Next End If lblCount.RemoveAt(location) lblCount.Items.) Handles btnAdd.1 lstOutput.1) For i As Integer = 0 To lstOutput.Items(location + i)) Next lstOutput. If location >= 0 Then lstOutput. End If End Sub . _ "Add Item") If location = -1 Then 'If no item is selected.Count .Click 'Add an item above the currently selected item...Add(newItem) For i As Integer = 0 To last. End Sub Private Sub btnDelete_Click(.Student Solutions Manual (Page 123 of 211) 21.Items(i)) Next lstOutput.Click 'Delete the highlighted item.Items.SelectedIndex 'Only delete if something is selected.location .Items.Count) 'Update the counter.Items.Text = CStr(lstOutput.Items.

) Handles _ cboBrand.SelectedIndex) End Sub 9.Text = "You have a " & cboBrand..SelectedIndexChanged." End If End Sub ..SelectedIndexChanged 'Update output if all choices have been made.Student Solutions Manual (Page 124 of 211) 23..File..txt") lstPres.ReadAllLines("AgesAtInaugural.1 Exercise 23 25.SelectedIndex >= 0) And (cboMonitor.DataSource = pres End Sub Private Sub lstPres_SelectedIndexChanged(. cboMonitor.Text = ages(lstPres. cboMemory.Load Dim pres() As String = IO.SelectedIndexChanged.Text & " computer with " & cboMemory.txt") Private Sub frmPres_Load(.) Handles MyBase.) Handles _ lstPres.. 'Note: This event procedure handles events from all three combo boxes Private Sub SelectedIndexChanged(.SelectedIndex >= 0) Then txtOutput.File. Dim ages() As String = IO.SelectedIndex >= 0) And (cboMemory.SelectedIndexChanged txtAge.Text & " monitor..ReadAllLines("USPres. If (cboBrand.Text & " of memory and a " & cboMonitor.

Two states are selected at random and displayed in the list box. 13. 17.leftmost point will be 20 pixels from the left side of the picture box and 30 pixels from the top side. 26) Dim city As String For i As Integer = 1 To num city = sr. A blue circle of radius 50 pixels will be drawn in the picture box. The Tick event will be triggered every intVar seconds. 19. The tooltip will appear one second after the cursor is hovered over a control. Timer1. A check mark appears in front of the mnuOrderAsc menu item. Dim randomNum As New Random() txtBox. 5. 9. Dim sr As IO.S. 13)) 31. 15.Student Solutions Manual (Page 125 of 211) EXERCISES 9. 25. 23. 11. The name of one of the 44 U.Files.ReadText("Towns.Next(1. 27. The contents of the Clipboard are deleted. The contents of the Clipboard are assigned to the variable strVar. The contents of the Clipboard are displayed in txtBox. is copied into the Clipboard.txt") Dim randomNum As New Random() Dim num As Integer = randomNum.StreamReader = IO. The text currently selected in txtBox. The Tick event will be triggered every 5 seconds (5000 milliseconds).Text = city .2 1. 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. Its upper. presidents is selected at random and displayed in txtBox. 7. 3.Next(1. 21.Enabled = False 29.ReadLine Next txtBox.Text = CStr(randomNum. A picture of an airplane will be placed in the picture box. if any.

n) Until secondNumber <> firstNumber lstBox. VScrollBar2.Value = VScrollBar2.Add(rivers(firstNumber)) lstBox.SelectedText) 39.Next(0.Items.") End If 35.SetText(txtBox. . Dim amount As Integer amount = CInt(Clipboard.Add(rivers(secondNumber)) Else MessageBox. Clipboard.Student Solutions Manual (Page 126 of 211) 33. mnuOrderDesc.Count If n ≥ 2 Then Dim randomNum As New Random() Dim firstNumber. Dim n As Integer = rivers.Minimum 45. Clipboard.Next(0.GetText) 41. secondNumber As Integer firstNumber = randomNum.Checked = False 43. n) Do secondNumber = randomNum. The menu item mnuOrderAsc is grayed out and cannot be selected.Items.Show("The array has fewer than two elements.SetText("") 37.

Load 'Load the image from the file into the picture box picBox. 0) 'If the number is less than 10. Dim timeStr As String = "" 'The function Hour returns the current hour. 0) 'The function Minute() returns the current minute.Tick 'When the timer ticks. UpdateClock() End Sub Private Sub UpdateClock() 'Update the clock with the current time. update the clock. add a zero.) Handles tmrClock.FromFile("TREES.BMP") UpdateClock() End Sub Private Sub tmrClock_Tick(. lblTime. timeStr &= ":" & PadZero(Second(Now)) 'Set the label to the time.Text = timeStr End Sub Function PadZero(ByVal num As Integer) As String 'Pads a one-digit number with a zero Dim result As String 'Format the number without decimal places. If num < 10 Then Return "0" & result Else Return result End If End Function .Image = Image. Private Sub frmClock_Load(.. timeStr &= ":" & PadZero(Minute(Now)) 'The function Second returns the current second.) Handles MyBase.Student Solutions Manual (Page 127 of 211) 47. timeStr = timeStr & FormatNumber(Hour(Now).... result = FormatNumber(num.

7) die2 = randomNum.Next(1.Student Solutions Manual (Page 128 of 211) 49.1) names(n .Text 'Choose a random person from first n-2 for Secretary. names(p) = names(n ..1) txtTreasurer.Click 'Roll a pair of dice until 7 appears 1000 times.Next(0.Next(1.Next(0.File.Next(0.) Handles btnPlay.1) = txtPresident.. names(p) = names(n .Text = names(p) End Sub 51. 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. 7) 'If lucky 7.. n ..2) names(n . txtOutput. 2) End Sub . Dim die1. die2 As Integer Dim numberOfSevens As Integer = 0 Dim numberOfRolls As Integer = 0 Do 'Roll the dice die1 = randomNum.Text 'Choose a random person from first n-1 for Treasurer.Text = names(p) 'Swap Treasurer with the person in the next to last array element.2) txtSecretary. n) txtPresident.) Handles btnSelect.2) = txtTreasurer. n . Dim names() As String = IO.txt") Dim n As Integer = names. increment the sevens counter.Text = names(p) 'Swap President with the person in the last array element.Click 'Assume there are at least three members in the club. Private Sub btnSelect_Click(. Dim randomNum As New Random() Private Sub btnPlay_Click(. p = randomNum. p = randomNum.ReadAllLines("Members.Text = FormatNumber(numberOfRolls / numberOfSevens.Count Dim p As Integer Dim randomNum As New Random() p = randomNum.

) Handles btnCompute. .Student Solutions Manual (Page 129 of 211) 53.Next(1. 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.. Private Sub btnCompute_Click(.Click Dim match As Boolean Dim num. 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.

FromFile(fileSpec) End Sub 59.FromFile("Moon" & phase & ".ShowDialog() fileSpec = OpenFileDialog1.Image = Image...Student Solutions Manual (Page 130 of 211) 57.) Handles tmrMoon.. picBox.FileName 'Display picture contained in the file.) Handles btnDisplay. Private Sub tmrMoon_Tick(.Tick 'Update the phase and display the image..Click 'Display the open file dialog box to get the file Dim fileSpec As String OpenFileDialog1.bmp") End Sub .Image = Image. Timer Enabled setting is True phase += 1 If phase = 9 Then phase = 1 End If picBox. Private Sub btnDisplay_Click(. 'Timer Interval setting is 2000.

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

3 1.Checked Then quotation = "Rosebud. Your last name begins with K.00 3.Text = Form2.Click Form2.Checked Then quotation = "Plastics. $106..) Handles btnDisplay.. 'Form1's code Private Sub btnDisplay_Click(.ShowDialog() txtQuotation.quotation End Sub 'Form2's code (Movies) Public quotation As String Private Sub btnProcessSelection_Click(.Student Solutions Manual (Page 132 of 211) EXERCISES 9.Close() End Sub .Checked Then quotation = "That's all folks..) Handles _ btnProcessSelection.. 5." End If If rad2.Click If rad1." End If Me." End If If rad3.

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

) Handles MyBase.Load 'Sets the class variables from a new or existing text file InitializeData() 'Set name and balance labels lblName. Form1's Code 'Class-level named constants and variables 'Data files that store information Const INIT_FILE As String = "Initial_Info..Text = FormatCurrency(curBal) 'Set the date field to the current date.Text = CStr(Today) SetupCheck() ResetInput() End Sub .txt" Public Const TRANS_FILE As String = "Transactions.Text = nameOnChk txtBalance.. txtDate.txt" 'Variables used for each entry Dim isCheck As Boolean Dim nameOnChk As String 'Name to appear on checks Dim lastCkNum As Integer 'Number of last check written Dim lastDpNum As Integer 'Number of last deposit slip processed Dim curBal As Double 'Current balance in account Private Sub frmAccount_Load(.Student Solutions Manual (Page 134 of 211) 9.

WriteLine(outputLine) Catch 'If a number cannot be converted then display message and quit MessageBox.Student Solutions Manual (Page 135 of 211) Private Sub InitializeData() If IO.CreateText(INIT_FILE) sw. "Error") Me."c) 'Load the name to appear on checks.ReadAllLines(INIT_FILE) 'Split the single line of the INIT_FILE using the separator data = initFileContents.File." & lastCkNum & ".File.File.StreamWriter nameOnChk = InputBox("Name to appear on checks:") Try curBal = CDbl(InputBox("Starting Balance:")) 'Get numbers of last check and deposit slip lastCkNum = CInt(InputBox("Number of first check:")) .Split(".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 & ".Close() Finally 'Close the writer no matter what happens above sw. number of 'last check written and number of last deposit slip processed nameOnChk = data(0) curBal = CDbl(data(1)) lastCkNum = CInt(data(2)) lastDpNum = CInt(data(3)) 'Possibly update the values above by looking at last record of TRANS_FILE If IO.Exists(TRANS_FILE) Then Dim transFileContents() As String = IO.Exists(INIT_FILE) Then Dim data() As String 'holds the data read from the file Dim initFileContents() As String = IO. current balance."c) curBal = CDbl(data(2)) lastCkNum = CInt(data(3)) lastDpNum = CInt(data(4)) End If Else 'INIT_FILE does not exist.ReadAllLines(TRANS_FILE) data = transFileContents. so get initial data from user Dim sw As IO.Close() End Try End If End Sub .First. Program terminating.File."." & curBal & "." & lastDpNum sw = IO.Show("Invalid number.Split(".1 lastDpNum = CInt(InputBox("Number of first deposit slip:")) .File.Last.

Text) transType = "Check" Else curBal += amt lastDpNum = CInt(txtNum.Text. separated by the separator sw. txtDate.Close() 'Reset input text boxes to blank for next entry ResetInput() End If End Sub .Text) 'Adjust balance by amount depending on check or deposit slip mode If isCheck Then curBal = curBal .")) sw. CStr(lastCkNum). CStr(amt).Text} Dim sw As IO.Text..Text = FormatCurrency(curBal) 'String array contains info to be stored Dim transOutput() As String = {transType.Student Solutions Manual (Page 136 of 211) Private Sub btnRecord_Click(.StreamWriter = IO.File..) Handles btnRecord.WriteLine(Join(transOutput. ". CStr(lastDpNum).Click 'Store the input into the transactions file Dim amt As Double Dim transType As String 'Only store if all required fields are filled and valid If DataValid() Then amt = CDbl(txtAmount. txtMemo.Text) transType = "Deposit" End If txtBalance. txtToFrom.AppendText(TRANS_FILE) 'Append the info to the text file. CStr(curBal).amt lastCkNum = CInt(txtNum.

Trim = "" Then errorMessage = "Amount" txtAmount.Focus() End If Catch exc As InvalidCastException errorMessage = "The amount " & txtAmount.) Handles btnMode.Focus() End If 'If no errors yet then check syntax of the two numerical fields If errorMessage = "" Then 'Check syntax of the amount field (Double) Try If CDbl(txtAmount.Show(errorMessage & " Please try again.Text.Click 'Toggle mode between Check and Deposit Slip If isCheck Then SetupDeposit() Else SetupCheck() End If 'Set fields for next entry ResetInput() End Sub .Trim = "" Then If isCheck Then errorMessage = "Pay To" Else errorMessage = "Source" End If txtToFrom..." txtAmount.Student Solutions Manual (Page 137 of 211) Function DataValid() As Boolean 'Returns True if all data are valid.Text) <= 0 Then errorMessage = "The amount must be greater than zero. recording can proceed Return True Else 'Advise user of invalid data MessageBox. assign its name to errorMessage If txtToFrom.Text & " is invalid.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.Focus() ElseIf txtAmount.") Return False End If End Function Private Sub btnMode_Click(.Text. or displays a message if not Dim errorMessage As String = "" 'If one of the two essential pieces of information 'is missing." txtAmount.

Focus() End Sub Private Sub btnReport_Click(.Exists(TRANS_FILE) Then Form2.Clear() If isCheck Then 'Make txtNum text box reflect next check number txtNum.Yellow End Sub Sub ResetInput() 'Reset all text entry fields except date txtToFrom.Text = "Pay To" btnRecord.) Handles btnReport.BackColor = Color.Text = "&Record This Check" btnMode.Show("There are no transactions to report..Clear() txtAmount.Text = "&Record This Deposit" btnMode.BackColor = Color.Text = CStr(lastCkNum + 1) Else 'Make txtNum text box reflect next deposit slip number txtNum..ShowDialog() Else MessageBox.Text = "&Switch to Deposits" Me.Clear() txtMemo.Click If IO.") End If End Sub .Text = "&Switch to Checks" Me.Text = "Check" 'Sets the title bar of the form lblToFrom.Text = "Source" btnRecord.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.File.Text = CStr(lastDpNum + 1) End If 'Set focus on to/from control for the next entry txtToFrom.Student Solutions Manual (Page 138 of 211) Sub SetupCheck() 'Prepare form for the entry of a check isCheck = True Me.

. ByVal depositNumber As String) As String If type = "Check" Then Return "Check #" & checkNumber Else Return "Deposit #" & depositNumber End If End Function Private Sub btnQuit_Click(.) Handles btnQuit.Close() 'Exit the program End Sub . ByVal checkNumber As String..Click Me.Student Solutions Manual (Page 139 of 211) Function FormNumber(ByVal type As String.

Amount."c) Let transDate = CDate(data(7)) Let number = frmAccount.) Handles MyBase.Columns("number").ReadAllLines(frmAccount.HeaderText = "Description" dgvTransactions. Memo. number..TRANS_FILE) Dim query = From trans In transFileContents Let data = trans. data(4)) Let toFrom = data(1) Let Memo = data(6) Let Amount = FormatCurrency(data(5)) Let Balance = FormatCurrency(data(2)) Select transDate. toFrom. Balance dgvTransactions.Student Solutions Manual (Page 140 of 211) Form2's Code Private Sub Form2_Load(.File.Split(".FormNumber(data(0).Load Dim transFileContents() = IO.HeaderText = "Recipient or Source" End Sub .DataSource = query.HeaderText = "Transaction Date" dgvTransactions..Columns("transDate").ToList dgvTransactions.Columns("toFrom"). data(3).

) Handles MyBase.) Handles MyBase..txtName.Close() End Sub 'Form3's code (Credit Card Info) Private Sub Form3_Load(..Text) Form1.Add("Expiration date: " & cboMonth.Load Dim num As Integer = Today.Text) Me.lstOutput.Click If radBillCust.Text state = cboState. 'Form1's code (Customer) Private Sub btnGet_Click(.) Handles btnRecord.lstOutput. state...Add("Name on card: " & txtName.Add(txtAddress.Click Form1.Text) Form1.) Handles btnRecord...Items.Items.Text = Form1.lstOutput.Text) city = txtCity.Text Form1.Add(txtName..ShowDialog() Else Form3.Text End Sub Private Sub btnRecord_Click(.) Handles btnGet. " & state & " " & zip) Me.lstOutput.ShowDialog() End If End Sub 'Form2's code (Customer Info) Private Sub Form2_Load(.Text) Form1.Items.lstOutput.Text zip = txtZip.Items.lstOutput.Items.Load txtName.Checked Then Form2.Click Dim city..Items.Add("Card number: " & txtCardNumber.Text) Form1.Add("Mail bill to:") Form1.lstOutput..Student Solutions Manual (Page 141 of 211) 11.Year For i As Integer = num To num + 5 cboYear.Close() End Sub .Items. zip As String Form1.Add(city & ".Text & "/" & cboYear.Items..Items.Add(i) Next End Sub Private Sub btnRecord_Click(.lstOutput.Add("Bill " & cboCard.

CSng(2 * r).Black.CreateGraphics Dim x As Double = picBox. CSng(y . CSng(y . CSng(y .FillEllipse(Brushes. CSng(x . CSng(2 * r).4 1.Width / 2 Dim y As Double = picBox.Click Dim gr As Graphics = picBox.r).r).Height / 2 Dim r As Double = 20 gr. Private Sub btnDraw_Click(..FillEllipse(Brushes.r).r). Private Sub btnDraw_Click(. CSng(2 * r)) End Sub .CreateGraphics Dim x As Double = picBox. CSng(2 * r)) End Sub 3.Student Solutions Manual (Page 142 of 211) EXERCISES 9. CSng(x .. CSng(x .White.Red.r).Width / 2 Dim y As Double = picBox. CSng(2 * r)) r = 19 gr.r).) Handles btnDraw...Click Dim gr As Graphics = picBox. CSng(2 * r).Height / 2 Dim r As Double = x / 2 If r > y / 2 Then r = y / 2 End If gr.) Handles btnDraw.FillEllipse(Brushes.

98. 98) 'left border gr. picFlag. 0.) Handles btnCreate.Red} 'picFlag.DrawLine(Pens. 98) 'bottom border gr. 0. picFlag. 0. Brushes.DrawLine(Pens.DrawLine(Pens.DrawLine(Pens. Brushes.Black. 148.Height = 99 For i As Integer = 0 To 2 gr. 0.FillPie(Brushes. 49 .Click Dim gr As Graphics = picFlag.Width = 149.DrawLine(Pens..CreateGraphics Dim br() As Brush = {Brushes. 0) 'top border gr. 0 + i * 50.Black.Orange.Click Dim gr As Graphics = picFlag. 50. 148. 98. 148. 99) Next gr. 148.) Handles btnCreate. 0.DrawLine(Pens.White.. 0 + i * 33.Black. 0.r. 148. 0. 0. 75 . 0.White.Student Solutions Manual (Page 143 of 211) 5. 98) 'left border gr.4 Exercise 7 (Niger) 7.DrawLine(Pens. 0.4 Exercise 5 (Italy) 9..Black. 98) 'right border End Sub ..FillRectangle(br(i). 2 * r.DrawLine(Pens. 0. 148.Black. 148.CreateGraphics Dim br() As Brush = {Brushes. 0. 149. 98) 'right border End Sub 9.r.Height = 99 For i As Integer = 0 To 2 gr.Width = 149. Brushes.Orange.FillRectangle(br(i). 0. Brushes. 98) 'bottom border gr. 0. 0) 'top border gr. Private Sub btnCreate_Click(.Green. Private Sub btnCreate_Click(. 0. 148. 0. 33) Next gr.Black. 0.Black.Black. 360) gr. 2 * r.Green} Dim r As Integer = 12 'radius of circle 'picFlag.

Blue.Click Dim numbers As String = "" Dim gr As Graphics = picBox.DrawLine(Pens..Student Solutions Manual (Page 144 of 211) 9. 8. 0. 12 + (24 * i).Refresh() Dim n As Integer = CInt(txtNumber.) Handles btnDraw.CreateGraphics picBox. 10.DrawLine(Pens. Private Sub btnDraw_Click(. Me.Font. 10) gr. 12 + (24 * i). 5..Blue.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. 20) End Sub . 15) Next gr.Blue. 24 * (n + 1). Brushes.DrawString(numbers.

Blue.Green. sumOfSweepAngles.1 sumOfQuantities += quantity(i) Next 'Convert tbe quantities to percents For i As Integer = 0 To quantity.r. Count .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.1) As Single Dim sumOfQuantities As Single = 0 Dim sumOfSweepAngles As Single = 0 Dim br() As Brush = {Brushes. c . Brushes. 14.Orange.3} Dim percent(quantity. Private Sub btnDisplay_Click(.1.7. Brushes.. Count . Brushes. Brushes.Gray} Dim gr As Graphics = picOutput. 20.r. percent(i) * 360) sumOfSweepAngles += percent(i) * 360 gr. Brushes.DrawString(legend(i). 21.Student Solutions Manual (Page 145 of 211) 11. 20) gr.Black.Tan.Red. 220. 2 * r. Count . 22 + 30 * i) Next End Sub . 11.FillPie(br(i).Text = "U. Brushes. Recreational Beverage Consumption" 'Sum the numbers for the quantities For i As Integer = 0 To quantity.) Handles btnDisplay.9..S.1 percent(i) = quantity(i) / sumOfQuantities Next 'Display the pie chart and the legends For i As Integer = 0 To quantity. "Beer".1 gr. c) Me. 2 * r. c . "Other"} Dim quantity() As Single = {52. 20 + 30 * i. "Bottled Water". 250.FillRectangle(br(i).Font.Count . Me.Click Dim legend() As String = {"Soft Drinks".

6) Next End Sub . 100 . 100 .Font. 30..Black.DrawString("Source: Higher Education Research Institute".Blue. Private Sub btnDisplay_Click(.Student Solutions Manual (Page 146 of 211) 13.Font. picOutput.Count .12.Click Dim gr As Graphics = picOutput. 100 . 50 + i * 35.7. 30.12. Brushes.smokers(i + 1) * 7) Next For i As Integer = 0 To smokers. 100.4} gr. 95.12. 0.Black. 5. 50 + i * 35.7 * 7) 'tick mark gr. 4. 30.6) gr.DrawString("12. 100 . 50 + i * 35.Black. 7.6. Me. 0) 'y-axis gr. 27.3. 6.Black.DrawLine(Pens.3.4. Brushes.smokers(i) * 7.Blue.7 * 7 . Me.CreateGraphics Dim smokers() As Single = {11.3.7".DrawLine(Pens. 100. Me. 33. 100) gr.Count .DrawLine(Pens..DrawString("1996 1998 2000 2002 2004 2006 2008".smokers(i) * 7 . 100 .DrawLine(Pens.Font.0.7 * 7. Me. 100 . 50 + (i + 1) * 35.2 gr. 30.4.DrawString("Percentage of College Freshmen Who Smoke".) Handles btnDisplay.1 gr.FillEllipse(Brushes.Black.DrawLine(Pens. 35. 6.Font.Blue. 102) gr.Width. Brushes.Black.Blue. 30. 100) 'x-axis gr. 135) For i As Integer = 0 To smokers. 12. 50 + i * 35 . 120) gr. 10. Brushes.

Text = "Most Popular Majors" For i As Integer = 0 To quantity. 12. 115) gr. 1) & "%"). (100 .Tan.DrawString("Prevet".Font. 195.Blue. Me.DrawLine(Pens..Blue.Font.DrawString(CStr(FormatNumber(quantity(i).Font. 21 + i * 60. picOutput.1. 30.Count .8} Dim gr As Graphics = picOutput. 100. 4.Blue. quantity(i) * 19) gr.DarkBlue..2. Admin. 102) legend = "(general) Premed" & " (general)" gr.Font.quantity(i) * 19). Private Sub btnDisplay_Click(. 85) Next legend = "Biology Psychology Nursing Predent Bus. 10.DrawString(legend. Brushes. Brushes.Black.) Handles btnDisplay.CreateGraphics Dim legend As String 'The picture box has width 310 and height 170 gr. 5." gr. Me.10.DrawString("Most Popular Majors for College Freshmen in Fall 2008". 3.5.1 gr. Me.Student Solutions Manual (Page 147 of 211) 15. Brushes. 5.FillRectangle(Brushes. Brushes. Me. 145) End Sub . 100) x-axis Me.Width . 15. 128) gr.Click Dim quantity() As Single = {5. Brushes.8.Font. 20 + i * 60.Blue. 3. Me.DrawString(legend.

88. 882. 60 + i * 30 + 7. 60 + i * 30 + 7.Black.Black..Font.DrawString(caption.Count . 15.1 gr. Me.Blue.21. "Spanish". Brushes. 0) 'y-axis gr. 8. "Mandarin". 110) gr.DrawLine(Pens. Me.DrawLine(Pens.DrawLine(Pens. 100.Student Solutions Manual (Page 148 of 211) 17. 96. "Wu"} Dim quantity() As Single = {173. 130) Next gr. Brushes. 40. 100. 100 .Count . 35.DrawString("Principal Languages of the World". 60 + i * 30.quantity(i) / 10). 326.DrawString("882". 60 + i * 30 . 100.6) Me.) Handles btnDisplay.Font. 40.Blue.1 Step 2 gr.DrawLine(Pens. quantity(i) / 10) Next For i As Integer = 0 To quantity.Black. (100 .2) 'tick mark gr. "Hindi".Black.Font. Brushes. 60 + i * 30 .FillRectangle(Brushes. 78} Dim gr As Graphics = picOutput. 60 + i * 30 + 7.2.Count . 90. "Portuguese".Click Dim legend() As String = {"Bengali".DrawString(legend(i). Brushes. "German".Font.Black. 40. Me.Width.Black. 146.DrawLine(Pens. 179. "English".CreateGraphics Dim caption As String 'The picture box has width 365 and height 185 gr.88. 100. "Japanese". 182. Private Sub btnDisplay_Click(.Blue. Me. Me. 150) caption = "(in millions of " & Chr(34) & "first language" & Chr(34) & " speakers)" gr. 165) End Sub .Black. Brushes.Black. 130) gr.1 Step 2 gr.88.DrawString(legend(i).. 128. 110) Next For i As Integer = 1 To quantity. 311.2 .Text = "Principal Languages" For i As Integer = 0 To quantity. 100 .Font. picOutput.10. 45. 100 . 100) 'x-axis gr. "Russian". 60 + i * 30 + 7. 90.

Enabled = True End Sub Private Sub Timer1_Tick(.Student Solutions Manual (Page 149 of 211) 19.Left = -picBox.Tick If picBox..) Handles MyBase..Width Else picBox..Left += 1 End If End Sub . Dim x As Integer = 1 Dim y As Integer = 40 Private Sub frmPlane_Load(.Load Timer1.) Handles Timer1.Left = Me..Width Then picBox.

300.Print() End Sub Handles btnPrint.PrintPage Dim gr As Graphics = e..Graphics Dim br() As Brush = {Brushes..DrawLine(Pens.Black.White.) Handles _ PrintDocument1.Black. 448. 50. 200. 200. 200. 298. 298) 'bottom border gr. 300.Document = PrintDocument1 PrintPreviewDialog1.. 200.Click PrintPreviewDialog1. 298) 'left border gr. Private Sub btnPrint_Click(..Black.DrawLine(Pens.) Handles btnPreview. 99) Next gr.. 200) 'top border gr. 300 + i * 50.Click Private Sub PrintDocument1_PrintPage.ShowDialog() End Sub .Black..DrawLine(Pens.Red} For i As Integer = 0 To 2 gr.Student Solutions Manual (Page 150 of 211) 21.FillRectangle(br(i).) PrintDocument1. 300. 298) 'right border End Sub Private Sub btnPreview_Click(. 448.Green.DrawLine(Pens. 300. Brushes. Brushes. 448. 448.

CurrentCell = Nothing dgvOutput.1 1.Columns("formattedPopGrowth"). (d) 5.pop2015 ..Cities Let popGrowth = (city.Fill(Me..Columns("name").pop2010) / city.HeaderText = "Country" dgvOutput. city. (e) 3.Cities) End Sub Private Sub btnDisplay_Click(.ToList dgvOutput.) Handles btnDisplay..Student Solutions Manual (Page 151 of 211) CHAPTER 10 EXERCISES 10.DataSource = query. Private Sub frmCities_Load(. formattedPopGrowth dgvOutput.) Handles MyBase.name.Load Me.HeaderText = "City" dgvOutput.country.Columns("country"). (b) 7.pop2010 Let formattedPopGrowth = FormatPercent(popGrowth) Order By popGrowth Descending Select city..Click Dim query = From city In MegacitiesDataSet.city.HeaderText = "Projected Population Growth" End Sub .CitiesTableAdapter.MegacitiesDataSet.

Columns("country"). city.Cities Where city.) Handles MyBase.CitiesTableAdapter.DataSource = query2..Fill(Me.pop2010 Order By perIncr Descending Select city.CurrentCell = Nothing dgvOutput.Fill(Me.SelectedItem = Nothing End Sub 11.Load Me..pop2010.name Dim geatestCity As String = query1.HeaderText = "Population in 2010" dgvOutput.HeaderText = "Population in 2015" End Sub . city.pop2015 .Cities) End Sub Private Sub btnDisplay_Click(.pop2015 Descending Select city.DataSource = query..ToList dgvOutput.Cities Where city.Student Solutions Manual (Page 152 of 211) 9.) Handles btnDisplay.name lstOutput..Columns("pop2015").pop2015 dgvOutput.Cities) End Sub Private Sub btnDisplay_Click(. Private Sub frmCities_Load(.ToList lstOutput.Click Dim query1 = From city In MegacitiesDataSet.HeaderText = "Country" dgvOutput. city.Cities Let perIncr = (city.) Handles MyBase.Click Dim query = From city In MegacitiesDataSet.Columns("pop2010").name.city.MegacitiesDataSet..name = geatestCity Select city.MegacitiesDataSet.CitiesTableAdapter. Private Sub frmCities_Load(.First Dim query2 = From city In MegacitiesDataSet..Load Me..HeaderText = "City" dgvOutput..Columns("name").pop2010) / city.) Handles btnDisplay.pop2015 > 20 Order By city.country.

Text Select cityPer txtOutput.First) End Sub 15.CountriesTableAdapter..Fill(Me.Countries) Me. query.Fill(Me.ToArray) MessageBox." & city..Cities Join country In MegacitiesDataSet.Cities Select city.Student Solutions Manual (Page 153 of 211) 13." & city.Cities Select city.Fill(Me.name & ".) Handles btnCreate.File.Click Dim query = From city In MegacitiesDataSet. Private Sub frmCities_Load(.Text = FormatPercent(query.country Equals country.ToList End Sub Private Sub lstCities_SelectedIndexChanged(.CitiesTableAdapter.TXT".) Handles MyBase.Show("File Created") End Sub .Load Me.name lstCities.name Let cityPer = city.MegacitiesDataSet..DataSource = query." & city.MegacitiesDataSet..pop2010 Where city.Countries On city.Load Me.country & ".pop2010 / country. Private Sub frmCities_Load(.Cities) Dim query = From city In MegacitiesDataSet.CitiesTableAdapter.pop2010 & ".SelectedIndexChanged Dim query = From city In MegacitiesDataSet..) Handles _ lstCities..pop2015 IO.MegacitiesDataSet..) Handles MyBase.name = lstCities.Cities) End Sub Private Sub btnCreate_Click(.WriteAllLines("MEGACITIES..

SelectedItem = Nothing End Sub .) Handles _ lstContinents.continent = lstContinents. Private Sub frmNations_Load(.DataSource = query.) Handles MyBase.ToList lstCountriesPop..area Descending Select nation.continent Ascending Select nation.NationsTableAdapter.Text Order By nation.Load Me.SelectedItem = Nothing Dim queryArea = From nation In UNDataSet.ToList End Sub Private Sub lstContinents_SelectedIndexChanged(..continent = lstContinents.Nations Where nation.Fill(Me.name lstCountriesArea.SelectedIndexChanged Dim queryPop = From nation In UNDataSet.Student Solutions Manual (Page 154 of 211) 17.population Descending Select nation..Nations) Dim query = From nation In UNDataSet.Nations Where nation.Text Order By nation.ToList lstCountriesArea.Nations Order By nation.UNDataSet.continent Distinct lstContinents.DataSource = queryArea.DataSource = queryPop..name lstCountriesPop.

area Dim max As Double = query.area = max Or country..Load Me.Nations Where country.) Handles MyBase.area = min Order By country.continent.area dgvOutput.Nations) End Sub Private Sub btnDisplay_Click(.NationsTableAdapter.Max Dim min As Double = query.Min Dim queryOutput = From country In UNDataSet.Nations Select country. country.DataSource = queryOutput.Student Solutions Manual (Page 155 of 211) 19.UNDataSet.) Handles btnDisplay.population.CurrentCell = Nothing End Sub . country. country..area Descending Select country.name.Click Dim query = From country In UNDataSet.ToList dgvOutput..Fill(Me. Private Sub Form1_Load(..

stadium txtStadium..country lstCountries..ToList End Sub Private Sub lstTeams_SelectedIndexChanged(.country = lstCountries.Teams) Dim query = From team In BaseballDataSet.Text = CStr(query.DataSource = query.Text = query.Teams Where team..SelectedIndexChanged Dim query = From team In BaseballDataSet.Teams Order By team.Rates Where money..) Handles MyBase..Fill(Me.Load Me.ExchrateDataSet.Rates Order By money.First.) Handles _ lstCountries.monetaryUnit txtRate.Text Select team...SelectedIndexChanged Dim query = From money In ExchrateDataSet.First End Sub .Load Me.name Select team.dollarRate) End Sub 23.monetaryUnit.Text = query.Text Select money. Private Sub frmBaseball_Load(.) Handles MyBase.dollarRate txtCurrency.. Private Sub frmCurrencies_Load(. money.DataSource = query.First.dollarRate Ascending Select money.name = lstTeams.ToList End Sub Private Sub lstCountries_SelectedIndexChanged(.Student Solutions Manual (Page 156 of 211) 21.RatesTableAdapter.name lstTeams.Rates) Dim query = From money In ExchrateDataSet.TeamsTableAdapter.Fill(Me.) Handles _ lstTeams.BaseballDataSet.

Click Dim query1 = From player In BaseballDataSet.Fill(Me.DataSource = query.name lstOutput.) Handles MyBase..hits Descending Select player.Columns("name").Players Where player.CurrentCell = Nothing dgvOutput.Load Me..Columns("formattedBattingAve").TeamsTableAdapter.Players) Dim query = From team In BaseballDataSet...ToList lstOutput.. Private Sub frmBaseball_Load(.Fill(Me.. Private Sub frmBaseball_Load(.name..team = lstTeams.) Handles btnDetermine.Players Order By player.Teams) Me.) Handles MyBase.Teams Order By team.DataSource = query.BaseballDataSet.PlayersTableAdapter.HeaderText = "Name" dgvOutput.Players Where player.PlayersTableAdapter.hits Dim mostHits As Double = query1.name Select team.Text Let battingAve = player.atBats Let formattedBattingAve = FormatNumber(battingAve.) Handles _ lstTeams.Max Dim query2 = From player In BaseballDataSet.BaseballDataSet.SelectedIndexChanged Dim query = From player In BaseballDataSet.ToList dgvOutput.BaseballDataSet. 3) Order By battingAve Descending Select player.hits / player.Players) End Sub Private Sub btnDetermine_Click(.Load Me. formattedBattingAve dgvOutput.ToList End Sub Private Sub lstTeams_SelectedIndexChanged(.Student Solutions Manual (Page 157 of 211) 25.DataSource = query2.HeaderText = "Batting Average" End Sub ..Fill(Me.hits = mostHits Select player.name lstTeams.SelectedItem = Nothing End Sub 27.

CheckedChanged DisplayPlayers("American") End Sub Private Sub radNational_CheckedChanged(.HeaderText = "Team" dgvOutput....BaseballDataSet.Teams Let battingAve = team. Private Sub frmBaseball_Load(.) Handles radNational.Student Solutions Manual (Page 158 of 211) 29..name.TeamsTableAdapter.Columns("formattedBattingAve").league = group Order By battingAve Descending Select team.) Handles MyBase.Teams) End Sub Private Sub radAmerican_CheckedChanged(.Columns("name").HeaderText = "Batting Average" End Sub . 3) Where team.. formattedBattingAve dgvOutput..hits / team.Load Me.Fill(Me.atBats Let formattedBattingAve = FormatNumber(battingAve.) Handles radAmerican.ToList dgvOutput.CurrentCell = Nothing dgvOutput.CheckedChanged DisplayPlayers("National") End Sub Sub DisplayPlayers(ByVal group As String) Dim query = From team In BaseballDataSet.DataSource = query.

TeamsTableAdapter.team Equals team.Click Dim query1 = From team In BaseballDataSet.league = "American" Select team.) Handles MyBase.PlayersTableAdapter..) Handles MyBase.Players) End Sub Private Sub btnCount_Click(. Private Sub frmBaseball_Load(. 0) End Sub .Teams On player.Click Dim query = From player In BaseballDataSet..Student Solutions Manual (Page 159 of 211) 31.Text = FormatNumber(query...TeamsTableAdapter.Sum / query2.Fill(Me..hits Dim query2 = From team In BaseballDataSet..Load Me.Teams) End Sub Private Sub btnCalculate_Click(.Teams Where team.Load Me.Count.Fill(Me.atBats txtBattingAve.league = "American" Select team.Teams) Me.league = "National" Select player.Sum. Private Sub frmBaseball_Load(..Players Join team In BaseballDataSet.Text = FormatNumber(query1..name txtNational.) Handles btnCalculate.BaseballDataSet.BaseballDataSet.Teams Where team.Fill(Me.) Handles btnCount.name Where team.BaseballDataSet. 3) End Sub 33.

Players Join team In BaseballDataSet.name lstTeams.Load Me.) Handles _ lstTeams.Text And playerBattingAve > teamBattingAve Order By playerBattingAve Descending Select player.atBats Where team.BaseballDataSet. Private Sub frmBaseball_Load(..Teams) Me.hits / player.Fill(Me.Players) Dim query = From team In BaseballDataSet.DataSource = query.name Let playerBattingAve = player.BaseballDataSet.SelectedItem = Nothing End Sub ..Teams Order By team.) Handles MyBase.team Equals team.name = lstTeams.Student Solutions Manual (Page 160 of 211) 35.Fill(Me.name Select team.hits / team.Teams On player.SelectedIndexChanged Dim query = From player In BaseballDataSet.ToList End Sub Private Sub lstTeams_SelectedIndexChanged(.DataSource = query.atBats Let teamBattingAve = team.PlayersTableAdapter..TeamsTableAdapter..name lstPlayers.ToList lstPlayers.

.team Equals team.Teams On player.Players) End Sub Private Sub btnDisplay_Click(.PlayersTableAdapter.Teams) Me..atBats Select playerBattingAve Dim highestAve As Double = query1.name Where team.name Let playerBattingAve = player.BaseballDataSet.league = "National" And playerBattingAve = highestAve Select player.Student Solutions Manual (Page 161 of 211) 37.ToList lstPlayers.league = "National" And player.Fill(Me.Max Dim query2 = From player In BaseballDataSet.team Equals team..Players Join team In BaseballDataSet.Teams On player.atBats > 100 Let playerBattingAve = player.hits / player.) Handles MyBase.SelectedItem = Nothing End Sub 39.Fill(Me.TeamsTableAdapter. film .Players Join team In BaseballDataSet.atBats Where team..Click Dim query1 = From player In BaseballDataSet.Load Me.hits / player.name lstPlayers. Private Sub frmBaseball_Load(.) Handles btnDisplay.DataSource = query2.BaseballDataSet.

MoviesDataSet.LinesTableAdapter..Actors On line.SelectedIndexChanged Dim query = From line In MoviesDataSet.ActorsTableAdapter.ToList End Sub Private Sub lstFilms_SelectedIndexChanged(. Private Sub frmMovies_Load(..Fill(Me.Lines Join flick In MoviesDataSet.Text Select flick.DataSource = query.film = lstFilms.Actors) Dim query = From line In MoviesDataSet.First End Sub .MoviesDataSet.) Handles _ lstFilms.Lines Select line.film Equals flick...) Handles MyBase.Fill(Me.maleLead txtLead.film Distinct lstFilms.film Where line.Student Solutions Manual (Page 162 of 211) 41.Load Me.Lines) Me.Text = query.

DataSource = query.Fill(Me.Lines Join flick In MoviesDataSet.) Handles _ lstActors..Load Me.Actors On line.SelectedItem = Nothing End Sub .ToList lstLines.Actors) Dim query = From flick In MoviesDataSet.MoviesDataSet.ActorsTableAdapter.Lines) Me.DataSource = query.MoviesDataSet.Text Select line..famousLine lstLines..ToList End Sub Private Sub lstFilms_SelectedIndexChanged(.Fill(Me.film Equals flick.maleLead = lstActors.LinesTableAdapter.maleLead Distinct lstActors.. Private Sub frmFilms_Load(.Student Solutions Manual (Page 163 of 211) 43.film Where flick.) Handles MyBase.Actors Select flick.SelectedIndexChanged Dim query = From line In MoviesDataSet.

MoviesDataSet.EndEdit() LinesTableAdapter. strVar) = 0) And (strVar <> "Bombay") 11. 19. Private Sub CountryTextBox_Leave(.Focus() End If End Sub 13.LinesTableAdapter. 9.2 7. address.Position = BindingSource2. BindingSource1. Create a control named BindingSource2 that has the Countries table as its DataMember.Text) If (CountryTextBox.Fill(Me.Find("name"..) Handles btnUpdate.Text <> "") And (BindingSource2. Private Sub frmMovies_Load(. (BindingSource1.) Handles _ CountryTextBox.Lines) End Sub Private Sub btnUpdate_Click(. CountryTextBox.Leave. The first table should contain the fields name.Student Solutions Manual (Page 164 of 211) EXERCISES 10. and stateCapital.) Handles MyBase... BindingNavigator1. 21.Update(MoviesDataSet.Show("Not a valid country. Thus the Rule of Referential Integrity would be violated.Find("name".Text <> "Argentina") Then MessageBox. but using the database Justices accdb. state.. Replace the table with two tables. .Load Me.. Add a record to the Cities table whose name field is empty or contains the same name as an already existing record.Lines) End Sub 17.".Click BindingSource2. Then use the program to update the database. Write a program similar to the one in Example 1..Position = 0) And (CountryTextBox.Click 'These two lines update the database file on the hard drive. and city. The second table should contain the fields city. "ERROR") CountryTextBox. Apollo 13 does not appear in the key field of the Actors table.

15.Student Solutions Manual (Page 165 of 211) CHAPTER 11 EXERCISES 11. m_name would need to be Public and referred to by scholar.Add(pupil. 9. Country: Canada Capital: Ottawa Pop: 31 million . 7.Midterm) are not valid. 13. but cannot return a value. The properties Midterm and Final are write only. The property SocSecNum is initialized to the value 999-99-9999. 3. Any negative grade will be recorded as 0 and any grade greater than 100 will be recorded as 100. The Midterm property is write only.Midterm = scholar.Items. 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.Midterm and lstGrades.m_name. The statement nom = m_name is not valid.1 1. it can be set. 11. The statements pupil. The keyword New is missing from the third line of the event procedure.

Xcoord = picCircle. and create a frmCircle_Load event procedure with the following lines.Student Solutions Manual (Page 166 of 211) 17.Height . round. Change 20 to –20 in the btnMove_Click event procedure.40 round.Ycoord = picCircle.40 .Width .

Sqrt(value) * 4 End Set End Property End Class 'Square . m_perimeter. m_area As Double Public Property Length() As Double Get Return m_length End Get Set(ByVal 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(ByVal 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(ByVal value As Double) m_area = value m_length = Math.Sqrt(value) m_perimeter = Math.Student Solutions Manual (Page 167 of 211) 19. Class Square Private m_length.

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.Student Solutions Manual (Page 168 of 211) 21. 7) m_die2 = randomNum.Next(1. 7) End Sub End Class 'PairOfDice .

m_faculty As Double Public WriteOnly Property Name() As String Set(ByVal Value As String) m_name = Value End Set End Property Public WriteOnly Property NumStudents() As Double Set(ByVal Value As Double) m_students = Value End Set End Property Public WriteOnly Property NumFaculty() As Double Set(ByVal 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 169 of 211) 23. Class College Private m_name As String Private m_students.

Balance) txtAmount.Add(CDbl(txtAmount.Student Solutions Manual (Page 170 of 211) 25.Click 'Subtract an amount from the balance. register.Text = FormatCurrency(register..amount) >= 0 Then 'Ensure balance stays nonnegative m_balance = m_balance .Focus() End Sub Private Sub btnSubtract_Click(.Text)) txtBalance. Public Class frmCashRegister Dim register As New CashRegister() Private Sub btnAdd_Click(.Click 'Add an amount to the balance.Clear() txtAmount..) Handles btnAdd..Balance) txtAmount. register.Text = FormatCurrency(register.Text)) txtBalance.amount End If End Sub End Class 'CashRegister .Clear() txtAmount.Subtract(CDbl(txtAmount.) Handles btnSubtract.Focus() End Sub End Class 'frmCashRegister Class CashRegister Private m_balance As Double Public ReadOnly Property Balance() As Double Get Return m_balance End Get End Property Sub Add(ByVal amount As Double) If (m_balance + amount) >= 0 Then 'Ensure balance stays nonnegative m_balance += amount End If End Sub Sub Subtract(ByVal amount As Double) If (m_balance ..

Click Dim tax As New FICA() tax.) Handles btnCalculate.Student Solutions Manual (Page 171 of 211) 27.062 * (106800 . medicareTax As Double If (m_previousEarnings + m_currentEarnings) <= 106800 Then socialSecurityBenTax = 0.PreviousEarnings = CDbl(txtToDate.Text = FormatCurrency(tax. Public Class frmFICA Private Sub btnCalculate_Click(..CurrentEarnings = CDbl(txtCurrent.CalculateFICA) End Sub End Class 'frmFICA Class FICA 'Member variables store property values. Dim socialSecurityBenTax.062 * m_currentEarnings ElseIf m_previousEarnings < 106800 Then socialSecurityBenTax = 0..Text) tax.m_previousEarnings) End If medicareTax = 0.0145 * m_currentEarnings Return socialSecurityBenTax + medicareTax End Function End Class 'FICA .Text) txtTax. Private m_previousEarnings As Double 'Previous year-to-date earnings Private m_currentEarnings As Double Public WriteOnly Property PreviousEarnings() As Double Set(ByVal Value As Double) m_previousEarnings = Value End Set End Property Public WriteOnly Property CurrentEarnings() As Double Set(ByVal Value As Double) m_currentEarnings = Value End Set End Property Function CalculateFICA() As Double 'Calculate Social Security benefits tax and Medicare tax 'for a single pay period in 2009.

SocSecNum Let semGrade = pupil.HeaderText = "SSN" dgvGrades.) Handles btnDisplay.Name..CalcSemGrade dgvGrades.ToList dgvGrades.Columns("Name").HeaderText = "Student Name" dgvGrades.Focus() End Sub .Student Solutions Manual (Page 172 of 211) EXERCISES 11.SocSecNum.2 1.Columns("SocSecNum"). Sub btnDisplay_Click(..Click ReDim Preserve students(lastStudentAdded) Dim query = From pupil In students Let name = pupil. pupil.CurrentCell = Nothing dgvGrades.Columns("CalcSemGrade"). pupil.CalcSemGrade Where semGrade = "A" Select pupil.DataSource = query.Name Let ssn = pupil.HeaderText = "Grade" ReDim Preserve students(50) txtName.

Text = query. state. "Enter state's name").ToUpper Select state..Density..First.txt") Dim data() As String For i As Integer = 0 To 49 data = usstates(i). DateFormat. CDate(data(2)).Name..Student Solutions Manual (Page 173 of 211) 3.) Handles btnLookup.Clear() txtEntered.Name txtAbbr.First. data(1).First. state.Entered txtName.Clear() Dim query = From state In states Where state.Abbreviation txtDensity.Clear() txtDensity.Text = query.) Handles MyBase. state.First..Entered.File. Public Class frmStates Dim states(49) As State 'Holds the state's data Private Sub frmStates_Load(.Split(". Dim nm As String Dim i As Integer = 0 'Get name of state from message box nm = InputBox("Name of state:".Density.ToUpper = nm.Load 'Load the data file into the array Dim usstates() As String = IO. 1) txtEntered.ToUpper 'Clear the output text boxes txtName.LongDate) End Sub End Class 'frmStates Class State Private m_name. CDbl(data(3)).Text = FormatDateTime(query.Clear() txtAbbr."c) states(i) = New State(data(0).Text = FormatNumber(query. CDbl(data(4))) Next End Sub Private Sub btnLookup_Click(.Name.Abbreviation.Click 'Look up name in the array and return the state information. 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 .ReadAllLines("UnitedStates.

ByVal 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. ByVal a As String. ByVal ar As Double. Return _Population / m_area End Function End Class 'State . ByVal e As Date.Student Solutions Manual (Page 174 of 211) 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(ByVal n As String.

CDbl(data(4)))) Next sr.Items.) Handles btnDisplay. 0)) 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(ByVal name As String.ReadLine. ByVal population As Double) Sub Add(ByVal 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.Name..OpenText("UnitedStates.Close() End Sub Sub Populous(ByVal name As String.Population > 10000000 Then RaiseEvent Populous(state.Population) End If End Sub End Class 'UnitedStates Class State Private m_name. Public Class frmStates Dim WithEvents usa As New UnitedStates() Private Sub btnDisplay_Click(.Student Solutions Manual (Page 175 of 211) 5. ByVal population As Double) Handles usa.StreamReader = IO. CDbl(data(3)).Click 'Load the data file into the array. ". 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 . lstOutput. state.. CDate(data(2)).Populous 'Display the populous states and their populations in the list box.Add(New State(data(0).txt") For i As Integer = 0 To 49 'Add each state to the USA object Dim data() As String = Split(sr. Dim sr As IO."c) usa.Add(name & ": " & FormatNumber(population.File. data(1).

Text)) txtBalance.Balance) txtAmount. ByVal 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. ByVal e As Date.Student Solutions Manual (Page 176 of 211) 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(ByVal n As String.Focus() End Sub ..Click 'Add an amount to the balance. Return _Population / m_area End Function End Class 'State 7.Clear() txtAmount..Text = FormatCurrency(register.) Handles btnAdd.Add(CDbl(txtAmount. ByVal ar As Double. register. ByVal a As String. Public Class frmCashRegister Dim WithEvents register As New CashRegister() Private Sub btnAdd_Click(.

Student Solutions Manual (Page 177 of 211) Private Sub btnSubtract_Click(.Clear() txtAmount.m_balance) End If End Sub End Class 'CashRegister .Balance) txtAmount. "Withdrawal Denied") End Sub End Class 'frmCashRegister Class CashRegister Private m_balance As Double Public Event AttemptToOverdraw(ByVal amt As Double) Public ReadOnly Property Balance() As Double Get Return m_balance End Get End Property Sub Add(ByVal amount As Double) If (m_balance + amount) >= 0 Then 'Ensure balance stays nonnegative m_balance += amount Else RaiseEvent AttemptToOverdraw(amount + m_balance) End If End Sub Sub Subtract(ByVal amount As Double) If (m_balance .Click 'Subtract an amount from the balance.Show("You would have been overdrawn by " & FormatCurrency(amt) & ".Text)) txtBalance.amount Else RaiseEvent AttemptToOverdraw(amount . register.Text = FormatCurrency(register..AttemptToOverdraw MessageBox.".Subtract(CDbl(txtAmount..amount) >= 0 Then 'Ensure balance stays nonnegative m_balance = m_balance .) Handles btnSubtract.Focus() End Sub Private Sub AttemptToOverdraw(ByVal amt As Double) Handles _ register.

Den) End Sub Sub fraction_ZeroDenominator() Handles x.Den 'Reduce and display the result.Click 'Add the x and y fractions to get the z fraction.Num = CInt(txtNumY.) Handles btnResult..Den = 1 End If End Sub End Class 'frmAdd .Text = "0" Then txtDenY. x.Student Solutions Manual (Page 178 of 211) 9. Dim message As String = "You cannot set a denominator to zero.Den) z.Num * y.Text) 'Add the two fractions.Text) y.Text = CStr(z. " & "All such denominators will be replaced by 1.Num = (x.Text = CStr(1) x. 'Store the input into the x and y fractions.Num = CInt(txtNumX.Num) txtDenZ.Num * x..Den = 1 End If If txtDenY.ZeroDenominator." MessageBox.Show(message) If txtDenX.Text = CStr(z.Text) y.Den * y.Den = CInt(txtDenX.Den) + (y.Text = CStr(1) y.Den = x.ZeroDenominator 'If x or y has a zero denominator. display an error message.Text) x.Den = CInt(txtDenY. z. z. Public Class frmAdd Dim WithEvents x As New Fraction() Dim WithEvents y As New Fraction() Dim WithEvents z As New Fraction() 'Left fraction 'Middle fraction 'Right fraction Private Sub btnResult_Click(.Text = "0" Then txtDenX. _ y.Reduce() txtNumZ.

the value of m will be the GCD.Student Solutions Manual (Page 179 of 211) 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(ByVal Value As Double) 'Raise the event if zero If Value = 0 Then RaiseEvent ZeroDenominator() Else m_den = Value End If End Set End Property Sub Reduce() Dim t As Double Dim m As Double = Num Dim n As Double = m_den 'Algorithm to calculate greatest common divisor of m and n. If m <> 0 Then Num = Num / m m_den = m_den / m End If End Sub End Class 'Fraction . Do While (n <> 0) t = n n = m Mod n m = t Loop 'Divide both numerator and denominator by greatest common divisor. 'After the loop terminates.

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(ByVal value As PairOfDice) m_second = value End Set End Property .Text = CStr(game.Die1) txt2Die2..Next loop." Case Else txtOutput.Text = "Player 1 wins.Second.Click 'Play the game.Die2) 'Display the results Select Case game.SumOfFaces Case game. Without the 'For. game." End Select End Sub End Class 'frmDice Class HighRoller Private m_first As PairOfDice Private m_second As PairOfDice 'First player 'Second player Public Sub New() m_first = New PairOfDice() 'The time is used to determine how the sequence of random numbers 'will be generated. Randomize() txt1Die1.Text = CStr(game..SumOfFaces txtOutput.Text = CStr(game. Public Class frmDice Dim game As New HighRoller() Private Sub btnPlay_Click(..Die1) txt1Die2.Student Solutions Manual (Page 180 of 211) 11.Next loop below guarantees that the 'two random number generators will act differently..Text = "Player 2 wins.Text = CStr(game.First..SumOfFaces txtOutput.Text = "Tie.Play() 'Display the throws.Second." Case Is > game. The For.First.Second.Die2) txt2Die1..Second.First.) Handles btnPlay. often the two rolls will be identical.

Next(1. m_first.Next(1. 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. 7) m_die2 = randomNum. 7) End Sub End Class 'PairOfDice .Student Solutions Manual (Page 181 of 211) Sub Play() 'Roll both pairs of dice.Roll() m_second. m_die1 = randomNum.Roll() End Sub End Class 'HighRoller Class PairOfDice Private m_die1.

Add("Name: " & emp.Add("Weekly Wages: " & FormatCurrency(wages)) lstOutput..Items.Items.Items.Hours = CDbl(txtHours.Text emp. lstOutput.Items.Add("Year-to-Date Wages: " & FormatCurrency(emp. takeHome As Double 'Store input into properties emp.Add("Withholding tax deduction: " & FormatCurrency(emp.Salary takeHome = wages .FICA)) lstOutput.Salary = CDbl(txtSalary.Text) emp. Public Class frmPayroll Dim emp As New Employee() Private Sub btnDisplay_Click(..Married = radMarried.Text) emp.Withholding 'Display paycheck receipt.emp.Add("FICA tax deduction: " & FormatCurrency(emp.Click 'Read input and display paycheck receipt Dim wages.YearToDate = CDbl(txtYtd.FICA .emp.Add("Take-home Pay: " & FormatCurrency(takeHome)) End Sub End Class 'frmPayroll Class Employee Private m_hours As Double Private m_salary As Double Dim tax As New Tax() 'Represents the tax for this employee Public Property Name() As String Public Property Hours() As Double Get Return m_hours End Get Set(ByVal Value As Double) m_hours = Value 'Update the tax property also tax.Student Solutions Manual (Page 182 of 211) 13.Items.YearToDate + wages)) lstOutput.Text) emp. wages = emp.Items.Wages = m_hours * m_salary End Set End Property .Withholding)) lstOutput.Name = txtName.Checked 'Calculate take-home pay.Text) emp.Hours * emp.Withhold = CInt(txtWithhold.Items.Clear() lstOutput.) Handles btnDisplay.Name) lstOutput.

Married = Value End Set End Property Function FICA() As Double 'Return the tax property Return tax.YearToDate End Get Set(ByVal Value As Double) 'Update the tax property tax.Withhold = Value End Set End Property Public Property Married() As Boolean Get 'Return the tax property Return tax.YearToDate = Value End Set End Property Public Property Withhold() As Integer Get 'Return the tax property Return tax.FICA End Function Function Withholding() As Double 'Return the tax property Return tax.Married End Get Set(ByVal Value As Boolean) 'Update the tax property tax.Withhold End Get Set(ByVal Value As Integer) 'Update the tax property tax.Withholding End Function End Class 'Employee .Wages = m_hours * m_salary End Set End Property Public Property YearToDate() As Double Get 'Return the tax property Return tax.Student Solutions Manual (Page 183 of 211) Public Property Salary() As Double Get Return m_salary End Get Set(ByVal Value As Double) m_salary = Value 'Update the tax property also tax.

(70.470) * 0.74 Case Else Return ((adjPay .4165) * 0.45 Case Is <= 4165 Return ((adjPay .15 + 16.062 * Wages ElseIf YearToDate < 106800 Then socialSecurityBenTax = 0.2272) * 0.303) * 0.Student Solutions Manual (Page 184 of 211) Class Tax Public Public Public Public Property Property Property Property Wages() As Double YearToDate() As Double Withhold() As Integer Married() As Boolean Function FICA() As Double 'Calculate Social Security benefits tax and Medicare tax 'for a single pay period in 2009 Dim socialSecurityBenTax.7321) * 0.19 * Withhold) 'Subtract exemptions If Married Then Select Case adjPay Case Is <= 303 Return 0 Case Is <= 470 Return (adjPay .YearToDate) End If medicare = 0.33) + 898.1 Case Is <= 1455 Return (adjPay .7 Case Is <= 2272 Return ((adjPay .35) + 1940.0145 * Wages 'Return the sum Return socialSecurityBenTax + medicare End Function Function Withholding() As Double Dim adjPay As Double = Wages .7 Case Is <= 7021 Return ((adjPay .25) + 163.1455) * 0.22 End Select .062 * (106800 . medicare As Double If (YearToDate + Wages) <= 106800 Then socialSecurityBenTax = 0.28) + 368.

7212) * 0.1 Case Is <= 696 Return (adjPay .200) * 0.138) * 0.87 Case Else Return ((adjPay .35 Case Is <= 7212 Return ((adjPay .2 Case Is <= 1279 Return ((adjPay .25) + 80.29 End Select End If End Function End Class 'Tax .15 + 6.6 Case Is <= 3338 Return ((adjPay .1279) * 0.Student Solutions Manual (Page 185 of 211) Else 'Withholding table for single earners Select Case adjPay Case Is <= 138 Return 0 Case Is <= 200 Return (adjPay .33) + 802.35) + 2081.3338) * 0.28) + 226.696) * 0.

. 17.. 9.. 'hide the exponentiation if checked If radCalculator. 64 5.Visible = True btnDivide.) Handles _ radAddingMachine.3 1. not MustOverride. 15.Visible = False btnExponentiation. The keyword Overrides should be Inherits.Visible = False btnDivide. The Hi function should be declared with the Overrides keyword in class Cowboy.. The Hello class should be declared with the MustInherit keyword. The Hi function should be declared with the Overridable keyword in class Hello and with the keyword Overrides keyword in class Aussie. The Hello class should be declared with the MustInherit keyword.CheckedChanged 'Show the multiply and divide functionality.Checked Then btnMultiply. and the function Hi should be declared with the MustOverride keyword.) Handles _ radCalculator. Can move Has jointed limbs and no backbone 7. 4 3.Visible = True btnExponentiation. 13. 11.Visible = False End If End Sub Private Sub radCalculator_CheckedChanged(.CheckedChanged 'Hide the multiply.Student Solutions Manual (Page 186 of 211) EXERCISES 11. 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(.Checked Then btnMultiply.Visible = False End If End Sub . divide and exponentiation 'functionality if checked If radAddingMachine.

Visible = True End If End Sub Private Sub btnAdd_Click(.Checked Then 'If calculator selected.Text = CStr(adder. use it to get the result calc..Text) calc.Text) txtResult.) Handles _ radScientific.Subtract()) End If End Sub .Text) txtResult.Text) txtResult.num2 = CDbl(txtNumber2.Text = CStr(adder.num1 = CDbl(txtNumber1.Text = CStr(sci.Text = CStr(calc.. use it to get the result sci.num2 = CDbl(txtNumber2. divide and exponentiation 'functionality if checked If radScientific..Text) sci.num1 = CDbl(txtNumber1. use it to get the result adder.Text) calc.Text) adder.Checked Then 'If adding machine selected.Add()) ElseIf radCalculator..num2 = CDbl(txtNumber2.. use it to get the result calc.Checked Then btnMultiply.num2 = CDbl(txtNumber2.Text) adder.Text = CStr(calc.Visible = True btnExponentiation.Text) txtResult.Visible = True btnDivide.Checked Then 'If calculator selected.num1 = CDbl(txtNumber1.num2 = CDbl(txtNumber2. use it to get the result adder.Text) sci.Student Solutions Manual (Page 187 of 211) Private Sub radScientific_CheckedChanged(.Subtract()) ElseIf radCalculator. use it to get the result sci.Text) txtResult.Subtract()) Else 'If scientific calculator selected.num1 = CDbl(txtNumber1.num1 = CDbl(txtNumber1.num2 = CDbl(txtNumber2.num1 = CDbl(txtNumber1.Text) txtResult.Add()) Else 'If scientific calculator selected.Text = CStr(sci.CheckedChanged 'Show the multiply.Click 'Add two numbers If radAddingMachine.Add()) End If End Sub Private Sub btnSubtract_Click(.) Handles btnSubtract..) Handles btnAdd.Click If radAddingMachine.Checked Then 'If adding machine selected.

Divide()) End If End Sub Private Sub btnExponentiation_Click(.num1 = CDbl(txtNumber1. sci.Text = CStr(sci. calc.Exponentiation()) End Sub End Class 'frmCalculator Class AddingMachine Property num1() As Double Property num2() As Double Function Add() As Double 'Add the two number Return num1 + num2 End Function Function Subtract() As Double 'Subtract the two number Return num1 .Multiply()) End If End Sub Private Sub btnDivide_Click(.num2 = CDbl(txtNumber2.num1 = CDbl(txtNumber1...Text) txtResult.num2 End Function End Class 'AddingMachine .Text) txtResult.num2 = CDbl(txtNumber2.Text) txtResult.Click If radCalculator.Checked Then 'If calculator selected.num1 = CDbl(txtNumber1.Multiply()) Else 'If scientific calculator selected. use it to get the result.Text) txtResult.num1 = CDbl(txtNumber1.Text = CStr(calc. calc. use it to get the result.Text) calc.num2 = CDbl(txtNumber2.Click sci..) Handles btnDivide.num2 = CDbl(txtNumber2.Student Solutions Manual (Page 188 of 211) Private Sub btnMultiply_Click(.Text = CStr(sci. use it to get the result.Divide()) Else 'If scientific calculator selected.Text) sci.Text) txtResult.Text) sci.) Handles btnMultiply.) Handles _ btnExponentiation...Click If radCalculator.num2 = CDbl(txtNumber2.Text) calc.Text = CStr(calc.Checked Then 'If calculator selected.Text) sci.Text = CStr(sci. use it to get the result sci.num1 = CDbl(txtNumber1..

Student Solutions Manual (Page 189 of 211) Class Calculator Inherits AddingMachine 'Calculator inherits properties num1 and num2 'and functions add() and subtract(). Subtract(). and Divide. Function Multiply() As Double 'Multiply the two number Return num1 * num2 End Function Function Divide() As Double 'Divide the two number Return num1 / num2 End Function End Class 'Calculator Class ScientificCalculator Inherits Calculator 'ScientificCalculator inherits properties num1 and num2 'and methods Add(). Multiply. Function Exponentiation() As Double 'Raise the first number by the second Return num1 ^ num2 End Function End Class 'ScientificCalculator .

00 Deposit(2) End Sub End Class 'FastTrackRegister .Text = CStr(tollBooth.amount End Sub Public ReadOnly Property Balance() As Double Get Return m_balance End Get End Property End Class 'CashRegister Class FastTrackRegister Inherits CashRegister Private m_count As Integer Public ReadOnly Property Count() As Integer Get Return m_count End Get End Property Sub ProcessCar() m_count += 1 Deposit(1) End Sub 'Process a car: $1..Text = FormatCurrency(tollBooth.Student Solutions Manual (Page 190 of 211) 19.ProcessTruck() End If txtRevenue..ProcessCar() Else tollBooth.) Handles btnProcess.Count) End Sub End Class 'frmRegister Class CashRegister Private m_balance As Double Sub Deposit(ByVal amount As Double) m_balance += amount End Sub Sub WithDrawal(ByVal amount As Double) m_balance = m_balance . Public Class frmRegister Dim tollBooth As New FastTrackRegister() Private Sub btnProcess_Click(.Click If radCar.Balance) txtNumVehicles.00 Sub ProcessTruck() m_count += 1 'Process a truck: $2.Checked Then tollBooth.

Text = "" txtQuantity.Cost = CDbl(txtCost.Clear() txtQuantity..) Handles btnOrder.Name = txtName.Text book.Clear() txtCost.Text) book.Student Solutions Manual (Page 191 of 211) 11.Text) 'Increment counter and store book into array books(count) = book count += 1 'Reset input fields and focus on the quantity txtName. Public Class frmBookstore Dim books(10) As Book Dim count As Integer 'Stores books 'Last stored book Private Sub btnOrder_Click(..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.Quantity = CInt(txtQuantity.Focus() End Sub .3 Exercise 21 21.

Click 'Display inventory of books Dim num As Integer = 0 Dim textb As Integer = 0 Dim cost As Double = 0 Dim value As Double = 0 'Aggregate totals For i As Integer = 0 To count .Quantity End If Next 'Display totals lstInventory.Price num += books(i).Add("Total value: " & FormatCurrency(value)) lstInventory.Items.1 cost += books(i).Quantity 'Count textbooks If TypeOf books(i) Is Textbook Then textb += books(i).Add("Number of books: " & num) lstInventory.Items.4 * Cost '40% markup End Get End Property End Class 'Tradebook Class Textbook Inherits Book Overrides ReadOnly Property Price() As Double Get Return 1.Clear() lstInventory.Quantity * books(i).) Handles btnInventory..Cost value += books(i).Items.2 * Cost '20% markup End Get End Property End Class 'Textbook .Add("Number of textbooks: " & textb) End Sub End Class 'frmBookstore MustInherit Class Book Public Property Name() As String Public Property Cost() As Double Public Property Quantity() As Integer 'Children must override this property MustOverride ReadOnly Property Price() As Double End Class 'Book Class Tradebook Inherits Book Overrides ReadOnly Property Price() As Double Get Return 1.Items.Add("Total cost: " & FormatCurrency(cost)) lstInventory.Student Solutions Manual (Page 192 of 211) Private Sub btnInventory_Click(..Items.Quantity * books(i).

Items.) Handles btnFind.1 lstOutput.purchPrice) / redemValue) txtIntRate.Text) For i As Integer = 1 To num ...Text) > max Then max = CDbl(txtSecondNum.Click Dim max As Double = CDbl(txtFirstNum.Add(num) End Sub 5.Items.purchPrice) / purchPrice) End Sub .) Handles btnDisplay...Text = FormatPercent((redemValue .) Handles btnCalculate. Protected Sub btnFind_Click(.Text = CStr(max) End Sub 3.Text = FormatPercent((redemValue .Add(i & " potato") Next lstOutput.Text) > max Then max = CDbl(txtThirdNum..Text) txtDiscRate.Click Dim purchPrice As Double = CDbl(txtPurPrice.Text) End If If CDbl(txtThirdNum.Text) If CDbl(txtSecondNum. Protected Sub btnDisplay_Click(. Protected Sub btnCalculate_Click(.Student Solutions Manual (Page 193 of 211) CHAPTER 12 EXERCISES 12.Text) Dim redemValue As Double = CDbl(txtRedValue.Text) End If txtLargestNum..1 1.Click Dim num As Integer = CInt(txtNumber.

) Handles btnAdd.Click If IsNumeric(txtFirstNum.Text) Then txtMessage.Text = "Each text box is empty or has an improper entry.Text) Then txtSum." End If Else txtMessage..Text = "The first text box is empty or has an improper entry. Protected Sub btnAdd_Click(." Else txtMessage.Text) Then If Not IsNumeric(txtSecondNum.Text) And IsNumeric(txtSecondNum.Student Solutions Manual (Page 194 of 211) 7..Text)) ElseIf Not IsNumeric(txtFirstNum.Text = "The second text box is empty or has an improper entry.Text = CStr(CDbl(txtFirstNum.Text) + CDbl(txtSecondNum." End If End Sub .

ByVal num2 As Double) As Double If num1 <= num2 Then Return num1 Else Return num2 End If End Function . grade3) ElseIf grade2 <= grade1 And grade2 <= grade3 Then first = Max(grade1.Click Dim grade1 As Double = CDbl(txtGrade1. ByVal grade2 As Double.Text = "The highest two grades are " & first & " and " & second & ". grade3) End Sub Sub DisplayHighestTwo(ByVal grade1 As Double." End Sub Function Max(ByVal num1 As Double. second As Double If grade1 <= grade2 And grade1 <= grade3 Then first = Max(grade2. grade2.Text) Dim grade2 As Double = CDbl(txtGrade2. Protected Sub btnDetermine_Click(. ByVal num2 As Double) As Double If num1 <= num2 Then Return num2 Else Return num1 End If End Function Function Min(ByVal num1 As Double. grade3) Else first = Max(grade1.) Handles btnDetermine. grade2) End If txtOutput.Text) Dim grade3 As Double = CDbl(txtGrade3.Text) DisplayHighestTwo(grade1.. grade2) second = Min(grade1.. ByVal grade3 As Double) Dim first.Student Solutions Manual (Page 195 of 211) 9. grade3) second = Min(grade1. grade3) second = Min(grade2.

Text = word1 & " before " & word2 End Sub Sub SwapWords(ByRef word1 As String.Length For j As Integer = m . temp As String = "" m = info. ByRef word2 As String) Dim temp As String temp = word1 word1 = word2 word2 = temp End Sub 13.Click Dim word1 As String = txtFirst.) Handles btnReverse. word2) End If txtOutput.Text If (word2 < word1) Then SwapWords(word1.Substring(j. Protected Sub btnReverse_Click(.Text Dim word2 As String = txtSecond.) Handles btnSort. 1) Next Return temp End Function . Protected Sub btnSort_Click(.Student Solutions Manual (Page 196 of 211) 11.Click txtBackwards.Text = Reverse(txtWord..Text) End Sub Function Reverse(ByVal info As String) As String Dim m As Integer..1 To 0 Step -1 temp &= info...

Average txtAverage.ReadAllLines(MapPath("App_Data\States.File.EndsWith("ia") Then lstOutput.Items.) Handles btnEvaluate.1 If grades(i) > avg Then counter += 1 End If Next txtAboveAvg.File.ReadAllLines(MapPath("App_Data\Final.Add(state) End If Next End Sub .Text = FormatPercent(counter / grades.Count) End Sub 17.. Protected Sub btnDisplay_Click(. Protected Sub btnEvaluate_Click(.Student Solutions Manual (Page 197 of 211) 15.txt")) For Each state As String In states If state.txt")) Dim grades(strGrades.) Handles btnDisplay.Count .Text = FormatNumber(avg) For i As Integer = 0 To grades..Count .Click Dim strGrades() As String = IO.Click Dim states() As String = IO..1 grades(i) = CDbl(strGrades(i)) Next avg = grades.1) As Double Dim avg As Double Dim counter As Integer For i As Integer = 0 To grades..Count .

Clear() For Each state As String In states If state...ReadAllLines(MapPath("App_Data\States.Add(state) End If Next End Sub .) Handles btnDisplay.Text lstOutput.Items.Student Solutions Manual (Page 198 of 211) 19.txt")) Dim letter As String = txtLetter.File.Click Dim states() As String = IO. Protected Sub btnDisplay_Click(.StartsWith(letter) Then lstOutput.Items.

Items.Remove(lstStates. chkMemory.ReadAllLines(MapPath("App_Data\States.CheckedChanged.Checked Then cost += 30 End If If chkMemory.. 'Note: The AutoPostBack and CausesValidation properties were 'set to True for each check box. chkUpgradedVideo..Text) txtNumStates.Student Solutions Manual (Page 199 of 211) EXERCISES 12.txt")) Dim query = From state In states Order By state Select state lstStates.Count) End Sub 12.2 1.Items.Text = FormatCurrency(cost) End Sub .Count) End If End Sub Protected Sub btnDelete_Click(.DataSource = query lstStates. chkModem.2 Exercise 1 3.SelectedIndexChanged.Checked Then cost += 200 End If If chkModem. If rblModel. Protected Sub rblModel_SelectedIndexChanged(..Checked Then cost += 120 End If txtOutput..CheckedChanged.File.DataBind() txtNumStates.) Handles btnDelete.Click lstStates.Items. Protected Sub Page_Load(.Text = CStr(lstStates.) Handles Me..Text = CStr(lstStates.) Handles _ rblModel.Text = "Deluxe" Then cost += 1000 Else cost += 1500 End If If chkUpgradedVideo..Load If Not IsPostBack Then Dim states() As String = IO.CheckedChanged Dim cost As Double = 0 'Add amounts to the cost based upon selections.

Click Dim fahrenheitTemp.. Protected Sub btnConvert_Click(. celsiusTemp As Double fahrenheitTemp = CDbl(txtTempF.Text = CStr(celsiusTemp) End Sub Function FtoC(ByVal t As Double) As Double Return (5 / 9) * (t ..) Handles btnConvert.Text) celsiusTemp = FtoC(fahrenheitTemp) txtTempC.32) End Function .Student Solutions Manual (Page 200 of 211) 5.

Text = "The highest two grades are " & first & " and " & second & ". ByVal num2 As Double) As Double If num1 <= num2 Then Return num2 Else Return num1 End If End Function . grade2) If first = grade1 Then second = Max(grade2.Text) Dim grade2 As Double = CDbl(txtGrade2. ByVal grade3 As Double) Dim first." End Sub Function Max(ByVal num1 As Double.Student Solutions Manual (Page 201 of 211) 7.. Protected Sub btnDetermine_Click(.Text) Dim grade3 As Double = CDbl(txtGrade3. ByVal grade2 As Double. grade3) Else second = Max(grade1. grade2. grade3) End Sub Sub DisplayHighestTwo(ByVal grade1 As Double.) Handles btnDetermine. grade3) End If txtOutput.Text) DisplayHighestTwo(grade1..Click Dim grade1 As Double = CDbl(txtGrade1. second As Double first = Max(grade1.

Clear() If word1 <= word2 Then lstOutput. Protected Sub btnAlphabetize_Click(.Student Solutions Manual (Page 202 of 211) 9.Items.Items.Add(word1) End If End Sub .) Handles btnAlphabetize..Text Dim word2 = txtWord2.Text DisplayWords(word1. ByVal word2 As String) lstOutput.Items.Add(word2) Else lstOutput..Add(word2) lstOutput.Items. word2) End Sub Sub DisplayWords(ByVal word1 As String.Click Dim word1 = txtWord1.Add(word1) lstOutput. Minimum is "a" and Maximum is "zzzzzzz".Items. 'In RangeValidator controls.

Cells(1). data(5)) Where state = stateAbbrev Select name.ToUpper Dim query = From justice In justices Let data = justice.Text = "Years Served" End Sub Function YearsServed(ByVal enter As Double.) Handles btnDisplay.HeaderRow.enter) Else Return (leave .txt")) Dim stateAbbrev As String = txtState.Split(". yrsServed grvJustices.DataSource = query grvJustices.Text = "Appointing President" grvJustices.Text = "Justice" grvJustices.Student Solutions Manual (Page 203 of 211) 11. pres..Click Dim justices() As String = IO.Cells(2)."c) Let name = data(0) & " " & data(1) Let pres = data(2) Let state = data(3) Let yrsServed = YearsServed(data(4).ReadAllLines(MapPath("App_Data\Justices.HeaderRow.enter) End If End Function . Protected Sub btnDisplay_Click(. ByVal leave As Double) As Double If leave = 0 Then Return (Now.Text.Year .HeaderRow.File.Cells(0).DataBind() grvJustices..

AxisY. popGrowth chtMegacities.name.pop2010 chtMegacities.) Handles btnDisplay.ChartAreas(0).ChartAreas(0).Title = "City" chtMegacities.3 1.DataBindTable(query.DataBindTable(query.pop2010) / city..Interval = 1 chtMegacities.city.Click Dim mcDC As New MegacitiesDataContext Dim query = From city In mcDC.Title = "City" chtMegacities.ChartAreas(0).AxisX.AxisX. city. "name") chtMegacities.pop2010 Order By popGrowth Descending Select city..Title = "Percentage Population Growth" End Sub ..name.) Handles btnDisplay.ChartAreas(0).Click Dim mcDC As New MegacitiesDataContext Dim query = From city In mcDC.AxisX.AxisX.Student Solutions Manual (Page 204 of 211) EXERCISES 12. Protected Sub btnDisplay_Click(.Cities Let popGrowth = 100 * (city.Cities Order By city.ChartAreas(0).AxisY.name Descending Select city.Interval = 1 chtMegacities. Protected Sub btnDisplay_Click(.ChartAreas(0).Title = "2010 Population in Millions " End Sub 3.. "name") chtMegacities.pop2015 .

AxisX.Click Dim avePop As Double Dim mcDC As New MegacitiesDataContext Dim query = From city In mcDC. "name") chtMegacities.pop2015 >= avePop Select city.Title = "City with Above-Average Population" chtMegacities. Protected Sub btnDisplay_Click(.Countries On city.. country.Title = "2010 Population in Millions" End Sub 7.AxisY.ChartAreas(0).Title = "2010 Pop.pop2010 chtMegacities.) Handles btnDisplay.Interval = 1 chtMegacities.DataBindTable(query.ChartAreas(0).) Handles btnDisplay.AxisX.Cities Join country In mcDC.DataBindTable(query2.AxisX.ChartAreas(0).ChartAreas(0). "name") chtMegacities.country Equals country.Title = "City" chtMegacities.ChartAreas(0).AxisY.Interval = 1 chtMegacities.Average Dim query2 = From city In mcDC.Cities Where city.pop2010 avePop = query.. of Country in Millions" End Sub .pop2010 chtMegacities.Click Dim mcDC As New MegacitiesDataContext Dim query = From city In mcDC.name Select city. city.name.Student Solutions Manual (Page 205 of 211) 5. Protected Sub btnDisplay_Click(.ChartAreas(0).Cities Select city.AxisX..name..

Protected Sub btnDisplay_Click(.Interval = 1 chtMegacities.ChartAreas(0).Title = "2010 Population in Millions" End Sub .AxisX.pop2010 chtMegacities.DataBindTable(query. country.Student Solutions Manual (Page 206 of 211) 9.) Handles btnDisplay.Countries Order By country.Title = "Country" chtMegacities.AxisY.ChartAreas(0).pop2010 Descending Select country.name..Click Dim mcDC As New MegacitiesDataContext Dim query = From country In mcDC..ChartAreas(0). "name") chtMegacities.AxisX.

DataSource = query GridView1.DataBind() GridView1.Student Solutions Manual (Page 207 of 211) 11.. Protected Sub btnDisplay_Click(.Text = "Population Increase" End Sub 13. 0) Order By pop Descending Select country.HeaderRow.pop2015 .Click Dim mcDC As New MegacitiesDataContext Dim query = From country In mcDC..DataBind() GridView1.Text = "Population in 2010" End Sub .) Handles btnDisplay.DataSource = query GridView1.name. formattedPopIncr GridView1.) Handles btnDisplay. Protected Sub btnDisplay_Click(.Cells(0).pop2010 Let formattedPop = FormatNumber(pop.city.name.pop2010) / city.HeaderRow.Click Dim mcDC As New MegacitiesDataContext Dim query = From city In mcDC.Cells(1).Text = "Country" GridView1.Text = "City" GridView1.HeaderRow.Cells(0).pop2010 Let formattedPopIncr = FormatPercent(popIncr) Order By popIncr Descending Select city. formattedPop GridView1..Cities Let popIncr = (city..Cells(1).HeaderRow.Countries Let pop = 1000000 * country.

AxisY.country.Countries On city.Text = "Currency" End Sub 17.Cells(1).monetaryUnit GridView1.Student Solutions Manual (Page 208 of 211) 15.HeaderRow.sales2008 Descending Let amount = chain.DataSource = query GridView1.Text = "City" GridView1. country.country Equals country. amount chtPizzaChains.Cells(2). Protected Sub btnDisplay_Click(.) Handles btnDisplay. "name") chtPizzaChains.Cities Join country In mcDC.sales2008 / 1000000 Select chain..name Order By city.DataBindTable(query.Title = "2008 Sales in Billions" End Sub .name.ChartAreas(0).Pizzerias Order By chain.ChartAreas(0).Click Dim mcDC As New MegacitiesDataContext Dim query = From city In mcDC.) Handles btnDisplay...AxisX.Text = "Country" GridView1.name.HeaderRow. Protected Sub btnDisplay_Click(.Cells(0)..DataBind() GridView1.HeaderRow.Interval = 1 chtPizzaChains.AxisX.name Ascending Select city. city.Click Dim pizzaDC As New PizzaDataContext Dim query = From chain In pizzaDC.Title = "Pizzeria" chtPizzaChains.ChartAreas(0).

AxisY. growth chtPizzaChains.AxisX.sales2008 / 1000000 Select chain..name Let sales2007 = chain.ChartAreas(0).AxisX.sales2007 / 1000000 Let sales2008 = chain.ChartAreas(0).name.Student Solutions Manual (Page 209 of 211) 19. Protected Sub btnDisplay_Click(.ChartAreas(0).) Handles btnDisplay.ChartAreas(0).numStores2008 .Interval = 1 chtPizzaChains. sales2007.chain..Pizzerias Let growth = chain.AxisX.AxisX.Title = "Pizzeria" chtPizzaChains.Interval = 1 chtPizzaChains.. sales2008 chtPizzaChains.numStores2007 Order By growth Select chain.DataBindTable(query..ChartAreas(0). "name") chtPizzaChains.DataBindTable(query.AxisY.Click Dim pizzaDC As New PizzaDataContext Dim query = From chain In pizzaDC.ChartAreas(0).Title = "2007 & 2008 Sales in $Billion" End Sub .Title = "Change in Number of Stores" End Sub 21.Click Dim pizzaDC As New PizzaDataContext Dim query = From chain In pizzaDC.) Handles btnDisplay. Protected Sub btnDisplay_Click(.Pizzerias Order By chain.Title = "Pizzeria" chtPizzaChains.name. "name") chtPizzaChains.

sales2007) / chain. Protected Sub btnDisplay_Click(.Pizzerias Order By chain.sales2008 chain.HeaderRow.HeaderRow.numStores2008 txtOutput..Click Dim pizzaDC As New PizzaDataContext Dim query = From chain In pizzaDC..sales2007) Select chain. 0) Let perChange = FormatPercent((chain.Sum.Cells(1). Protected Sub btnDisplay_Click(.DataBind() grvPizzaChains.HeaderRow.Cells(0)..Text = "Pizzeria" grvPizzaChains.) Handles btnDisplay.sales2008 Descending Let for7 = FormatCurrency(chain. perChange grvPizzaChains.DataSource = query grvPizzaChains. 0) Let for8 = FormatCurrency(chain.Text = "Change" End Sub 25. for8.0.Pizzerias Select chain.0.sales2007 * 1000.Click Dim pizzaDC As New PizzaDataContext Dim query = From chain In pizzaDC.Cells(2). for7.Student Solutions Manual (Page 210 of 211) 23. 0) End Sub ..sales2008 * 1000.name.Text = FormatNumber(query.) Handles btnDisplay.HeaderRow.Cells(3).Text = "2007 Sales" grvPizzaChains.Text = "2008 Sales" grvPizzaChains.

Pizzerias Order By chain.Click Dim pizzaDC As New PizzaDataContext Dim query = From chain In pizzaDC.First End Sub ..Student Solutions Manual (Page 211 of 211) 27.name txtOutput.Text = query.) Handles btnDisplay. Protected Sub btnDisplay_Click(.numStores2008 Ascending Select chain..

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer: Get 4 months of Scribd and The New York Times for just $1.87 per week!

Master Your Semester with a Special Offer from Scribd & The New York Times