<<

Using Data in Programs

HUS FAR IN THE VISUAL BASIC PROJECTS, we have used objects, Tmodified the properties and exercised some methods. We have used events to provide action in the projects. However, we have not used data except for text strings, and have not made any mathematical calcu- lations. That is about to change. We are now going to enter numeric data in the project, and perform some calculations. This will give us much more capability to do something useful than we have done so far.

Variables and Constants

Broadly speaking, data can be divided into two basic categories: (1) data that is changeable (or will likely change), and (2) data that will not change. In computer-eze, data that either can change or will likely change is called a variable, while data that does not change is called a constant. Most of the data you will deal with will be variables, but constants are also around us. Visual Basic treats them the same in some respects but has important differences.

65 Constants are values that have been given a specific definition, and nothing you can do will change it. For example, there are 7 days in a week, 24 hours in a day, 60 seconds in a minute, 12 months in a year, 12 inches in a foot, 5,280 feet in a mile, and so forth. Nobody can change them, and they are “constant” in their definition. A variable is data that will or could change. Examples are the number of work hours in a work week, rate of pay, scores on exams, price of a movie ticket, number of people attending an event, and so forth.

Variable and Constant Names

To make our lives easier, we use words to represent both variables and constants to describe the values they represent. If we say “day” we all know it is the same thing as 24 hours, or 1440 minutes. Or, a “mile” is the same thing as 5,280 feet or 1760 yards. Both day and mile are names for constants, and we all learned long ago what the actual values are. On the other hand, if I say “pay-rate” we don’t know what value that represents unless we define it. After it has been defined (or described), we can then use pay-rate the same way we use day or mile to describe a numeric We must amount. In computer-eze, we use pay-rate, day, or mile as a placeholder use an for a numeric value. We call that placeholder a variable or constant name. appropriate container Likewise, in math and Algebra we learned that you can use about to hold any letter to represent any value as long as it is defined someplace. For different example, we can say that “A = 15” and then we can use the letter “A” to types of represent the value 15. In this case, “A” is a variable name for the value data. 15. Visual Basic uses variable names in the same way as Algebra, or as English does for common, fixed values.

Visual Basic uses variable names to represent memory locations inside the computer. Those memory locations are containers that hold data. We are normally not concerned where the exact location is in memory, but we need to know what the location is called. We refer to these memory locations as Identifiers.

To help you conceptualize a memory identifier, think of an identifer as a container. We are used to using various types of containers to contain different items. For example, we have cardboard boxes, paper bags, metal or plastic buckets, glass bottles, fiber baskets, air-tight tanks, etc., and they hold different items. They are all containers. You would not think of put- ting a liquid in a basket or paper bag, but could put solid items in a basket. We know a liquid needs a bottle, and sand needs a bucket. We must like- wise use an appropriate container to hold different types of data.

66 Data Types

Data includes both numeric data and alphabetic data. However, we all learned long ago that these two types of data are not the same. We can add and subtract with numbers, but not with alphabetic characters. Num- bers are not all the same either. Some numbers have points and others do not. Numbers with decimal points are called , and whole numbers (numbers without decimals) are called Integers. Alphabetic characters are called Strings. To be successful in programming, you need to understand that the data types are different, and you need to know the type of data you are using. Visual Basic recognizes 12 different types of data, but normally only four are significantly different and important at this level. The four data types you need to understand for this class are Integer, Decimal, String, and Boolean. They are described below.

Table 4.1 Common Description Use Data Types in Integer Whole numbers Counting and computing Visual Basic Decimal Numbers with decimals Computations String Any Text characters, punctua- tion, and numbers not used in computations Boolean On or off state True or False values

Even though all data is contained electronically in the computer, its identifiers are different sizes, and we need to assign the right type of identifier to the appropriate data. The different data types need different amounts of memory space to be stored properly. For example, an Integer requires 4 of storage while a Decimal number requires 16 bytes of storage. A Boolean value only needs 2 bytes of storage while String data needs a varying amount of storage space. The other data types recognized by VB include the following:

Table 4.2 Other Data Type Use Data Types in Single Single-precision numbers with 6 digits of accuracy Visual Basic Double Double-precision numbers with 14 digits of accuracy Long Very large whole numbers Short Small whole numbers Date Date values through Dec 31, 9999 Char Single Unicode characters (including non-English language characters) Binary data Object The default data type; could be used for any data

67 Each of the above data types has certain restrictions. For example, the Short data type is restricted to Integer values ranging from -32,768 to +32,767 while the Integer data type allows values to plus or minus 2.1 billion. If your Integer value will be larger than 2.1 billion, you must use the Long data type. Likewise, most decimal applications fit within the Decimal data type. However, if you need very high levels of decimal precision, then use Single or Double. If you are planning a trip to Mars, then you probably should use Double to get the highest degree of precision. If you are counting grains of sand on the beach, you probably should use Long. Byte is used to transfer binary data between various programming languages, such as transferring from Visual Basic to C++ or C#. The Object data type should only be used if the type of data is unknown, or is likely to change in data type frequently. It is the least efficient data type available, and should only be used when nothing else works. Technically, the Single data type is more efficient than the Decimal data type. However, Single, Double, and Long are usually used in scientific applications while business-use usually uses Integer and Decimal data types. Refer to Appendix A for details on all data types.

