Unit II Practice/Learning

CS 1130 Visual Basic

Overview

Unit II addresses interpreting and constructing numeric and string expressions in Visual Basic. The focus of the practice activity will be on creating and testing expressions. During that process you should gain facility with:

The assignment builds on the expressions form produced the Unit I practice assignment. You may start a new VB project in Visual Studio and create your own form or download the project I created and placed in the project folder of the notes directory (its title is VB-practice_unit-II.zip). If you choose to use it, you may modify it as you please and I suggest you change its name before starting—after unzipping replace "_unit-II" with your name/initials.

I suggest you use at least two forms for this assignment—one for numeric expressions and one for string expressions. You also have a choice of where you place your code.

The choice is yours. There is no "right" way and I suspect there really isn't a better way. Remember that you can copy and paste both controls and code to make the job easier.

Once you have the form you can start work on the assignment. You are to use an existing button or create a new one for each task indicated below. Then you should supply code that will accomplish the task and display the result of your code. If you use an existing button you will want to comment out any previous code for that button.

Note that this unit coincides with one of the competency/mastery demonstrations. That demonstration will be like an in-class quiz. (Remember that the demos are pass/fail and can be re-taken with little penalty but with time contraints.)

I encourage you to work all the problems to maximize your experience. Consider forming a partnership or group in which everyone verbally shares their work and reflects on differences found. You may also share them with me if you wish and ask questions or seek feedback about particular aspects of particular examples.

Specifications

I have divided the problems into subgroups. You may create a button for each subgroup and place the code for each problem there, commenting out code for the previous problem when you move on the the next. Alternatively you can create a button for each problem, perhaps labelling it with the problem number and place code for that one problem with the button. I do suggest that you use at least two forms, one for numeric problems and one for string problems.

When done you should probably copy all your code and paste it into a text file (perhaps using NotePad) to more easily allow for sharing your code during class discussion.

Numeric Exercises

The input for these problems should mostly be entered in text boxes. You could use message boxes to provide directions for each problem. Unless otherwise directed, report your results with an explanation, i.e., the result and words that explain what it represents.

Basic Numerics

  1. pay

    Calculate gross pay for a pay period (probably a week). You'll want to get values for pay-rate and hours-worked from the user. Use a message box to display a labeled result.

  2. time to travel

    Determine the time needed to travel an indicated distance. In addition to the desired distance, you'll want to get a value for speed from the user. Report the result using a message box.

  3. hybrid savings

    Get input values for miles driven per year, MPG with current car, MPG with new hybrid, and cost of gasoline; then calculate and report the cost of fuel for each and the savings with the hybrid. Report the labeled results in a message box.

  4. your own "problem"

    Think of a problem that seems similar to these and produce code that will get appropriate input values and produce an "answer".

More Advanced Numerics

  1. pay with overtime

    Calculate gross pay for a pay period (probably a week). You'll want to get values for pay-rate and hours-worked from the user. Be sure to include time-and-a-half for overtime hours. Use a text box to display a labeled result.

  2. Celcius to Fahrenheit

    Accept a value for a temperature on the Celcius scale and produce equivalent value on the Fahrenheit scale. Report your

  3. military time conversion

    Accept a four digit number representing military (24 hour) time, e.g., 0730 or 2145, and produce the equivalent 12 hour time, e.g. 7:30 or 9:45. (You need not worry about AM & PM.)

  4. one of the following
    • sale price

      I want to advertise a sale by indicating how much a customer has to pay. Provide code that allows me to enter the original price and a "percent off", and then tell me the sale price I can advertise. Use a text box to report the labeled result.

    • percent off

      I wish to advertise a sale item by indicating the savings percentage or "percent off" for the sale. I know the original price and I want try several different values for what I might charge. Provide code that will tell me what "percent off" I should claim in my advertising for a given pair of values for original price and sale price. Report the labeled result in a text box.

    • original price

      A sale advertisement indicates the sale price and the savings or "percent off" figure. Provide code that will report the

  5. average of averages

    Assume I know the averages for two exams and I want to find the overall average. Accept input for the average score and the number of scores included for each of the exams. Calculate and report the overall average of the two sets of scores.

  6. your own "problem"

    Think of a problem that seems similar to these and produce code that will get appropriate input values and produce an "answer".

Numeric Functions

  1. total cost

    My daughter always wanted to know if she had enough money to buy something. Provide code that will accept input for price and tax-rate and then produce the total cost value. Report that labeled value using the MessageBox() method. Round the result to the nearest cent.

  2. die roll

    Use the Rnd() and Fix() functions to produce a value for a standard (1-6) die roll. Report the result using the MessageBox() method.

  3. craps roll

    As above but report the total when two dice are rolled. Report the result using a message box.

  4. generate an addition problem

    Produce a drill & practice addition problem that asks the user to add two integers between 0 and 10 (inclusive). Use a message box to present the problem in the form of X + Y = ? where X and Y are replaced by the random numbers you generated.

  5. generate an subtraction problem

    Produce a drill & practice subtraction problem. (Hint: generate an addition problem as above, calculate the sum, and then present the problem as sum - x = ?.)

  6. peeps offspring

    Peeps are entities that live for 6 years. At age two they mate for life (magically half are male and half are female :-) At ages three and four each pair produces a single offspring. Get values for the number of 3-year and 4-year olds and report the number of peeps that will be born. (Note: there cannot be half a peep.)

  7. floor tiles

    Accept input for the length and width of a room (in inches) and for the size of floor tile to be used, e.g., 4 inches square. Determine and report the number of tiles needed. Note: tile remnants can not be used.

  8. arbitrary random integer

    Accept input for the low value and the high value for a range of random numbers. Then generate and report a random value in the range [low, ..., high] (inclusive).

  9. your own "problem"

    Think of a problem that seems similar to these and produce code that will get appropriate input values and produce an "answer".

