Unit V Practice Exercises — Repetition

CS 1130 Visual Basic—Spring 2018

I have totally reworked this set of activities. Thus, there will certainly be errors in either the sample project, the tasks provided for you, or both. Please have patience as we work through these opportunities for learning repetition in Visual Basic.

Overview

We are gaining facility and experience with programming and should be ready for a little more complexity. Repetition is our primary new capability but with it often comes files, class variables, arrays, and creating our own subroutines.

Computer programs are useful because they allow a problem to be solved repeatedly. Sometimes that means running the program today, then next week, then next month, then next year. Sometimes that means allowing the user to cause repetition by clicking on a button. This assignment addresses the capability of having the computer repeat instructions for solving a problem or (more often) for solving a part of a problem automatically. Knowing what to repeat and how to control the repetition are the main ideas we need to address.

This assignment involves pieces of several problems we have worked on in the past—flashcards and the pizza ordering app. It also includes a new piece—text analysis. All the problems will involve looping constructs (For ... or Do Until ... or Do While .... Some will ask you to do at least two versions of looping—a counting loop and an indefinite loop.

I encourage you to work with a partner, either using pair programming (one person types and one person watches for mistakes and swap roles every 30 minutes or so) or working side by side on separate computers. This way each person interacts with the code on each item—the only way to learn the material.

I have prepared a Visual Basic Project you can use to develop and test your code. It is available in the notes directory. I suggest you rename the folder with your initials after you download and unzip it, then give it your own name, e.g., unitV_jpe.

Pepe's Pizza App

In addition to repetition we will also be dealing with other new ideas—working with the controls array for forms, processing items in a collection (a list box in this case), and writing values to a file.

  1. Reset the controls in a form

    After adding a pizza selection to an order it might be useful to reset all the radio buttons to be not checked. This can be done using many individual statements like rdo8.Checked = False. But, it can also be done by accessing the controls in the form's controls array. This also uses a different form of repetition—using an iterator. The controls we want to access are in group boxes and we cannot get to them directly. We must first find/specify the group boxes in the form and then process their radio buttons. The code for controlling the actions is shown below. (Variables are italicized.)

    	Dim control, grpControl As Control
    	For Each control In Me.Controls
    	    If TypeOf control Is GroupBox Then
    	        For Each grpControl In control.Controls
    	            DirectCast(grpControl, RadioButton).Checked = False
    	        Next
    	    End If
    	Next
    

    In this case the For loop doesn't do automatic "counting", rather it automatically sets the looping variable to the "next" control. It's like magic :-)

    Your code will need to be one of the last things that happens in the subroutine thats handles the click of the Update the Order button.

  2. Input validation

    Sometimes when a user enters data you want to be sure they entered data that is acceptable. Typically this requires a loop that keeps checking the data until the data entered is acceptable. A general algoritm (not code) for this is:

    set dataOk to False
    repeat until dataOk
         get the input data
         if the-data-tests-as-okay then
              set dataOk to True
         else
              show incorrect-data-message

    Note that you can test the data directly but you have to initialize it to some value before the loop starts.

    Your task is to make sure the text boxes for the server and the table have appropriate values. For this example you can assume anything entered is appropriate, i.e., the length of the values in the text boxes is greater than zero. This code should be included in the Submit the Order button.

    The deletion to the algorithm is due to my oversight of the fact that in event-driven situations (like this one) the user causes the repetition by repeatedly clicking the Submit the Order button. The algorithm will not work here but it works great in other situations and is something you will want to be aware of.

  3. Prepare the order ticket

    This task also relates to the Submit the Order button. After checking the table and server values, prepare the order ticket. The order ticket includes the table and server values and then the information that is in the list box for the order. Normally we would print the order so we could hand it to the cook staff. In this case we will just build a string with the first line containing the table and server and then each pizza ordered on a single line. We'll use a message box to display the string. You will want to add (concatenate) a VBNewLine at the end of each line of the string.

  4. Prepare the bill/receipt

    The receipt will be similar to the order ticket but not include table and server. It will need to include each order and a price based on the size of the pizza—$5.00, $7.50, $11.00, $15.00. After printing each pizza and price on a single line:  1) print "Subtotal" and the subtotal value,  b) print "Tax" and the tax value (7.5% of the subtotal),  c) print "Gratuity/Tip",  and d) after a blank line "Total" and the overal total value.

    Instead of actually printing the receipt you can either construct a string with the specified content or write the information to a file. File related aspects of writing to the file are shown below. The italicized material is algorithm, not code.

    	Dim reptFile as IO.StreamWriter
    	reptFile = IO.File.CreateText("receipt.txt")
    	Dim dataLine as String
    	Dim total as Double = 0
    	loop to process each element in the listbox
    	    prepare the value in dataLine to write to the file
    	    accumulate the value for the total
    	    reptFile.Writeline( dataLine )
    	end of loop
    	reptFile.WriteLine( "Subtotal" & total.ToString("C") )
    	reptFile.WriteLine( "Tax       " & (calculation-for-tax).ToString("C") )
    	reptFile.WriteLine( VBNewLine & "Gratuity/Tip" )
    	reptFile.WriteLine( "Total   " & (total + calculation-for-tax).ToString("C") )
    	reptFile.Close()
    

