Visual Basic 2008 Programming: Business Applications with a Design Perspective
Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9
Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Appendix A Appendix B Appendix C Home
Last change: February 13 2016 18:48:19.

 Chapter in PDF

Table of Contents

Chapter 4: Data, Operations, and Built-In Functions
Last change: February 13 2016 18:47:36.

The Calculating Vending Machine: An Example

Tosee how some of the previously mentioned string handling functions can be used to solve a programming problem, let's consider an example. In this project, a list box is used as the display of a vending machine. The customer buys an item by clicking on it. The visual interface of the project in action is given in Figure 4-5. At run time, this program behaves in the following manner:

Figure 4-5
The vending machine in action

Setting Up the Vending Machine

The list box will display the items available as the program starts. So, how do you add the items to the vending machine? You can use the list box’s Items.Add method to add the food items along with their prices. (In a real application, food items and their prices can be read from a file or database.) You would also like to align the prices in a column. This can be accomplished by inserting a tab character between the food item and its price. The key code constant for the tab character (Chr(9)) is defined in VB as vbTab. You will have six items in the vending machine. The code should be placed in the Form Load event procedure:

Private Sub frmVendingMachine_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load lstVending.Items.Add("New York Top Sirloin" & vbTab & "16.95") lstVending.Items.Add("Boston Red Lobster" & vbTab & "26.95") lstVending.Items.Add("Alaska King Salmon" & vbTab & "15.95") lstVending.Items.Add("Home Made Sandwich" & vbTab & "12.95") lstVending.Items.Add("Washington Red Apples" & vbTab & "4.95") lstVending.Items.Add("Florida Orange Juice" & vbTab & "5.95") End Sub

Notice that the length of each item varies slightly. The price of each item has a slightly different length, too. However, the use of the tab character (vbTab) helps align the prices fairly evenly.

Look It Up
Use the keyword constants to search the Index tab of the help file. You will find all kinds of predefined constants that you can use in your program. The subtopic, miscellaneous, gives constants that are used in printing and display, such as tab, linefeed, and so on.

A Side Note on Coding Mechanics

Notice the repetitive references to lstVending.Items in the previous procedure. A coding structure exists that allows you to use a shorthand reference to the same object or collection. This involves the use of the With…End With structure, which has the following syntax:

With Object Statements End With

Inside the With block, any statement that begins with a dot will be automatically qualified with the object. For example, the preceding Form Load event procedure can be rewritten as follows:

Private Sub frmVendingMachine_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load With lstVending.Items .Add("New York Top Sirloin" & vbTab & "16.95") .Add("Boston Red Lobster" & vbTab & "26.95") .Add("Alaska King Salmon" & vbTab & "15.95") .Add("Home Made Sandwich" & vbTab & "12.95") .Add("Washington Red Apples" & vbTab & "4.95") .Add("Florida orange Juice" & vbTab & "5.95") End With End Sub

All the .Add statements will be interpreted as lstVending.Items.Add because the With statement refers to lstVending.Items. This structure is not only convenient for coding, but also efficient for execution. The reference to the object is set for all statements in the block, thus avoiding the need to locate the object for each statement individually.
When you have a block of code that refers to an object several times, use the With…End With structure to reference the object. Your coding will be more efficient. The code executes faster, and the code is easier to read.

Determining the Item the Customer Has Chosen

When the user makes a selection by clicking an item in the vending machine, what does the computer know? You may recall that the item is identified by the list box’s SeletectedItem property, as well as the SelectedIndex property. This item will be referenced several times in the program. You will assign the text to a variable, which is named TheItem. You can code the following:

TheItem = lstVending.SelectedItem ‘store the clicked item in a variable

Obtaining the Item Name

How do you get the food item name from this string? Recall that the string has both the name and the price. You know that the tab character separates the item and its price. If you know the position of the tab character, you should be one step closer to solving your problem. You can use the InStr function to find this position. If you use the variable TabPos to keep track of the position, you can code the following:

‘ Find the position of vbTab in the selected item TabPos = InStr(TheItem, vbTab)

The item name starts at the beginning of the string, and ends one position before the tab character position. It can be computed as follows:

Miscrosoft.VisualBasic.Left(TheItem, TabPos - 1)

Putting Items Bought Together

The question then is what should you do with this result? Consider this list:
One, two, three, …
When you have only one item such as One, you will show only the item One. If you have more than one item, you want to insert a comma between the two items; that is, in addition to adding the item, you also add a comma and a space. If you use a variable named ItemsBot to track the items purchased, you will assign the item name to ItemsBot when this item is the first one; that is:

ItemsBot = Miscrosoft.VisualBasic.Left(TheItem, TabPos - 1) ‘For the first item

If the item is not the first one, you will add a comma (with a space) as well as the item name to the existing string. The code should be as follows:

ItemsBot = ItemsBot & “, “ & Miscrosoft.VisualBasic.Left(TheItem, TabPos - 1)

Showing Items on Separate Lines

Here is an additional thought. What if you want to show each item on a separate line? This ensures that the text to be displayed is wrapped properly. The character combination Chr(13) & Chr(10)—recognized as carriage return and line feed—will make the computer display what follows it in the next line. This constant has a predefined name vbCrLf. To make each item appear on a separate line, you can insert this named constant to the preceding code:

ItemsBot = ItemsBot & “, “ & vbCrLf _ & Miscrosoft.VisualBasic.Left(TheItem, TabPos - 1)

Telling the First Item from Others

Finally, you can tell whether the current item is the first item purchased by checking the length of ItemsBot. If the current item is the first one, nothing has been bought before. The length of ItemsBot will be zero. The code to add the item name to the list ItemsBot should be as follows:

If Len(ItemsBot) = 0 Then ‘First item, just keep the item name ItemsBot = Miscrosoft.VisualBasic.Left(TheItem, TabPos - 1) Else ‘Not the first item; add a comma, and concatenate the new item ItemsBot = ItemsBot & “, “ & _ vbCrLf & Miscrosoft.VisualBasic.Left(TheItem, TabPos - 1) End If

Obtaining the Price

So far, you have taken care of the list of items bought. How do you get the price from TheItem? Recall that the price starts from one position beyond the tab character, and extends to the end of TheItem. The Mid function can be used neatly to find the price string:

Mid(TheItem, TabPos + 1)

Recall that the Mid function takes three parameters. When the last parameter is omitted, it returns the remainder of the string beginning with the position specified in the second parameter.

Accumulating the Total

You will use the variable Total to keep track of the total purchases by the customer. The price string obtained previously should be converted to numeric data before it is added to Total. You can use the Val function to convert the price string, such as:

‘ Add the purchase price to total Total = Total + CSng(Val(Mid(TheItem, TabPos + 1)))

The Complete Code for a Selected Item

As described in the project requirements, the customer buys an item when he or she clicks on it; therefore, all the preceding code should be placed in the lstVending's Click event procedure. The complete event procedure appears as follows:

Private Sub lstVending_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstVending.Click Dim TabPos As Integer Dim TheItem As String TheItem = lstVending.Text 'store selected item in a variable ' Find the position of vbTab in the clicked item TabPos = InStr(TheItem, vbTab) If Len(ItemsBot) = 0 Then ' first item, just keep the item name ItemsBot = Microsoft.VisualBasic.Left(TheItem, TabPos - 1) Else 'Not the first item; add a comma, a CrLf 'and concatenate the new item ItemsBot = ItemsBot & ", " & vbCrLf & _ Microsoft.VisualBasic.Left(TheItem, TabPos - 1) End If ' add the purchase price to total Total = Total + CSng(Val(Mid(TheItem, TabPos + 1))) End Sub

Declaring the Variables Used

Notice that four variables have been used: ItemsBot, Total, TheItem, and TabPos. You need to consider their data types and scope. In terms of their data types:
Both ItemsBot and TheItem are used to handle string data. They should be declared as the String type.

In terms of their scope:

Dim ItemsBot As String Dim Total As Single

Beware that you are not allowed to break a string constant into multiple lines as shown below:
lblDemo.Text = “This is a demonstration of _ an extremely long string message” 
In the first line, the compiler considers the space and the underscore as a part of the string literal; it fails to recognize it as an underscore for line continuation. The correct code should be:
lblDemo.Text = “This is a demonstration of  ” _ & “an extremely long string message”

Handling “That’s all."

Finally, consider handling the event when the user clicks the button with the text, ”That’s all”. This is the event where your program should tell the user what he or she purchased as well as the total amount. The list of purchased items has been collected in the lstVending Click procedure. You would like for the computer to show a message such as the following:

You have purchased Boston Red Lobster, Florida Orange Juice. The total is $32.90.

More Text on Separate Lines

If you examine the tentative output carefully, you should notice that both the first line and the last line of output are on separate lines from the purchase list. In addition, there is a period at the end of the purchase list as well as the end of the total. This means vbCrLf and the period should be added at the proper places. Notice also the amount displayed has a $ sign, and there should be two decimal places, suggesting that the total should be formatted with the Currency format. The code should appear as follows:

MsgBox(“You have purchased” & vbCrLf & ItemsBot & “.” & __ vbCrLf & “The total is “ & Format(Total, “Currency”) & “.”)/

A Finishing Touch

There is another fine point you should consider. What if the user clicks the “That’s All button before clicking any item? Using the previous line will result in the following message:

You have purchased . The total is $0.00.

Although that’s not too bad, it does not appear very neat. You would rather inform the user that he or she has not yet selected any item. Recall that you can test whether any item has been purchased by checking the length of ItemsBot; therefore, the more complete code is as follows:

If Len(ItemsBot) = 0 Then MsgBox(“You have not selected any item yet.”) Else MsgBox(“You have purchased” & vbCrLf & ItemsBot & “.” & _ vbCrLf & “The total is “ & Format(Total, “Currency”) & “.”) End If

Reinitializing Data for the Next Customer

After the message is displayed, you should also clear ItemsBot and Total so that the vending machine will be ready for another customer. To do this, you can assign a zero-length string to ItemsBot and a value 0 to Total:

ItemsBot =”” Total = 0

Complete Code, ''That’s all."

Recall that the name of the button is btnShow. The complete procedure to handle the event when the customer clicks the That’s All button should appear as follows:

Private Sub btnShow_Click(ByVal Sender As System.Object, ByVal e As System.EventArgs) Handles btnShow.Click If Len(ItemsBot) = 0 Then MsgBox("You have not selected any item yet.") Else MsgBox("You have purchased" & vbCrLf & ItemsBot & "." & _ vbCrLf & "The total is " & Format(Total, "Currency") & ".") ItemsBot = "" Total = 0 End If End Sub

Finally, you should also take care of the event when the user clicks the Quit button:

Private Sub btnQuit_Click(ByVal Sender As System.Object, ByVal e As System.EventArgs) Handles btnQuit.Click Me.Close() End Sub

Additional Remarks

The vending machine example involved four event procedures:

Run and test the program. If everything works correctly, you should be able to verify that the computer:

Last change: February 13 2016 18:47:34.