Lab 2

advertisement
Practical Programming
Practicals
Practical 2
Values, Types, Arithmetic and Making Decisions in VB.Net
This practical centres around doing arithmetic and making decisions in VB.NET. You will do
a variety of calculations, explore input from text boxes and output to textboxes and labels.
The words input and output are used from the computer’s point of view.
Input:
Output:
When a person provides information to a computer program
When a computer program displays information for a person to see
Before the Lab Session
No special preparation is required for this laboratory session. However, we are building on
the ideas in Practical 1. The instructions will assume that you can: start Visual Studio .NET
(the development environment), create a new VB .NET project (ie: start a new program); put
controls onto a form; set property values; set up an event to handle a button press; and build
and test your program. You may find that a few minutes revision of Practical 1 is useful.
Getting Started
You may find it helpful to create a folder called Lab2 inside your 153 folder. You can put
programmes written this week into that folder.
Remember, when you first start a new lab session, Visual Studio takes a few minutes to
‘launch’. Please be patient.
A first example calculation
The programs we will be developing in this lab session are mostly of the style: have a screen
with some text boxes, in which a person can enter values; have a button to press; when the
button is pressed some calculation is performed and the result displayed. For example,
consider the program shown running in Fig 1.
Figure 1: GST calculator programme
The idea here is that a person enters a price into the top text box ($10); clicks the button; the
programme calculates the GST and displays it in the lower text box ($1.25).
1. Start your own GST Calculator programme. The only new thing in this programme is the
way of actually doing the calculation (which will be step 2). So, using the ideas learned in
Practical 1 put controls onto a form as shown in Figure 1. (You will need to use ‘Label’
controls to show “Enter price of goods” and “GST on price”.) Think about the names you
should give your controls and set the text values of all controls (including the form itself).
Answer questions 1 and 2 on the review page now.
2. Doing the GST calculation. Under current New Zealand taxation policy, the GST payable
on any price is 12.5%. Double click on the ‘Calculate’ button to create an ‘on click’ event
handler. Try the following assignment statement
Private Sub CalculateButton_Click . . .
GSTTextBox.Text = PriceTextBox.Text * 12.5 / 100
End Sub
The statement says: Evaluate the expression on the right hand side of the =, ie: take the Text
property value of the PriceTextBox control and calculate 12.5% of it (multiply by 12.5 and
divide by 100); and put the resulting value into the GSTTextBox control’s Text property.
3. Test the program with 10.0 in the Price text box. What is the result? Is it correct?
Whenever we allow a person to input a value to a computer, we must worry about what will
happen if the person supplies an inappropriate value
4. Test the program again. This time type some non number text into the Price text box, eg:
Hello. What happens? Hint: the best way of escape from this is to quit. Answer review
question 3.
Whenever a computer stores or works with a value, we need to know just what kind of value it
is. What happened in step 4, was that the wrong kind of value was supplied for a
multiplication operation. In VB .NET the word ‘type’ to refer to the kinds of values we use.
We will come back to this program later, so make sure it is saved.
Types
In VB .NET, each property has a type. For example the ‘Width’ property of a control is of
type ‘Integer’. This means that it can hold a whole number value, in the range ±2 billion
approx. VB .NET can do arithmetic on ‘Integer’ values, including addition (+),
subtraction (-), multiplication (*), division (/), and raising to a power (^). In contrast the
‘Text’ property of a control is of type ‘String’ – just a sequence of characters.
Our next example program doesn’t serve any useful purpose. It just provides us with an
opportunity to experiment with arithmetic.
Sizing and moving buttons
5. Start a new program – call it Lab2b. Put four buttons on to the form. Three buttons can be
left with the names and text Button1, Button2, and Button3. Position Button1 near the top
right corner of your form, Button3 near the bottom left, and Button2 somewhere in between.
Practical Programming
Practicals
Name the fourth button GoButton and put the text “Go” on it. Position it near the bottom
right corner. It should look like the window shown in Fig 2.
Figure 2: Second example program
6. Add an event handler for the GoButton click event. Try the statement.
Button2.Left = (Button1.Left + Button3.Left) / 2
What does this do? How would you put Button2 half way between buttons 1 and 3 vertically?
(Note: The ‘Top’ property sets vertical position).
7. What happens if you leave out the parentheses in the expression of step 6. Explain. Ie:
Button2.Left = Button1.Left + Button3.Left / 2
8. What statements would you use to position Button2 exactly beneath Button1 (Fig 3, left)?
9. What statements would you use to position Button2 as shown in the right of Fig 3?
Figure 3: Button layouts for steps 8 and 9.
Note: It is rare to write program instructions to move and size buttons – usually we just place
the button where we want it and leave it there. However, if you think of the same kind of
program organising pictures on the window, it makes more sense.
Scaling pictures
10. Find a picture somewhere. In “My Documents” you should find “My Pictures” and
within that “Sample Pictures”. See Fig 4. If that doesn’t work try the Google Image search
for something interesting (and polite to share with everyone in the lab) and save it.
Figure 4. Sample images usually available on Windows computers.
11. Start a new program. Put a ‘PictureBox’ control on your form. Set it’s Image property to
the picture you have found. (Click on the … and navigate to the picture file.) When you first
load the picture you will probably only see a corner. Try setting the PictureBox’s SizeMode
property to StretchImage. What happens now? What happens if you resize the image?
12. Add buttons to increase and decrease the width of the PictureBox by 1/10th.
We have seen that controls have properties. Property values can themselves have properties.
An Image has properties of its own. We get at them with more dots and names. For example
the image knows its own ‘natural’ size, regardless of the way a picture box might have scaled
it. We can get at the natural width of an image being used by a picture box by:
PictureBox1 . Image . Width
13. Extra: Try some exercises similar to the button placement examples, using pictures
instead of buttons.
Keep your program from this section to show your demonstrator. (Review question 5.)
Practical Programming
Practicals
To the power of
One of the arithmetic operations in VB .NET is ^, meaning ‘raise to the power of’.
14. Create another program called ‘Powers’ something like that shown in Fig 5. When
‘Calculate’ is pressed it should calculate 2 to the power of the number in the text box.
Figure 5: Powers of 2
15. Extra: You will notice that it is tedious to use this program repeatedly. Try adding a
button which adds one to the number in the text box, and then performs the calculation.
16. VB .NET allows ‘arithmetic’ on strings as well. To get more interesting output from the
‘Powers’ program try something like
ResultLabel.Text = “The answer is: “ + 2 ^ Inbox.Text
In this case we are “adding” two strings – VB .NET interprets the + operation between two
strings as concatenation – joining the two strings end to end. So
“Hello “ + “World” is just the same as “Hello World”
Addition (concatenation) is the only operation allowed on strings. (We could think of sensible
ideas for multiplication and subtraction, but they have not been provided.) The fact that we
can ‘add’ two strings does mean that we need to look a little more closely at our operations on
strings.
An Addition programme
17. Start a new program called “Adder”. Put two text boxes, one button and a label on the
form, as shown in Fig 6. Add an event handler for the ‘Add’ button click, so that the two
numbers entered in the text boxes are added and the result put into the result label. To do this
first try
ResultLabel.Text = BoxOne.Text + BoxTwo.Text
What happens? Why?
Figure 6: The Adder Program
The problem is that addition of Strings and Numbers is quite different. In this example, to get
a sensible result you need to clearly show the VB system when and where to convert between
numbers and strings. Use Val to convert a string to a number. Use Str to convert a number to
a string. The following statement should make this program work correctly.
ResultLabel.Text = Str(Val(BoxOne.Text) + Val(BoxTwo.Text))
18. Try correcting the program using Val and Str as shown. What happens now if you enter
non number values into the text boxes? What do you think is going on here?
Back to the GST program
19. Modify the statement in the GST program using the Str and Val functions. Answer review
question 6.
20. Choose your own calculation example – eg: Fahrenheight to Centigrade temperature
conversion; area of a circle; currency conversion. Build a program to perform the calculation.
Be prepared to demonstrate your program.
Practical Programming
Practicals
Making Decisions in Visual Basic .Net
Programs statements do three kinds of things. The first is arithmetic – calculating values, or
sometimes just moving values from one place to another. The second is making decisions –
looking at values and, depending on what they are, doing different things. The third is
repeating – doing some action again and again. Our topic for this week is the second –
‘making decisions’ (guess what’s coming in the next week or two). As usual we will meet
some new aspects of the VB.Net programming environment on the way. In this part of the
practical we will work with the RadioButton and GroupBox controls.
Check Boxes (Display options – colour and show/hide)
21. Try implementing the program presented in the lecture that allowed a user to choose,
using a check box, whether to have a yellow background colour on the form.
What happens to the background colour of controls sitting on the form? Try buttons, labels
and text boxes.
Experiment with this. What happens if you explicitly set the background colour of a button?
You can answer review question 8 partly now, but will need to revisit it after experimenting
with GroupBox later.
22. Sometimes we use a checkbox to control whether other controls are visible or not. Write
a program with a check box and a picture box control, so that the picture box is visible only
when the check box is checked.
Keep this program to show for verification.
Alternative Calculations A
This is a very typical use of the if statement – to perform a calculation that needs to be done
differently in different situations.
23. Try doing your own implementation of the Tax Rate calculation from the lecture. The
statements are quite complex here – three different options to consider. Spend some time to
satisfy yourself that you understand what is going on.
24. Can you operate your tax rate program just using the keyboard? Use the <Tab> key to
move between controls. Use the <Enter> key to ‘press’ a button. Is this better than using
mouse and keyboard? Were you doing that anyway?
Add the following statement after your tax rate calculation in the button click event handler
IncomeTextBox.Focus()
Note: This statement is rather different from those we have used to date. We have written
statements that set properties of controls. In this case ‘Focus’ is a command (also called a
method) of the control – we are not setting a property value – we are asking the control to do
something – in this case become the ‘current input’ or ‘keyboard focus’. That is shown (rather
oddly) by the empty parentheses after the word ‘Focus’.
What does focus do? Is this helpful?
25. Why do we have a button? What if the program just calculated the new tax rate
immediately we type something into the IncomeTextBox? Some variation is possible, but one
way of doing that is to supply an event handler for the ‘TextChanged’ event of the
IncomeTextBox. (Double click on the text box to create the handler). Now, put all your
calculation statements into the new handler, instead of the button click handler.
Experiment! What way of operating this program do you like best? (Review question 11)
Alternative Calculations B
26. Try implementing the Fruit Prices example from the lecture.
Things to think about: What happens if an inappropriate value is entered? How easy is it to
add extra options? Program this with the if statement as well as the Select Case
statement
Using Radio Buttons
27. The radio button provides an alternative way of allowing a person to make a choice. Your
task is to program something like that shown in Fig 7. As a first step start a new program and
put three Radio Button controls on the form – don’t set any properties. Try running the
program and see how the buttons work. How could you arrange for the program to start with
one button already selected?
28. If you want to have several groups of radio buttons, as shown in Fig 7., you must place
each group of buttons on a different GroupBox. Experiment with placement.
29. Try writing the program of Fig 7. The idea is that a person selects options in each group
of radio buttons, fills in the name, and then presses OK. In most programs with this kind of
screen the data would then be put in a database. For our example, you are asked to program
instructions to make sentences and display them in labels at the bottom of the screen.
Practical Programming
Fig 7: A program with many selections
Show your finished program to your demonstrator (Q14)
Practicals
Practical 2: REVIEW PAGE
Name: ______________________
Questions: Complete the following questions. (Note: this must be done before you seek a
verification).
1. Explain your choice of names for the controls you used in this programme.
2. To what values did you set the ‘Text’ properties of the two text box controls, when writing
the program? Ie: What values appear when the program first runs? Why?
3. What happened when you entered a value that wasn’t a number into the GST calculator?
4. What happened when the parentheses were left out in step 7? Explain.
5. Demonstrate your image scaling program.
6. Write down your GST statement with and without Str and Val functions, and explain what
type conversions occur
7. Show your demonstrator your calculation program.
Practical Programming
Practicals
8. If the background colour of a form is set to yellow, what determines the background
colours of controls on the form? What happens with a GroupBox or a Panel that has controls
of its own?
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
9. Show your demonstrator the program you wrote for task 22 (Picture box example).
10. How did you test the tax rate calculation program?
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
11. What style of input did you like best for the tax rate program? Why?
________________________________________________________________________________________
________________________________________________________________________________________
12. How can you make a program start with one of a group of radio buttons already selected?
________________________________________________________________________________________
________________________________________________________________________________________
13. Why would you want a program to start with a radio button selected?
________________________________________________________________________________________
________________________________________________________________________________________
14. Demonstrate your selection program to your demonstrator.
Verification:
Grade: 0 – 4 and Signature – for Demonstrator to Fill In
Download