Declaring Variable Names

The most important thing about a variable name is that it must be representative of the data it contains. You cannot assume that you will remember what the value of the data actually is, so the name must identify it for you. You might not even know what the value is. For those reasons, the variable name “X” is the worst name possible -- it doesn’t describe anything. Visual Basic has some “Naming Rules” to keep in mind when naming variables or constants:  Names can contain alphabetic characters, numbers, and the underscore, but no other punctuation.  Names must begin with an alphabetic character.  Names cannot contain a space or a period.  Names cannot be a reserved word, but reserved words can be contained inside a name, such as ClassFriend. (A reserved word is a word that has a special meaning in Visual Basic, such as Sub, Private, Dim, Close, etc. Refer to Appendix B for a partial list of reserved words.)  Names are not case sensitive. Names such as Quantity, quantity, and QUANTITY are all considered the same variable name.  There is no real limit to the number of characters used.

68 Most experienced programmers like to use prefixes to identify the data type in variable and constant names. Variable or constant name pre- fixes are similiar to prefixes used to identify controls. A suggested listing of prefixes for variables and constants are as follows:

Table 4.3 Variable and Data Type Prefix Example Constant Name Integer int intCount Prefixes Decimal dec decNetAmount Boolean bln blnMale String str strAcctNum

As with control prefixes, variable name prefixes should be lower case with the main part of the name starting with a capital letter. Using prefixes to designate the data types is highly encouraged to avoid “Type- Mismatch” errors, such as trying to compute a zip code. The important thing is the spelling and capitalization used because it will appear that way throughout the program. It is also important to assign the right type of prefix as it is named. Consider the following when assigning a data type:  If a value could be used in calculations and does not have a decimal, use the Integer data type.  If a value could be used in calculations and does have a decimal, use the Decimal data type.  If a value will not be used in calculations, use the String data type. This would include numbers such as Social Security numbers, phone numbers, account numbers, Zip Codes, addresses, etc.  If the variable contains alphabetic characters, use the String data type.

The Declaration Statement

Variable names are created using a Declaration statement. The Declaration statement establishes the name and assigns the data type to that name. It also assigns the scope of the name (which will be discussed in the next section). The Declaration statement is often called a “Dim” state- ment because it starts with the keyword Dim. (Dim is a shortened version of “dimension.”) The Variable name follows the word Dim, then the key word “As”, then the data type. Figure 4.1 shows some examples.

69 Figure 4.1 In Figure The Dim 4.1, the first two Statement statements de- declaring Decimal, clared decPayRate Integer, and and decMaxPoints String variables as Decimal variables, the next two (intCount and intQuantity) as Integer variables, and the last two (strCity and strZipCode) as String variables.

Note: it is the keywords As Decimal, As Integer, or As String that assign the data type, not the prefix. If you list it as “Dim intValue as Deci- mal”, then it will be a decimal data type regardless of the prefix. Normally a variable is created and the opening value is zero. How- ever, if you wish to initialize it with a value other than zero, you can do so, as shown with the variable decMaxPoints in Figure 4.1. Since decMaxPoints is a variable, it can be changed later while the program is running.

Declaring Constants

Declaring a constant is nearly the same as declaring a variable. However, constants use the keyword “Const” instead of “Dim,” and con- stants must be given a value at the time they are declared. Once they are declared and initialized to a value, they cannot be changed. Constants must also be given a data type when created. The data type and the value given must also match. Figure 4.2 shows a constant being declared and initial- ized. Figure 4.2 shows four constants being declared and initialized. A couple of things are different than with variables. Variables may be initial-

Figure 4.2 Declaring Constants

70 ized when declared, but constants must be given a value when declared. Also notice that the bottom two constants have a different capitalization than the first two in that most of the constant name is capitalized (except for the prefix). This is an optional arrangement, but is a very handy way of showing the difference between a variable and a constant to the program- mer on the code sheet. Also notice that in Figure 4.2 the value is followed by a type declaration character. This will ensure that the data and the data type match. The type declaration characters are D for Decimal, I for Integer, R for Double, L for Long, S for Short, and F for Single. No space is allowed between the value and the type declaration character. If the type declaration character is missing, then a whole number is assumed to be an Integer and a decimal number is assumed to be a Decimal. It is an extra step to help the programmer not make a type-mismatch error later.

Scope of Variables and Constants