Flash Cards

There are a variety of ways we might use repetition in the flash card program. Some are noted below. This version has changed somewhat—there is a master and a problem presenter. The master allows you to set the terms of the drill. You may choose to implement only addition and multiplication if you wish. The drill master has settings for the operation to be practiced, items presented in each set, and minimum correctness value. The idea is that at least the "items presented in each set" problems will be presented but you may require that the user get some percentage of them correct. For example, 10 items per set and 90% correct in which case 10 items would be presented and if the user got at least 9 right they would be done. However, if less than nine were correct, another set would be presented the test for being done assessed again.

Test your code with at least addition and multiplication and for each test the following data situations:

  1. some number of items per set and a zero value for the minimum percent correct—check two or three different values
  2. some number of items per set and some reasonably high (50% or better) value for minimum percent correct

Password Strength

The selection (Unit IV) learning activity contained some password strength problems. With repetition, the coding becomes a little more complex and a lot simpler/shorter. While the tests for using upper and lower case letters can be done the same way, the tests for including digits and special characters becomes much simpler. However, it requires nested loops. An algorithm showing the approach is provided below.

    digitFound <-- False
    digits <-- "0123456789"
    specialChars <-- "!@#$%^&*()_+:;-='?/,."
    pPosit <-- 0 
    while pPosit < password's length and Not digitFound
    |   dPosit <-- 0
    |   while dPosit < digits' length and Not digitFound
    |   |   if character at pPosit in password = character at dPosit in digits
    |   |   |   digitFound = True
    |   |   |----
    |   |   dPosit <-- dPosit + 1
    |   |--------
    |   pPosit <-- dPosit + 1
    |------------

If you don't mind wasting a bit of computer time you can replace the while loops with for loops as show below (still need to declare digits and specialChars)

    for pPosit <-- 0 to password's length - 1 
    |   for dPosit <-- 0 to digits' length - 1
    |   |   if character at pPosit in password = character at dPosit in digits
    |   |   |   digitFound = True
    |   |   |----
    |   |--------
    |------------
  1. Password Strength

    Make up your own definition for password strength or use this: Strength depends on: a) length (1 point per character) and one additional point for each of the following characteristics: b) lower-case letter, c) upper-case letter, d) digit, e) special character. Report strength as one of the following: weak (scores less than 10), okay (scores of 10-12, good (scores of 13-15), strong: (scores over 15).

Text Analysis

With looping we can make interesting use of our string functions. We can determine the number of words, or sentences, in a piece of text. We can do a frequency distribution of word lengths (like counting the number of rolls for the dice values). We can count the number of vowels in a word. With these capabilities we can also determine the reading level of a piece of text (see last problem).

The repetition activities here are provided below. Presumably the user will either enter some test in the multi-line text box or designate a file to be processed. (The file should be located in the bin/Debug folder of your project.) If the text box is empty, check to see if a file has been identified (the code supplied in the practice program template allows this to happen). If neither has a value, your code should report that condition and ask the user to designate data to be processed. Code to declare and read a file is shown below. Note: the first two lines are already included in the sample code for the project.

	Dim fileIn as IO.Streamreader
	fileIn = IO.File.OpenText(theFile)
	
	Dim dataLine as String
	Do Until fileIn.EndOfStream
	    dataLine = fileIn.ReadLine
	    process the line of data
	Loop
	fileIn.Close()
  1. Number of characters

    Determining how many characters a string in a textbox contains is straightforward. A file can be read as one big string but you should read the file line by line and to determine the number of characters.

  2. Number of words

    A word has a space after it or is at the end of a line/piece of text.

  3. Number of sentences

    A sentence ends with a period, question mark, or exclamation point.

  4. (this is optional) produce a frequency distribution of the word lengths for a piece of text, from a text box or file.

Note that I have included two files in the bin\Debug folder that you could use in the text processing.

Process Reminders

Don't forget to use Save All. And, use it early and at least after completing a part (form or subroutine or ...) of the program.

If you have problems and want me to examine what is going on, you can either copy and paste your code into an e-mail message that also describes the problem or you can send me the project using the process below.

  1. compress/zip the folder
  2. upload the compressed file via the submission upload page
  3. send me an e-mail message describing your difficulty and indicating that you have uploaded the project