3.5. Input and OutputFormatting Output with Format FunctionsThe Format functions are used to display numbers in familiar forms and to align numbers. Here are some examples of how numbers are converted to strings with Format functions:
The value of FormatNumber(n, r) is the string containing the number n rounded to r decimal places and displayed with commas as thousands separators. The value of FormatCurrency(n, r) is the string consisting of a dollar sign followed by the value of FormatNumber(n, r). FormatCurrency uses the accountant's convention of denoting negative amounts with surrounding parentheses. The value of FormatPercent(n, r) is the string consisting of the number n displayed as a percent and rounded to r decimal places. With all three functions, r can be omitted. If so, the number is rounded to two decimal places. Strings corresponding to numbers less than one in magnitude have a zero to the left of the decimal point. Also, n can be a number, a numeric expression, or even a string corresponding to a number.
Formatting Output with ZonesData can be displayed in tabular form in a list box. In order to have the items line up nicely in columns, you must
Figure 3.21 (on the next page) shows a line of a list box divided into zones of widths 15 characters, 10 characters, and 8 characters. The leftmost zone is referred to as zone 0, the next zone is zone 1, and so on. These zones are declared in a string with the statement Dim fmtStr As String = "{0, 15}{1, 10}{2, 8}" Figure 3.21. Zones. |
The following program displays information about two colleges in the United States. Note: The endowments are in billions of dollars. The final column tells what fraction of the student body attended public secondary schools.
Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim fmtStr As String = "{0,-10}{1,12}{2,14}{3,12}" With lstColleges.Items .Clear() .Add(String.Format(fmtStr, "College", "Enrollment", _ "Endowment", "Public SS")) .Add(String.Format(fmtStr, "Harvard", 6660, 19.2, 0.659)) .Add(String.Format(fmtStr, "Yale", 5278, 10.1, 0.532)) End With End Sub [Run, and click on the button.]
|
There is no limit to the number of zones, and the zones can be of any widths. In addition, by placing a colon and formatting symbols after the width, you can instruct Visual Basic to specially format numeric data. (String data are not affected.) The most used formatting symbols consist of a letter (n for number, C for currency, or P for percent) followed by a digit specifying the number of decimal places. If there is no digit after the letter, two decimal places are displayed. Here are some examples of such formatting:
Zone Format Term | Number to Be Formatted | Number Displayed |
---|---|---|
{1, 12:N3} | 1234.5679 | 1,234.568 |
{1, 12:N0} | 34.6 | 34 |
{1, 12:C1} | 1234.567 | $1,234.6 |
{1, 12:P} | 0.569 | 56.90% |
If the second line of the program in Example 1 is replaced with
Dim fmtStr As String = "{0,-10}{1,12:N0}{2,14:C}{3,12:P0}"
the output will be as follows.
The format strings considered so far consist of a sequence of pairs of curly brackets. We also can insert spaces between successive pairs of brackets. If so, the corresponding zones in the output will be separated by those spaces. The lines of code
Dim fmtStr As String = "{0, 5} {1, -5}" 'Two spaces after the 'first right curly bracket With lstOutput.Items .Add("12345678901234567890") .Add(String.Format(fmtStr, 1, 2)) End With
produce the output
12345678901234567890 1 2
So far, we have relied on assignment statements and text box controls to assign data to variables. Data also can be stored in files and accessed with a StreamReader object or supplied by the user with an input dialog box.
In Chapter 1, we saw how to create text files with Windows Notepad. We will assume that the files created with Notepad have one item of information per line. Figure 3.22 shows a sample file giving payroll information. Each set of three lines gives the name of a person, their hourly wage, and the number of hours that person worked during the week.
Mike Jones |
7.35 |
35 |
John Smith |
6.75 |
33 |
Data stored in a file can be read in order (that is, sequentially) and assigned to variables with the following steps:
1. | Execute a statement of the form Dim readerVar As IO.StreamReader A StreamReader is an object from the Input/Output class that can read a stream of characters coming from a disk or coming over the Internet. The Dim statement declares the variable readerVar to be of type StreamReader. |
2. | Execute a statement of the form readerVar = IO.File.OpenText(filespec) where filespec identifies the file to be read. This statement establishes a communications link between the computer and the disk drive for reading data from the disk. Data then can be input from the specified file and assigned to variables in the program. This assignment statement is said to "open the file for input." Just as with other variables, the declaration and assignment statements in Steps 2 and 3 can be combined into the single statement Dim readerVar As IO.StreamReader = IO.File.OpenText(filespec) |
3. | Read items of data in order, one at a time, from the file with the ReadLine method. Each datum is retrieved as a string. A statement of the form strVar = readerVar.ReadLine numVar = CDbl(readerVar.ReadLine) Note: If all the data in a file have been read by ReadLine statements and another item is requested by a ReadLine statement, the item retrieved will have the value Nothing. |
4. | After the desired items have been read from the file, terminate the communications link set in Step 3 with the statement readerVar.Close() |
Consider the following program that displays the address of the White House. (The form design for all examples in this section consists of a button and a text or list box.) Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim houseNumber As Double Dim street, address As String houseNumber = 1600 street = "Pennsylvania Ave." address = houseNumber & " " & street txtAddr.Text = "The White House is located at " & address End Sub [Run, and then click the button. The following is displayed in the text box.] The White House is located at 1600 Pennsylvania Ave. |
Let's now rewrite this program so that it uses a file for input and produces the same output. First, use Windows Notepad to create the file DATA.TXT containing the following two lines:
1600 Pennsylvania Ave.
In the following code, the fifth line of the event procedure reads the first row of data as the string "l600", converts its type to Double, and assigns it to the variable houseNumber. (Visual Basic records that this row of data has been used.) The sixth line looks for the next available line of data, "Pennsylvania Ave.", and assigns it to the string variable street.
Note: You will have to alter the information inside the parentheses in the second line to tell Visual Basic where the file DATA.TXT is located. For instance, if the file is in the root folder of a diskette in drive A, then the parentheses should contain the string "A:\DATA.TXT". If the file is located in the subfolder My Programs of the C drive, then the parentheses should contain the string "C:\My Programs\DATA.TXT". In this book, we will always write just the name of the file and leave it up to you to add an appropriate path.
Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim sr As IO.StreamReader = IO.File.OpenText("DATA.TXT") Dim houseNumber As Double Dim street, address As String houseNumber = CDbl(sr.ReadLine) street = sr.ReadLine sr.Close() address = houseNumber & " " & street txtAddr.Text = "The White House is located at " & address End Sub
Each Visual Basic program is contained in a folder with the name you specified in the Save Project window. This folder holds the files for the program and contains three subfolders named bin, My Project, and obj. The folder bin contains two subfolders named Debug and Release. If no path is specified for a text file, Visual Basic will look for the file in the Debug subfolder for the program. Every program from the companion website for this book that reads a file assumes that the file is located in the Debug subfolder for the program. Therefore, even after you copy the contents of the Programs folder onto a hard drive, the programs will continue to execute properly without your having to alter any paths.
The following program uses the file PAYROLL.TXT shown in Figure 3.22. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim sr As IO.StreamReader = IO.File.OpenText("PAYROLL.TXT") 'The file PAYROLL.TXT is in the Debug subfolder 'of the bin subfolder of the folder 3-5-3. Dim name As String Dim hourlyWage, hoursWorked, salary As Double name = sr.ReadLine hourlyWage = CDbl(sr.ReadLine) hoursWorked = CDbl(sr.ReadLine) salary = hourlyWage * hoursWorked lstPayroll.Items.Add(name & " " & FormatCurrency(salary)) name = sr.ReadLine hourlyWage = CDbl(sr.ReadLine) hoursWorked = CDbl(sr.ReadLine) sr.Close() salary = hourlyWage * hoursWorked lstPayroll.Items.Add(name & " " & FormatCurrency(salary)) End Sub [Run, and then click the button. The following is displayed in the list box.] Mike Jones $257.25 John Smith $222.75 |
In certain situations, we must read the data in a file more than once. This is accomplished by reopening the file with a second assignment statement of the form sr = IO.File.OpenText(filespec). This statement sets a pointer to the first line of data in the specified file. Each time a ReadLine method is executed, the line pointed to is read, and the pointer in then moved to the next line. After the last line of data is read, the pointer is said to be at the end of the file.
The following program takes the average annual amounts of money spent by single-person households for several categories and converts these amounts to percentages. The data are read once to compute the total amount of money spent and then read again to calculate the percentage for each category. Note: These figures were compiled for a recent year by the Bureau of Labor Statistics. The file COSTS.TXT consists of the following eight lines: Transportation 4251 Housing 8929 Food 3414 Other 8829 Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim sr As IO.StreamReader = IO.File.OpenText("COSTS.TXT") Dim total As Double 'Total annual amount spent Dim category As String Dim amount As Double 'Amount spent on category Dim fmtStr As String = "{0,-15}{1,8:P}" category = sr.ReadLine 'Read the first category from the file total += CDbl(sr.ReadLine) 'Increment total by the amount 'associated with the category category = sr.ReadLine 'Read the next category from the file total += CDbl(sr.ReadLine) category = sr.ReadLine total += CDbl(sr.ReadLine) category = sr.ReadLine total += CDbl(sr.ReadLine) sr.Close() [Run, and then click the button. The following is displayed in the list box.] Transportation 16.72 % Housing 34.12 % Food 13.43 % Other 34.73 % |
Normally, a text box is used to obtain input, where the type of information requested is specified in a label adjacent to the text box. Sometimes, we want just one piece of input and would rather not have a text box and label stay on the screen forever. The problem can be solved with an input dialog box. When a statement of the form
stringVar = InputBox(prompt, title)
is executed, an input dialog box similar to the one shown in Figure 3.23 pops up on the screen. After the user types a response into the text box at the bottom of the screen and presses Enter (or clicks OK), the response is assigned to the string variable. The title argument is optional and provides the text that appears in the Title bar. The prompt argument is a string that tells the user what information to type into the text box.
When you type the opening parenthesis following the word InputBox, the editor displays a line containing the general form of the InputBox statement. See Figure 3.24. This feature of IntelliSense is called Parameter Info. Optional parameters are surrounded by square brackets. All the parameters in the general form of the InputBox statement are optional except for prompt.
In the following enhancement to Example 2, the file name is provided by the user in an input dialog box. We assume that the program is contained in the subfolder Debug of the program folder. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim sr As IO.StreamReader Dim fileName, prompt, title, street As String Dim houseNumber As Double prompt = "Enter the name of the file containing the information." title = "Name of File" fileName = InputBox(prompt, title) 'We assume the file is located in the subfolder Debug 'of the bin subfolder of the folder 3-5-5. sr = IO.File.OpenText(fileName) houseNumber = CDbl(sr.ReadLine) street = sr.ReadLine sr.Close() txtAddr.Text = "The White House is located at " & _ houseNumber & " " & street & "." End Sub [Run, and then click the button. The input dialog box of Figure 3.23 appears on the screen. Type "DATA.TXT" into the input dialog box, and click on OK. The input dialog box disappears, and the following appears in the text box.] The White House is located at 1600 Pennsylvania Ave. |
The response typed into an input dialog box is treated as a single string value, no matter what is typed. (Quotation marks are not needed and, if included, are considered as part of the string.) Numeric data typed into an input dialog box should be converted to a number with CDbl or CInt before being assigned to a numeric variable or used in a calculation. Just as with a text box or file, the typed data must be a literal. It cannot be a variable or an expression. For instance, num, 1/2, and 2+3 are not acceptable.
Sometimes you want to grab the user's attention with a brief message such as "Correct" or "Nice try, but no cigar." You want this message only to appear on the screen until the user has read it. This task is easily accomplished with a message dialog box such as the one shown in Figure 3.25. When a statement of the form
MsgBox(prompt, 0, title)
is executed, where prompt and title are strings, a message dialog box appears with prompt displayed and the Title bar caption title and stays on the screen until the user presses Enter, clicks on the box in the upper-right corner, or clicks OK. For instance, the statement
MsgBox("Nice try, but no cigar.", 0, "Consolation")
produces Figure 3.25. You can omit the zero and a value for title and just execute MsgBox(prompt). If you do, the Title bar will contain the name of the program and the rest of the message dialog box will appear as before.
Problems can arise when the wrong type of data is entered as input into a text box. For instance, if the user replies to the request for an age by entering "twenty-one" into a text box, the program can easily crash. Sometimes this type of predicament can be avoided by using a masked text box for input. (In later chapters, we will consider other ways of insuring the integrity of input.)
In the Toolbox, the icon for the MaskedTextBox control consists of a rectangle containing the two characters # and _. The most important property of a masked text box is the Mask property that can be used to restrict the characters entered into the box. Also, the Mask property can be used to show certain characters in the controlto give users a visual cue that they should be entering a phone number or a social security number, for example. Some possible settings for the Mask property are shown in Table 3.3. The first two settings can be selected from a list of specified options. The last three settings generalize to any number of digits, letters, or ampersands. If the Mask property is left blank, then the MaskedTextBox control is nearly identical to the TextBox control.
Setting | Effect |
---|---|
000-00-0000 | The user can only enter a social security number. |
000-0000 | The user can only enter a phone number (without an area code). |
(000)000-0000 | The user can only enter a phone number (with an area code). |
00/00/0000 | The user can only enter a date. |
0000000 | The user can only enter a positive integer consisting of 7 digits. |
LLLLL | The user can only enter a string consisting of 5 letters. |
&&&&&&&& | The user can only enter a string consisting of 8 characters. |
Suppose a form contains a masked text box whose Mask property has the setting 000-00-0000. When the program is run, the string "___-__-____" will appear in the masked text box. The user will be allowed to type a digit in place of each of the eight underscore characters. The hyphens cannot be altered, and no characters can be typed anywhere else in the masked text box.
During run time, the characters 0, L, and & in the setting for a Mask property are replaced by underscore characters that are place holders for digits, letters, and letters and/or spaces, respectively. When the characters "-", "(", ")", or "/" appear in a characters for a Mask property, they appear as themselves in the masked text box and cannot be altered. There are some other mask settings, but these seven will suffice for our purposes.
Figure 3.26 (a) shows a masked text box during design time. It looks like an ordinary text box. However, the Tasks button for the masked text box is used to set the Mask property rather than the Multiline property. Figure 3.26 (b) shows the result of clicking on the Tasks button. Then, clicking on "Set mask" brings up the Input Mask dialog box shown in Figure 3.27. (This input dialog box is the same input dialog box that is invoked when you click on the ellipses in the Mask property's setting box.) You can use this input dialog box to select a commonly used value for the Mask property, such as the social security number or phone number mask, or set and test a custom-designed mask you create with characters such as 0, &, and L. We will use the prefix mtxt for the names of masked dialog boxes.
The statement Dim sr As IO.StreamReader = IO.File.OpenText("DATA.TXT") will be used frequently in this book, albeit with a different file name each time. You can store this line of code (or any frequently used fragment of code) for later reuse by highlighting it and dragging it from the Code window into the Toolbox. To reuse the code, just drag it back from the Toolbox to the Code window. A copy of the code will remain in the Toolbox for further use. Alternately, you can click on the location in the Code window where you want the code to be inserted, and then double-click on the code in the Toolbox.
1. | Is the statement txtOutput.Text = FormatNumber(12345.628, 1) correct, or should it be written txtOutput.Text = CStr(FormatNumber(12345.628, 1)) |
2. | What is the difference in the outcomes of the following two sets of code? strVar = InputBox("How old are you?", "Age") numVar = CDbl(strVar) txtOutput.Text = numVar numVar = CDbl(InputBox("How old are you?", "Age") txtOutput.Text = numVar |
In Exercises 1 through 30, determine the output produced by the lines of code.
1. | txtOutput.Text = FormatNumber(1234.56, 0) |
2. | txtOutput.Text = FormatNumber(-12.3456, 3) |
3. | txtOutput.Text = FormatNumber(1234, 1) |
4. | txtOutput.Text = FormatNumber(12345) |
5. | txtOutput.Text = FormatNumber(0.012, 1) |
6. | txtOutput.Text = FormatNumber(5 * (10 ^ -2), 1) |
7. | txtOutput.Text = FormatNumber(-2/3) |
8. | Dim numVar As Double = Math.Round(1.2345, 1) txtOutput.Text = FormatNumber(numVar) |
9. | Dim numVar As Double = Math.Round(12345.9) txtOutput.Text = FormatNumber(numVar, 3) |
10. | Dim numVar As Double = Math.Round(12.5) txtOutput.Text = FormatNumber(numVar, 0) |
11. | Dim numVar As Double = Math.Round(11.5) txtOutput.Text = FormatNumber(numVar, 0) |
12. | txtOutput.Text = FormatCurrency(1234.5) |
13. | txtOutput.Text = FormatCurrency(12345.67, 0) |
14. | txtOutput.Text = FormatCurrency(-1234567) |
15. | txtOutput.Text = FormatCurrency(-0.225) |
16. | txtOutput.Text = FormatCurrency(32 * (10 ^ 2)) |
17. | txtOutput.Text = FormatCurrency(4 / 5) |
18. | txtOutput.Text = FormatPercent(0.04, 0) |
19. | txtOutput.Text = FormatPercent(0.075) |
20. | txtOutput.Text = FormatPercent(-.05, 3) |
21. | txtOutput.Text = FormatPercent(1) |
22. | txtOutput.Text = FormatPercent(0.01) |
23. | txtOutput.Text = FormatPercent(2 / 3) |
24. | txtOutput.Text = FormatPercent(3 / 4, 1) |
25. | txtOutput.Text = "Pay to France " & FormatCurrency(27267622) |
26. | txtOutput.Text = "Manhattan was purchased for " & FormatCurrency(24) |
27. | Dim popUSover24 As Double = 177.6 'Million Dim collegeGrads As Double = 45.5 'Million '45.5/177.6 = 0.2561937 txtOutput.Text = FormatPercent(collegeGrads / popUSover24, 1) & _ " of the U.S. population 25+ years old are college graduates." |
28. | Dim degrees As String = FormatNumber(1711500, 0) txtOutput.Text = degrees & " degrees were conferred." |
29. | txtOutput.Text = "The likelihood of Heads is " & _ FormatPercent(1 / 2, 0) |
30. | txtOutput.Text = "Pi = " & FormatNumber(3.1415926536, 4) |
In Exercises 31 through 40, determine the output produced by the lines of code. Assume that Courier New is the font for the list box.
31. | Dim fmtStr As String = "{0,-5}{1,5}" With lstOutput.Items .Add("12345678901234567890") .Add(String.Format(fmtStr, 1, 2)) End With |
32. | Dim fmtStr As String = "{0,5}{1,5}" With lstOutput.Items .Add("12345678901234567890") .Add(String.Format(fmtStr, 1, 2)) End With |
33. | Dim fmtStr As String = "{0,5}{1,-5}" With lstOutput.Items .Add("12345678901234567890") .Add(String.Format(fmtStr, 1, 2)) End With |
34. | Dim fmtStr As String = "{0,-5}{1,-5}" With lstOutput.Items .Add("12345678901234567890") .Add(String.Format(fmtStr, 1, 2)) End With |
35. | Dim fmtStr As String = "{0,3}{1,10}" With lstOutput.Items .Add("12345678901234567890") .Add(String.Format(fmtStr, "A", "Alice")) End With |
36. | Dim fmtStr As String = "{0,-13}{1,-10}{2,-7:N0}" With lstOutput.Items .Add("123456789012345678901234567890") .Add(String.Format(fmtStr, "Mountain", "Place", "Ht (ft)")) .Add(String.Format(fmtStr, "K2", "Kashmir", 28250)) End With |
37. | Dim fmtStr As String = "{0,11} {1,-11}" 'Three spaces With lstOutput.Items .Add("12345678901234567890") .Add(String.Format(fmtStr, "College", "Mascot")) .Add(String.Format(fmtStr, "Univ. of MD", "Terrapins")) .Add(String.Format(fmtStr, "Duke", "Blue Devils")) End With |
38. | 'Toss coin twice Dim fmtStr As String = "{0,8} {1,-7:P0}" 'Two spaces With lstOutput.Items .Clear() .Add("12345678901234567890") .Add(String.Format(fmtStr, "Number", "Percent")) .Add(String.Format(fmtStr, "of Heads", "of time")) .Add(String.Format(fmtStr, 0, 1 / 4)) .Add(String.Format(fmtStr, 1, 1 / 2)) .Add(String.Format(fmtStr, 2, 1 / 4)) End With |
39. | 'Elements in a 150 Pound Person Dim fmtStr As String = "{0,-7} {1,-7:N1} {2,-7:P1}" '2 spaces With lstOutput.Items .Clear() .Add("12345678901234567890") .Add(String.Format(fmtStr, "Element", "Weight", "Percent")) .Add(String.Format(fmtStr, "Oxygen", 97.5, 97.5 / 150)) .Add(String.Format(fmtStr, "Carbon", 27, 27 / 150)) End With |
40. | Dim fmtStr As String = "{0,10} {1,-10:C0}" 'Three spaces With lstOutput.Items .Clear() .Add("12345678901234567890") .Add(String.Format(fmtStr, "", "Tuition")) .Add(String.Format(fmtStr, "College", "& Fees")) .Add(String.Format(fmtStr, "Stanford", 24441)) .Add(String.Format(fmtStr, "Harvard", 25128)) End With |
In Exercises 41 through 52, assume that the file DATA.TXT (shown to the right of the code) has been accessed with the statement Dim sr As IO.StreamReader = IO.File.OpenText("DATA.TXT") and closed afterwards with the statement sr.Close(). Determine the output displayed by the lines of code.
41. | Dim num As Double DATA.TXT num = CDbl(sr.ReadLine) 4 txtOutput.Text = CStr(num * num) |
42. | Dim word As String DATA.TXT word = sr.ReadLine speakable txtOutput.Text = "un" & word |
43. | Dim strl, str2 As String DATA.TXT str1 = sr.ReadLine base str2 = sr.ReadLine ball txtOutput.Text = strl & str2 |
44. | Dim numl, num2, num3 As Double DATA.TXT num1 = CDbl(sr.ReadLine) 3 num2 = CDbl(sr.ReadLine) 4 num3 = CDbl(sr.ReadLine) 5 txtOutput.Text = CStr((numl + num2) * num3) |
45. | Dim yrOfBirth, curYr As Double DATA.TXT yrOfBirth = CDbl(sr.ReadLine) 1986 curYr = CDbl(sr.ReadLine) 'Current year 2006 txtOutput.Text = "Age: " & curYr - yrOfBirth |
46. | Dim strl, str2 As String DATA.TXT strl = sr.ReadLine A, my name is str2 = sr.ReadLine Alice txtOutput.Text = strl & " " & str2 |
47. | Dim building As String DATA.TXT Dim numRooms As Double White House building = sr.ReadLine 132 numRooms = CDbl(sr.ReadLine) txtOutput.Text = "The " & building " has " & numRooms & " rooms." |
48. | Dim major As String DATA.TXT Dim percent As Double Computer Science major = sr.ReadLine 1.4 percent = CDbl(sr.ReadLine) txtOutput.Text = "In 2004, " & percent & _ "% of entering college freshmen majored in " & major & "." |
49. | Dim num, sum As Double DATA.TXT sum = 0 123 num = CDbl(sr.ReadLine) 321 sum += num num = CDbl(sr.ReadLine) sum += num txtOutput.Text = "Sum: "& sum |
50. | Dim grade, total, average As Double DATA.TXT Dim numGrades As Integer 85 total = 0 95 numGrades = 0 grade = CDbl(sr.ReadLine) total += grade 'Increase value of total by value of grade numGrades += 1 'Increase value of numGrades by 1 grade = CDbl(sr.ReadLine) total += grade 'Increase value of total by value of grade numGrades += 1 'Increase value of numGrades by 1 average = total / numGrades txtOutput.Text = "Average grade: " & average |
51. | Dim college As String DATA.TXT college = sr.ReadLine Harvard lstOutput.Items.Add(college) Yale sr.Close() sr = IO.File.OpenText("DATA.TXT") college = sr.ReadLine lstOutput.Items.Add(college) |
52. | Dim num As Integer, str As String DATA.TXT num = CInt(sr.ReadLine) 4 str = sr.ReadLine calling birds lstOutput.Items.Add(num & " " & str) 3 sr.Close() French hens sr = IO.File.OpenText("DATA.TXT") num = CInt(sr.ReadLine) str = sr.ReadLine lstOutput.Items.Add(num & " " & str) |
In Exercises 53 through 58, determine the output displayed.
53. | Dim bet As Double 'Amount bet at roulette bet = CDbl(InputBox("How much do you want to bet?", "Wager")) txtOutput.Text = "You might win " & 36 * bet & " dollars." (Assume that the response is 10.) |
54. | Dim word As String word = InputBox("Word to negate:", "Negatives") txtOutput.Text = "un" & word (Assume that the response is "tied".) |
55. | Dim lastName, message, firstName As String lastName = "Jones" message = "What is your first name Mr. " & lastName & "?" firstName = InputBox(message, "Name") txtOutput.Text = "Hello " & firstName & " " & lastName (Assume that the response is "John".) |
56. | Dim intRate, doublingTime As Double 'Current interest rate, time to double intRate = CDbl(InputBox("Current interest rate?", "Interest")) doublingTime = 72 / intRate lstOutput.Items.Add("At the current interest rate, money will") lstOutput.Items.Add("double in " & doublingTime & " years.") (Assume that the response is 4.) |
In Exercises 57 and 58, write a line of code to carry out the task.
57. | Pop up a message dialog box with "Good Advice" in the title bar and the message "Keep cool, but don't freeze." |
58. | Pop up a message dialog box with "Taking Risks Proverb" in the title bar and the message "You can't steal second base and keep one foot on first." |
In Exercises 59 through 66, identify any errors. If the code refers to a file, assume that DATA.TXT (on the right of the code) already has been opened for input.
59. | Dim num As Double DATA.TXT num = CDbl(sr.ReadLine) 1 + 2 txtOutput.Text = CStr(3 * num) |
60. | 'Each line triplet of DATA.TXT contains DATA.TXT 'building, height, # of stories Sears Tower Dim building As String 1454 Dim ht As Double 110 Dim numStories As Integer Empire State Building lstOutput.Items.Clear() 1250 building = sr.ReadLine 102 ht = CDbl(sr.ReadLine) lstOutput.Items.Add(building & " is " & ht & " feet tall.") building = sr.ReadLine ht = CDbl(sr.ReadLine) lstOutput.Items.Add(building & " is " & ht & " feet tall.") |
61. | Dim num As Double num = InputBox("Pick a number from 1 to 10.") txtOutput.Text = "Your number is " & num |
62. | info = InputBox() |
63. | Dim num As Double = FormatNumber(123456) lstOutput.Items.Add(num) |
64. | txtOutput.Text = FormatCurrency($1234) |
65. | Dim fmtStr As String = "{0,20}{1,10}" lstOutput.Items.Add(fmtStr, "Washington", "George") |
66. | MsgBox("Proof", "Pulitzer Prize for Drama") |
In Exercises 67 through 70, write an event procedure starting with a Private Sub btnCompute_Click(. . .) Handles btnCompute.Click statement, ending with an End Sub statement, and having one, two, or three lines for each step. Lines that display data should use the given variable names.
67. | The following steps display information about Americans' eating habits. Assume that the three lines of the file SODA.TXT contain the following data: soft drinks, million gallons, 23.
|
68. | The following steps display the changes in majors for first-year college students from 2003 to 2004. Assume that file MAJORS.TXT consists of six lines containing the following data: Elementary Education, 4.9, 4.6, Psychology, 4.7, 4.6.
|
69. | The following steps calculate the percent increase in a typical grocery basket of goods:
(Test the program with a $215 end-of-year price.) |
70. | The following steps calculate the amount of money earned in a walk-a-thon:
(Test the program with a pledge of $2.00 and a 15-mile walk.) |
In Exercises 71 through 76, give a setting for the Mask property of a masked text box used to input the stated information.
71. | A number from 100 to 999. | ||||||||||||||||||||
72. | A word of ten letters. | ||||||||||||||||||||
73. | A Maryland license plate consisting of three letters followed by three digits. (Example: BHC365) | ||||||||||||||||||||
74. | A California license plate consisting of a digit followed by three letters and then three digits. (Example: 7BHC365) | ||||||||||||||||||||
75. | An ISBN number. [Every book is identified by a ten-character International Standard Book Number (ISBN). The first nine characters are digits and the last character is either a digit or the letter X.] (Example: 0-32-108599-X). | ||||||||||||||||||||
76. | A two-letter state abbreviation. (Example: CA) | ||||||||||||||||||||
77. | Table 3.4 summarizes the month's activity of three checking accounts. Write a program that displays the account number and the end-of-month balance for each account and then displays the total amount of money in the three accounts. Assume that the data are stored in a text file.
| ||||||||||||||||||||
78. | Table 3.5 contains a list of colleges with their student enrollments and faculty sizes. Write a program to display the names of the colleges and their student/faculty ratios, and the ratio for the total collection of students and faculty. Assume that the data for the colleges are stored in a text file.
Source: The World Almanac, 2005. | ||||||||||||||||||||
79. | Write a program to compute semester averages. Each set of five lines in a text file should contain a student's Social Security number and the grades for three hourly exams and the final exam. (The final exam counts as two hourly exams.) The program should display each student's Social Security number and semester average, and then the class average. Use the data in Table 3.6.
| ||||||||||||||||||||
80. | Table 3.7 gives the year 2003 populations of three New England states. Write a program that calculates the average population and then displays the name of each state and the difference between its population and the average population. The states and their populations should be stored in a text file.
| ||||||||||||||||||||
81. | Design a form with two text boxes labeled "Name" and "Phone number". Then write an event procedure that shows a message dialog box stating "Be sure to include the area code!" when the second text box receives the focus. | ||||||||||||||||||||
82. | Write a program to calculate the amount of a waiter's tip given the amount of the bill and the percentage tip obtained via input dialog boxes. The output should be a complete sentence that reiterates the inputs and gives the resulting tip, as shown in Figure 3.28. Figure 3.28. Sample output for Exercise 82.
| ||||||||||||||||||||
83. | When P dollars are deposited in a savings account at interest rate r compounded annually, the balance after n years is P(1 + r)n. Write a program to request the principal P and the interest rate r as input, and compute the balance after 10 years, as shown in Figure 3.29 (on the next page). Figure 3.29. Sample output for Exercise 83.
|
In Exercises 84 and 85, write lines of code corresponding to the given flowchart. Assume that the data needed are contained in a file.
84. |
|
85. |
|
1. | The first statement is correct, since FormatNumber evaluates to a string. Although the second statement is not incorrect, the use of CStr is redundant. |
2. | The outcomes are identical. In this text, we primarily use the second style. |