Variables are “born” when they are created, but they don’t live forever. Like humans, variables don’t live forever; they will eventually “expire.” The lifetime between when a variable is created and when it expires is called its scope. But, there is more to it than that. Scope also relates to its area of influence. A variable only exists within its lifetime and area of influence. When variables expire, the memory locations are re- leased, the contents are erased, and the variable name is no longer valid. Generally, there are three levels of scope: global, modular, and local. A local-level variable is only useable within the event procedure where it was created. When the flow of control enters the event procedure, it becomes alive, and when the flow of control leaves the procedure, it no longer exists. A modular-level variable becomes alive when the module A variable (or form) becomes active and when the form becomes inactive, the vari- only exists able no longer exists. A global variable is alive and active whenever the within its project is active. lifetime (The code sheet for a form is called the “module sheet,” so gener- and area of ally a form and module are the same. At advanced levels, there is a differ- influence. ence, but it is not important now. The term “module” is preferred.) If a project only has one form, then global- and modular-level scope would be nearly the same. If the project is large and has more than one form, then modular-level and global-level become different. Likewise, if a module only has one event procedure, then local-level and modular- level would be the same. However, it is very unlikely that a module will only have one event procedure, so the difference between modular-level and local-level scope is most likely to be relevant.

71 Declaring Local Variables

Scope level of a variable is determined by where the variable is declared. Local-level scope is created using the Dim statement, and it normally should be at the top of the event procedure above all other code lines. The variable will be alive and useful only within the event procedure in which it was declared, and will normally expire when the End Sub statement is reached at the end of the procedure. Each time you re-enter an event procedure, the variable is re-created. Always use local-level scope if possible.

Declaring Module-Level Variables

A module-level variable is created using the keyword Private, and the remainder of the declaration line is the same as the Dim statement used to create a local variable. The declaration is placed above the first event procedure on the module sheet in the area called the “Declarations section” of the module sheet. Normally the module-level declarations are placed below the line reading “Public Class form-name” and above the first event procedure. Module-level variables are useful in all event procedures on the form or module. Figure 4.3 shows both local and modular-level variables and their declaration statements. The variable intCounter is declared as a modular-

Figure 4.3 Declaring Module-level and Local-level Variables

72 level Integer variable, and is located in the Declarations section of the module sheet. It will be available in all event procedures on the module sheet. The variable decScore is declared as a local variable and is only active inside the btnComputeScore_Click event procedure. Likewise, the variable decFinalGrade is a local variable and is only active inside the btnComputeGrade_Click event procedure. The variable decScore is not known to the btnComputeGrade_Click procedure, and the decFinalGrade variable is not known to the btnComputeScore_Click event procedure. To further explain how scope works, let’s use a legal/political example. Assume you have three independent cities (Fairfield, Vallejo, and Vacaville), all located inside one county (Solano) which is also located inside one state (California). If the Fairfield City Council passes a law, it has no effect inside the cities of Vallejo or Vacaville, but does have an effect inside the City of Fairfield. That is an example of local scope. Also assume the County of Solano passes a law. It is in effect within the entire county, including the cities in the county, but has no effect in other coun- ties. That is an example of module-level scope. If the State of California passes a law, it is in effect in each county, and each county within the state, but not other states. That would be an example of global scope. The advantage of using local scope is that an unexpected result will not have an impact in an event procedure because it was declared some- where else, and has wider impact than is needed or expected. You should always use the lowest-possible scope for your variables.

Global Scope

Even though global scope (now called “Namespace scope” by Microsoft) will probably not be used in this class, it needs to be covered briefly here. Global scope is intended for large applications that have several forms and/or modules and those variables will be used throughout the entire application. Global variables are declared using the keyword Public instead of Private or Dim. Other than the Public keyword, the process is exactly the same as declaring a module-level variable. The declaration statement should occur on the first module sheet to be encountered or used in the project. Once declared, a global variable can be used or changed anywhere in the project. Instead of using globally-declared variables, good programming technique involves passing the value (or reference to the variable) directly to the specific event procedure where it is needed. The process of passing variables from one procedure to another is not difficult, but is beyond the level of knowledge needed in this class.

73 Scope of Constants

Constants are declared in the Declarations section of the module sheet along with module-level variables. The reason for placing constant declarations with module-level variables is to make them easier to find if needed. A medium-sized application could have hundreds of event proce- dures, but only a few modules. Finding a constant declaration located inside an event procedure would be like searching for a needle in a hay- stack. Also, it is rare when a constant is given local scope. An example of a global constant is shown in Figure 4.4. Note the inclusion of the keyword “Public.” Omitting this keyword would give it modular-level scope. Compare this example with those in Figure 4.4 which show module-level constants.

Figure 4.4 Declaring Global Constants

Performing Arithmetic Calculations

Arithmetic operations in Visual Basic are fairly straightforward. Addition, subtraction, multiplication, and division are very similar to the operations of simple arithmetic. The operators used to perform those calculations include the +, -, *, and / symbols, respectfully. For example: Addition: 10 + 3 results in 13 Subtraction: 10 – 3 results in 7 Multiplication: 10 * 3 results in 30, and Division: 10 / 3 results in 3.333.