String Exercises

As above, the input for these problems should mostly be entered in text boxes. You could use message boxes to provide directions for each problem. Unless otherwise directed, report your results with an explanation, i.e., the result and words that explain what it represents.

Basic String Actions

  1. welcome message

    Accept a value for a person's name and use a message box to welcome the person to the class, e.g., "Welcome to Visual Basic, Philip!"

  2. address

    Use the InputBox() method to get values for city, state (code), and zip; then, combine the values as in an address (i.e., City, ST  zip) and display the results in the output text box.

  3. increment

    Accept a value for a number in a text box, add one to the value, and report the result back in the same text box. What happens if you click the button again?

  4. your own "problem"

    Think of a problem that seems similar to these and produce code that will get appropriate input values and produce an "answer".

String Functions

  1. password length

    Accept a value representing a password and indicate how many characters it contains. Try clicking the button without typing anything.

  2. first character

    Use a message box to report the first character of the value entered via the text box.

  3. last character

    Use a message box to report the last character of the value entered via the text box.

  4. location of @

    Use a message box to report the first location of the at sign (@) in the value entered via the text box. Be sure to include a test value that does not include the at sign.

  5. location of comma

    Use a message box to report the first location of a comma in the value entered via the text box. Be sure to include a test value that does not include a comma.

  6. first word length

    Use a message box to report the length of the first word of the value entered via the text box. Be sure to enter more than one word. (Words are separated by spaces.)

  7. first word

    Use a message box to show a copy of the first word of the value entered via the text box. Be sure to enter more than one word. (Words are separated by spaces.)

  8. second word

    Use a message box to show a copy of the second word of the value entered via the text box. Be sure to enter more than one word. (Words are separated by spaces.)

  9. mail server

    Use a message box to report the mail server name entered via the text box. The mail server is the value between the at sign (@) and the dot (.) in an e-mail address.

  10. city, state, zip

    Accept a value from the small text box that represents the City, ST  zip and report the values on separate lines in the bigger text box. Note: vbNewLine can be used (via concatenation) to place a return character in a string.

  11. your own "problem"

    Think of a problem that seems similar to these and produce code that will get appropriate input values and produce an "answer".

In Closing

As you work, remember that the purpose is familiarization with variables, different data types, functions, form element/control properties and expressions. If you have questions, ask. If you are confident you know how to do one of the activities skip it if you want. Be aware that the competency demo questions will likely be similar to what you see here.

Extra Credit

Extra credit will be available to those who produce code to do the bulk of the tasks noted above and add a report-to-file capability to their program. Perhaps the easiest way to do so is to append each answer to a file when you report it to the screen. I suggest you produce a string that is your "answer" to each problem and report it to the screen and then append it to the file. You will need to include the following code at the top of the Start class (just below Public Class Start

    Public report As IO.StreamWriter

And, insert the following code in the Start form's "load" procedure (double click on the start form and you should be taken to the correct place in the code/.VB file).

    report = IO.File.AppendText("unit-II_report.txt")
    report.WriteLine(DateAndTime.DateString())

And, insert the following code in the btnExit button's click handler (double click on the and you should be taken to the correct place in the code/.VB file). Be sure to place it before Me.Close()

    report.Close()

(The following "should" not be necessary but I didn't figure out how to do without it.) In both the "numerics" and "strings" forms, we need to declare a local variable to provide access to the file declared in the "start" form. So, at the top of each of those form's code, include:

    Private report as IO.StreamWriter = Start.Report

Then in the "numerics" and "strings" forms, declare a string to store your answer, use it to report to the screen, then write it to the file, e.g.,

     Dim result as String
     
     '...  declare variables and do whatever is need to get the answer ready

     result = '... set the value of what you plan to report to the screen
     
     '... show your result using   MessageBox.Show(result)  or  txtResult.Text = Result
     
     report.WriteLine(result)     'write your result to the file

For example, my solution to #20 might look like

    Dim result as String
    '...  code for previous problems
    
    '. . . . . #20 arbitrary random integer
    Dim lo, hi, randVal As Integer
    lo = Val(txtInput1.Text)
    hi = Val(txtInput2.Text)
    randVal = Fix(Rnd() * (hi - lo + 1)) + lo
     
    result = "#20: A random number in [" & lo.ToString & " ... " & hi.ToString _
             & "] is " & randVal.ToString
    txtResult.Text = result
    
    report.WriteLine(result)

To submit your work for extra credit evaluation prepare your program. When done, run it testing each of the problems with 2-3 of values. The file should save the results each time you run it. You can view the file by looking in the projects bin/Debug folder. If you want to start over, just delete it. When done, zip the project (& change its name) and send me an e-mail message:

Final Suggestions

To maximize the learning experience with these examples consider how you might change them to make them "better", functionally or aesthetically. And, devise a VB form for some application or problem from your discipline (or that is of personal interest) that you would like to see implemented. If this activity were graded, some results here would be required for an A.

Remember, have fun! Feel free to embellish what you see. The goal is to familiarize yourself with the form objects and their properties (such as font, size, color etc.).

Process Reminders

Don't forget to use Save All. And, use it early and at least after completing each new task.

If you have problems and want me to examine what is going on