In addition, Visual Basic allows Integer division, Modulus division, and (raising a number to its exponent power).

Integer division is dividing one Integer by another and the resulting answer is likewise an Integer. The remainder, if any, is disre- garded. The symbol used for Integer division is the backslash (\). For example, if the Integer 10 is divided by the Integer 3, the Integer division answer is the Integer 3. The remainder of 0.33 is disregarded. That would be shown as 10 \ 3 with the answer being 3.

74 Modulus division returns only the remainder of the division operation. The word Mod is used for the operator. For example, using the example above, the Integer 10 modulus Integer 3 gives the answer of .333. The Integer portion of the answer is disregarded. That would be shown as 10 Mod 3. Integer and Modulus division is useful for stripping off or truncat- ing a portion of the answer.

Exponentiation is raising a number to the power specified, and uses the caret (^) symbol. The number before the symbol is the base number and the number after the symbol is the exponent (or power). For example, the base number of 10 raised to the power of 2 would be 10 ^ 2 and the result would be 100.

The examples above involving only one arithmetic operator are referred to as simple calculations because it only has one operator, and only one possible result. However, the process can get more involved when two arithmetic operators are involved, such as 10 + 3 * 5. Which is per- formed first – the addition or the multiplication? If the addition is per- formed first, the result is 65. However, if the multiplication is performed first then the result is 25. They can’t both be considered correct. Calculations involving more than one arithmetic operator are called “complex” calculations – regardless how simple or difficult the actual arithmetic is. To avoid confusion in complex calculations, an Order of Arithmetic Operations has been established.

Order of Arithmetic Operations for multiple operators: (Highest order to lowest order) 1. Any operation inside parentheses 2. Exponentiation 3. Multiplication and division 4. Integer division 5. Modulus division 6. Addition and subtraction

Multiple operations on the same level are performed left to right. If multiple sets of parentheses are involved, work from the inside out. If you want to override the above order, insert parentheses. In the above example of 10 + 3 * 5, the correct answer would be 25 since multiplication would be performed before addition. If you want the addition to occur first, then place that portion of the formula inside paren- theses, such as (10 + 3)* 5 which results in 65.

75 Data Conversion

Performing calculations in Visual Basic is fairly easy to do. The wrinkle in the process, however, is getting the data ready for the calcula- tions.

Initializing Data

When a numeric variable has been created using the Dim or Private statements, its initial value is zero. String variables are equal to empty when created. To be useful, most numeric variables need to have a value other than zero. This is called “initializing.” As explained previously, variables can be initialized to a value when they are declared. If this isn’t done, then they can be initialized in a separate line, such as Variablename = value Normally, initialization statements would be grouped to follow the declaration statements.

Converting Data

One of the new concepts of Visual Basic .Net is the concept of converting data from one data type to another. Visual Basic is a strongly- typed , which in laymen’s terms is that the data type of a variable is very important – more important than most “beginners to programming” realize.

The Parse Method

As previously mentioned, data found in the Text Property of a TextBox is Text (or String). You must convert string data into a numeric data type before it can be used in calculations. This processes called Parsing or Casting. Parsing is a method of a data type. It is simple to do, but must be done. Assume you have a TextBox on your form called txtQuantity, and you want to convert its Text Property into an Integer variable called intQuantity. Use the Integer.Parse method and place the text string inside parentheses, as shown in Figure 4.5. Each numeric data type has a Parse method. If you are converting from String to a Decimal data type, use the Decimal.Parse(text-string) method. Likewise, you can use the Short.Parse, Long.Parse, and Double.Parse methods in a similar way. The string you wish to convert can be a property of a control (such as a TextBox), a String variable, or a String 76 Figure 4.5 Initializing a Variable Using the Parse Method

constant. The String value being parsed is called the argument of the Parse method.

Val function. Older versions of Visual Basic used the Val function to convert numeric strings to numeric data. If the string data contained a decimal point, it would assume the numeric value was a Double data type, but if it did not have a decimal it would assume it was an Integer data type. The problem with using the Val function was with a zero value – it was unreliable, and that is never acceptable in good programming practice. Since the Parse method does a better job, the Val function should be avoided.

Converting Numeric data to Strings

After you have completed your calculations using numeric vari- ables, you likely will need to output the results to a label. Again, the Text Numeric Property of a label is also Text (or String). Numeric data must be converted data must into a String data type to display it in a label. This conversion is accom- be converted plished using the ToString() method. (Note: the parentheses indicate that it into a string is a method.) Nothing needs to be included inside the parentheses. The data type to general form of the ToString() method is display it in lblLabel.Text = intVariablename.ToString() a label. lblResult.Text = decVariablename.ToString()

Figure 4.6 below shows the variable intResult being converted to a string data type that can be displayed in the Text Property of a label named lblResult.

77 Figure 4.6 The ToString method of converting a numeric variable to a string variable

Declaring variables

Parsing Text data to Numeric data

Converting Numeric data to Text data

Formatting Output

To make the output easier to read, it is customary to format numeric values to fit the circumstance. That means that numbers larger than “999” are usually displayed with comma separators. For example, the value 12345 would normally be displayed as “12,345.” If the output is meant to be a currency value, the dollar sign is added. Normally currency values are displayed to either zero or two decimal places. Also, negative currency values are enclosed in parentheses. Formatting should only occur after the calculation is complete and as part of the output process. Formatting is accomplished using the ToString method by placing a format string inside the parenthesis following the ToString method. For example, ToString(“c”) would format the output to currency and append the dollar sign, insert comma separators as appropri- ate, and display two decimal places. Other numeric formatting patterns are also available. To format for percent, use a “p” for the format code. Percent format will automatically multiply the result by 100 and append a space followed by the percent sign. Negative numbers will show a leading minus sign. The Number format is fairly generic. It will insert comma separators and show negative values with a leading minus sign. Number format uses the “n” format string. Scientific notation uses the “e” (for exponent) format string, and will display the value in exponential form. The format string can be further customized by placing a value after the designated letter to indicate the number of decimal places to show. For

78 example, the string c0 (letter “c” and the zero) will show the currency format rounded to zero decimal places. Likewise, p1 will show percent to one decimal, and n3 will show the number format to three decimal places. For currency, you do not need to show “c2” because two decimal places is the default for currency. Lost decimal places are rounded, not truncated, when formatted. Table 4.4 shows the format string and examples in tabular form.

Table 4.4 Format Unformatted Formatted Format Strings Description String Number Number Used to Format Output Data Currency (default) c 1234.567 $1,234.57 Currency no decimals c0 1234.567 $1,235 Percent (default) p 0.12345 12.35 % Percent 1 decimal p1 0.12345 12.4 % Number (default) n 1234.567 1,234.57 Number no decimal n0 1234.567 1,235 Number 3 decimals n3 1234.5 1,234.500 Scientific (default) e 1234.567 1.234567e-003

Since output formatting is so easy to accomplish, there really is no excuse for not formatting numbers properly.

Accumulating Totals and Counters

Accumulators: A frequent programming technique is to keep a running total of a variable. The variable that keeps the running total is usually called an accumulator. An accumulator can be used to keep track of An total sales, total earnings to date, and a variety of other applications. The accumulator concept of accumulating a running total consists of adding the current value increases a to the previous running total. To perform this task, two variables are needed: running total a current value and a running total value, such as decSales and by a varying decTotalSales. For this example, the variable decSales is the amount of one amount, but a counter transaction, and the variable decTotalSales is the accumulator. The actual increases a computation line would be running total decTotalSales = decTotalSales + decSales by a fixed This line would take the previous total (decTotalSales) and add the amount. latest transaction (decSales), and replace this sum in the variable on the left side of the equal sign.

79 Counters: Similar in concept to an Accumulator variable is a Counter variable. An accumulator increases a running total by a varying amount each time, but a counter increases a running total by a fixed amount each time. For example, a Counter variable would be intCounter = intCounter + 1I Each time the line is encountered, it would increment the counter variable by one. Most counters increment by one, but any other value could be used, such as by counting by 2 or 3, etc. It could also decrement by using a minus sign instead of a plus sign. Using an accumulator and a counter would be an easy way to determine the average by dividing the accumulator variable by the counter variable. For example, the average sales could be computed by dividing the total value of sales (the accumulator) by the number of sales (the counter). Accumulators and Counters are also frequently used in loops and repetitive operations which will be covered in a later chapter. Depending upon how the programming algorithm is up, it may be necessary to give either the accumulator or counter variables modular- level scope so they won’t lose their values when the program flow exits the event procedure. However, if everything is contained within the local procedure, local scope should be used.

Informational Message Boxes

Sometimes you need a convenient way to give a message to the user without having to provide the information in a label on the form. This can be accomplished using a Message Box, as shown in figure 4.7. Message Boxes can be used to give the result of a computation, to inform a user that the wrong type of data was entered, or to signal the completion of a routine or task. They are shown in the middle of the screen, and the user must respond to the message by clicking a button on the message box before con- Figure 4.7 tinuing. Sample The typical message Informational box, as shown in Figure 4.8, Message Box has four parts: the title (or caption), the text (or prompt), the OK button, and the icon. The Text is the most important part because it provides the information the user needs. The Caption is the title shown at the top of the Message Box. The

80 Button allows the user to respond, and by default shows “OK” as its text. The icon is optional, but can be used as a graphic image for the user. These parts of the Message Box are identified in Figure 4.8

Figure 4.8 Four parts of a Informational Caption Message Box

Icon

Text Message

Button

Most of the parts have several options so the message box can be customized to fit a wide variety of applications. For example, both the Text and Caption are text strings the programmer provides. Six possible button combinations are allowed, but if the purpose of the Message Box is to merely inform the user, then only the single OK button should be used. Decision Message Boxes (to be covered in the next chapter) require the user to select between various buttons, and the button selected will deter- mine future actions of the program. Four icons can be used depending on the purpose of the message, but for Informational Message Boxes, only the three icons shown in Figure 4.9 should be used.

Figure 4.9 Message Box Icons Programming code Icons MessageBoxIcon.Information

MessageBoxIcon.Exclamation

MessageBoxIcon.Stop

The programming code to show a Message Box uses the MessageBox.Show method. The general format for this statement is

MessageBox.Show(“Text”,”Caption”,button,icon) 81 Both the Text and Caption arguments are text strings, and must be enclosed inside double quotation marks. The code for the OK button is MessageBoxButtons.OK and the code to show the information icon is MessageBoxIcon.Information. (The code to show the other buttons and icons will be covered in the next chapter.) The arguments are separated by a comma. If the caption text string is omitted, the title bar will be blank. If the button code is omitted, the OK button will show, and if the icon code is omitted, no icon will show on the Message Box. However, if the Text string is omitted, you will receive an error message. Variables and constants are permitted in the Text string in similar fashion as used to display text strings and variables in label controls. Concatenation and Line Continuation characters can also be used. The complete code is shown below, and the resulting Message box image is shown in Figure 4.10.

MessageBox.Show(“The transaction is complete.”, _ “Cactus Mail Order Sales”, _ MessageBoxButtons.OK, _ MessageBoxIcon.Information)

Figure 4.10 Completed Message Box

More will be said about message boxes in the next chapter.

Hands-On Programming Example

As in the previous chapter, this hands-on project is provided to help you understand the concepts in this chapter to a higher level. You should attempt to complete the project on your own without looking at the solu- tion. And, then after your attempt, compare your project with the project that follows.

82 Step 1 – Plan the Project

The Project

Create a project that will compute the value of a base number raised to an exponential value. The project should allow the user to enter a base number and an exponent (both whole numbers), and have the correct value displayed on the form. The user will have two text boxes for entering the values, a label for displaying the result, and three buttons: one to perform the calculation, one to clear the contents of the text boxes, and one to end the project.

Planning the Action

The user will supply a base number and an exponent value, then click the Calculate button to show the result. A message box will notify the user that the calculation is complete. Clicking the Clear button will clear the contents of both text boxes, the label, and reset the focus to a text box. Pseudocode Clicking the End button will terminate the project.

The pseudocode for the Compute button will be: 1. Declare the needed variables. 2. Read the values from the text boxes into the variables. 3. Perform the calculation using the variables. 4. Display the formatted results on the form. 5. Display a message box to the user.

The pseudocode for the Clear button will be: 1. Clear both input text boxes. 2. Clear the output label. 3. Reset the focus to a text box.

The pseudocode for the Exit button will be: 1. Terminate the program.

Step 2 – Create the User Interface

Populating the Form

Place the following objects on the form, and arrange them to match Figure 4.11: 2 Text Boxes 5 Labels 3 Buttons

83 Setting the Properties

Set the following properties for each object:

Object Property Setting Form Text Exponent Calculator AcceptButton btnCalculate CancelButton btnClear StartPosition CenterScreen

TextBox1 Name txtBase Text (blank)

TextBox2 Name txtExponent Text (blank)

Label1 Name (unnamed) Text Raising to the power FontStyle Bold Italics

Label2 Name (unnamed) Text Exponent

Label3 Name (unnamed) Text Base

Label4 Name (unnamed) Text = [the equal sign]

Label5 Name lblResult Text (blank) AutoSize True BorderStyle Fixed3D FontSize 14 pt.

Button1 Name btnCalculate Text &Calculate

Button2 Name btnClear Text Clea&r

Button3 Name btnExit Text &Exit

84 Figure 4.11 Completed Exponent Calculator Project User Interface

Step 3 – Write the Code

You will need to write code for each of the following Event proce- dures. Start by wring the comment lines which come from the pseudocode:

Event Procedure Comment Lines (from the pseudocode) btnCalculate_Click ‘Perform exponent calculation ‘Declare local variables ‘Initialize variables using parse method ‘Perform calculation using variables ‘Display formatted results in label ‘Display message box

btnClear_Click ‘Clear both text boxes and label ‘Reset the focus to Base text box

btnExit_Click ‘Terminates the program

Complete the Event Procedure Code

Project ‘Programmer: Don Hoggan Comment ‘Title: Exponent Calculator Lines ‘Class: CIS 001 ‘Description: This project will compute the result ‘ of raising a base number by the ‘ exponent value 85 Public Class Form1

btnExit_Click Private Sub btnExit_Click(ByVal sender As _ event procedure System.Object, ByVal e As System.EventArgs) Handles btnExit.Click ‘Terminates the program Me.Close() End Sub

btnCalculate_ Private Sub btnCalculate_Click(ByVal sender As Click System.Object, ByVal e As System.EventArgs) Handles event procedure btnCalculate.Click ‘Performs Exponent calculation

‘Declare local variables Dim intBase As Integer Dim intExponent As Integer Dim intResult As Integer

‘Initialize variables intBase = Integer.Parse(txtBase.Text) intExponent = Integer.Parse(txtExponent.Text)

‘Perform calculation intResult = intBase ^ intExponent

‘display formatted results in label lblResult.Text = intResult.ToString(“n0”)

‘Display message box MessageBox.Show(“The computation is complete.”, _ “Exponent Calculator”, MessageBoxButtons.OK, _ MessageBoxIcon.Information) End Sub

btnClear_Click Private Sub btnClear_Click(ByVal sender As System.Object, event procedure ByVal e As System.EventArgs) Handles btnClear.Click ‘Resets controls to start-up stats txtBase.Clear() txtExponent.Clear() lblResult.Text = “” txtBase.Focus() End Sub

End Class

86 Step 4 – Test and Debug the Program

1. When running the program, the form should center on the screen with the cursor blinking in the base text box. 2. Enter a 2 in the base text box and a 10 in the exponent text box, and then click the Calculate button. A message box should appear informing the user that the calculation is complete. After pressing the OK button on the message box, the label on the form should show 1,024. 3. Click the Clear button and the text boxes and label should all be cleared, and the blinking cursor should show in the Base text box. 4. Test the Tab sequence. 5. Test the Keyboard Access keys. 6. Click the End button and the project should terminate.

Chapter Summary

1. Variables and constants are temporary memory locations that have a name, data type, and a scope. The value contained in a variable can be changed while the program is running, but a constant cannot be changed. 2. Data types are like storage containers that hold values (numbers or strings). Like containers, they are designed to hold different types of data. 3. The most common data types are Integer, Decimal, String and Boolean. Lesser used data types include Single, Double, Long, Short, Date, Char, and Byte. The Object data type is the default, and should only be used when none of the others will work. 4. Variable and constant names must conform to the Visual Basic naming rules, and should contain specific lowercase prefixes to identify the data type and be meaningful to its intended contents to aid in identifying the data. 5. Variables are named using the Dim, Private, or Public keywords, and scope is assigned based on the location where the declaration statement appears. 6. The scope of a variable can be local, modular-level, or global. Local variables are active only within the event procedure where they are declared. Module-level variables are active in any event procedure on the module sheet, and global variables are active anywhere within the project. The lowest level possible should be used when assigning scope.

87 7. Calculations can be performed using addition, subtraction, multiplication, division, Integer division, Modulus division, and exponentiation. When a formula has multiple arithmetic operators, the order of arithmetic operations determines the order used to solve formulas. Parentheses can be used to alter the default order. 8. Numbers normally need to be converted into a numeric data type using a conversion method before it can be used to perform calculations. The preferred method of conversion is using the Parse method. 9. Numeric values also need to be converted into the String data type before being placed in the Text property of a control. The ToString method is used for conversions to the String data type. 10. String data can be formatted by placing dollar signs, comma separators, percent signs, etc. while it is being converted to a String data type. 11. Accumulators are used to maintain a running total by adding a varying amount to the running total. Counters increase a running total by a fixed amount, usually 1, each occurrence. 12. Message Boxes can be used to provide temporary and immediate information to the user without displaying the information in a control on the form. Message boxes have the informational message, a title or caption, and a button for the user to respond. They may also display an icon.

Key Terms

accumulator identifier Private keyword Boolean initialize Prompt Caption Integer Public keyword casting Integer division reserved words Char Key words scope Const Message box String constant module ToString counter Modulus type declaration character data type Namespace variable Declaration statement Naming rules Dim Parse

Review Questions

1. Explain the difference between a variable and a constant. 2. What is an “identifier”? 3. What is a “data type”? Name the four most common data types. Give the main characteristics or use of each. 4. Name the eight other data types. When should they be used? 88 5. How are variables created? What keywords are necessary? 6. How is a data type assigned to a variable? 7. What are the required naming rules for declaring variables? 8. Indicate whether each of the following variable names conform to the recommended naming rules. If the name is not correct, give the reason and provide a correct alternative: a. AverageAge d. intQuantity g. str$Address b. conCompanyName e. strPayRate h. intPhoneNumber c. Private f. Minimum Wage i. 77points 9. When a numeric variable is created, what is its original value? What is a string variable initialized to? 10. How is a constant declared? What keywords are used? 11. What is meant by “scope”? How is scope level determined? 12. What is the difference between local and module-level scope? Module- level and global scope? 13. What level of scope should be used in normal situations? When should modular-level scope be used? When can global scope be justified? 14. Write a declaration statement to declare the following variables: a. the number of hours an employee works (allow decimal point) b. an employee’s name c. the account number for a charge account d. a variable for the number of employees in a department 15. What is the difference between complex and simple arithmetic? 16. What is the “Order of Arithmetic Operations”? Give the levels from highest to lowest? How do parentheses effect the order? 17. Calculate the correct answer to the following problems: a. 12 / 4 + 1 + 12 * 2 - 5 c. 5 + 9 / 3 - 16 / 2 + 3 * 7 b. ( 7 + 5 ) / 3 + 9 * 3 - 5 d. 16 / 2 ^ 2 + 9 / 3 18. What is the difference between regular division and Interger division? Interger and Modulus division? 19. Which arithmetic symbols are used for regular, Integer, and modular division? 20. What is the result of each of the following calculations? a. 10 / 3? c. 10 mod 3? b. 10 \ 3? d. 10 ^ 3? 21. Why does the numeric contents of a text box need to be converted to a numeric data type before it can be used in a calculation? What method is used to perform the conversion? 22. What method is used to convert a numeric variable to a string variaiable? 23. How is formatting symbols (dollar signs, percent signs, etc.) inserted in data to be displayed in a label? 24. What is the difference between an accumulator and a counter? 25. What is the purpose of a message box? 26. What are the four parts of a typical message box? 89 Vocabulary Crossword

Solve the crossword puzzle using the clues below. All terms are in this chapter or previous chapters.

ACROSS 3. A data type that only has two possible values. 6. A named placeholder for a value that can be changed. 8. A method to cast data from one data type to another data type. 10. A value that can not change while the program is running. 11. A data type for text, numbers, and other characters. 12. The process of raising a number to its power. DOWN 1. An arithmetic operation resulting in a fractional remainder. 2. A numeric data type for whole numbers. 4. The area of influence for a variable or constant. 5. Giving a variable or constant its original value. 7. A variable used to keep a running total. 9. A method used to convert a numeric value to a text data type.

90 Programming Practice

Exercise 4-1. Writing code Write a single line of Visual Basic code to accomplish each of the following: a. Declare the variable blnGender as a local boolean variable. b. Declare the variable intQuantity as a modular-level integer variable. c. Assign the string Jenny to the variable strFirstName. d. Assign the value 1234 to the label lblPrice and format it to show a dollar sign with no decimal places. e. Set the focus to the txtQuantity text box. f. Increment the variable intCount by 1. g. Increment the variable decYTD by decGrossPay.

Exercise 4-2. Miles per Gallon Calculator Create a project that will calculate a car’s gas mileage. The form will have text boxes that the user will fill in the number of miles driven, and the number of gallons of gas used. The miles per gallon will be dis- played in a label. Format the result to one decimal point. Include buttons to clear the entries and result, and a button to end the project. Use the decimal data type for all entries. Test your project with the following inputs: 39.7 gallons used and 1022.6 miles driven. The miles per gallon should be 25.8.

Exercise 4-3. Baseball Slugging Percentage Calculator In baseball, the Slugging Percentage statistic accounts for the number of bases a player gets when batting. Home runs count as 4 bases, Triples count as 3 bases, Doubles count as 2 bases, and Singles count as 1 base. No bases are given if the player makes an out. Other outcomes at bat are not considered, such as bases on balls, hit batters, sacrifices, fielder’s choices, etc. are not counted. Create a project that will compute the Slugging percentage. Provide Text Boxes for Home Runs, Triples, Doubles, Singles, and Total At-Bats. Display the slugging percentage in a label formatted to three decimal places. Declare variables as needed. Use local scope. Use the following statistics to test your project: At Bats = 90, Singles = 15, Doubles = 5, Triples = 2, and Home Runs = 4. The Slugging percentage should be .522.

Exercise 4-4. Basketball Scorekeeper Assume you are the scorekeeper for your son’s or daughter’s after school basketball team. Create a project that will compute an individual’s season statistics for shooting and rebounds. The inputs will be the number of Free Throws, Field Goals, 3-Point Field Goals, and Rebounds. The output will give the Total Points, Points per game, and Rebounds per 91 game. Remember that Free Throws earn 1 point each, Field Goals earn 2 points each, and 3-Point Field Goals earn 3 points each. Declare variables as needed. Format the Points per game and Rebounds per game to one decimal point. Use the following to test your results: 16 Free Throws, 32 Field Goals, 5 Three-point Goals, 50 Rebounds, and 12 games played. The Points per game should be 7.9 and the Rebounds per games should be 4.2.

Exercise 4-5. Currency Conversion. Assume you have decided to organize a tour group of your friends to tour Europe. You know you will need to convert your U.S. currency to the British Pound and European Euro as you arrive on foreign soil. Create a Visual Basic program that will compute the amount in Pounds and Euros that you will have after the conversion. Input an amount in U.S. currency in a text box, and the output will show both Pounds and Euros in separate labels. The calculation should occur when a Convert button is clicked. Also include a Clear and an End button on your form. Assume the exchange rate from U.S. to Pounds is 0.627 and from U.S. to Euros is 0.696. You may include the exchange rate inside your program, or place two additional text boxes on your form for the rates. Be sure proper data type conversions occur. Ignore exchange fees or commissions. To test your program, input $350 U.S.; you should receive 219.45 Pounds and 243.6 Euros.

92