basic feed line vbcr visual
Transcription
basic feed line vbcr visual
Programming Standard Grade Computing Studies C Wilson, 2007 [VISUAL BASIC 2005 EXPRESS EDITION] Programming in Visual Basic Express CONTENTS Page GETTING STARTED Creating a Visual Basic Project ……………………………………………………….…. 3 Storing your Visual Basic Projects ………………………………………………………… 6 FOUNDATION Displaying information (TextBox) …………………………………………………………. 9 Displaying Several Lines of Information (ListBox) ……………………………..………. 10 Simple Calculations ………………………………..…………………….………….…… 12 Variables & Data Types ……………….………………………………...……………….. 13 Worked Example – Area ……………………………………………………………….… 14 Installing the PrintForm Component ……………….………………….……………….. 18 Using the PrintForm Component ………………..……………………………………….. 19 SQA Task – Food Mixers ……………………….……………………………………….. 23 Loops (FOR Loop) ………………………………..……………………………………….. 25 Worked Example – Punishment Exercise! …………………………………………...... 26 SQA Task – Car Stickers ………………………………………………………………… 29 GENERAL Modules & Sub-routines (design & code) …………………………….………………... 33 IF … THEN (Selection) ………………………….………………….….………………... 35 Worked Example – Car Sales ………………………….….…………………………….. 36 SQA Task – School Heating ………………………..….……………….……………….. 39 User Interface – MessageBox …..………………..….……………….………………… 41 User Interface – InputBox ……………………………………….……………………….. 44 Worked Example – Currency Converter …………….…………….….………………... 46 SQA Task – Car Hire …………………………………………………………..…………. 51 Running Totals & Counters ………………………..……………………………………… 53 Loops & Control Variables …………………………….…….…….……………….….….. 54 Worked Example – Rainfall Program ………………………….….…………………….. 56 SQA Task – Over Forty …………………………………..……..……….……………….. 61 CREDIT Complex Conditions – AND / OR ………………..…………….……………….……….. 65 Loops (WHILE Loop) ……………………………………………………………………… 65 Input Validation – MessageBoxes / Pre-defined & user-defined functions ………….. 66 Program Testing ………………………………………………………………………….. 72 Worked Example – Can You Drive? ……………………………………………………. 73 SQA Task – Language Course ………………………………………….…….………... 77 Random Numbers ………………………………………………………………………….. 79 Boolean Variables ………………………………………………………………………… 80 Worked Example – Dice Game ………………………………………………………… 81 SQA Task – Guess Number ……………………………………………………………... 85 Arrays ………………………………………………………………………………………. 87 Worked Example – Golden Ticket ……………………………………………………… 91 SQA Task – Charity Lottery ……………………….……………………………………... 95 C Wilson, 2007 -2- Programming in Visual Basic Express Creating a new Visual Basic Project When you launch Visual Basic Express your screen should look like the one below. Click as shown to create a new programming project. Before we can start programming, we provide Visual Basic with a name for our project. Make sure „Windows Application‟ is selected as below Enter „First Program‟ for our project name and click „OK‟. C Wilson, 2007 -3- Programming in Visual Basic Express You will arrive at the „form design‟ screen like the one below. We will use this screen to create the user interface for our programs. To create our user interface we will use the „toolbox‟ located on the left hand side of our screen. Hover your mouse over the toolbox icon and click the little „pin‟ icon to keep the toolbox on your screen as shown below. C Wilson, 2007 -4- Programming in Visual Basic Express Your screen should now appear like the one below. We will use the toolbox to create objects on our blank form by dragging them. Users of our program use these objects to enter inputs and view outputs while our programs are running. The toolbox looks very complicated at first but don‟t worry! We‟re only going to use a few of the items in it to create our programs. C Wilson, 2007 -5- Programming in Visual Basic Express Storing your Visual Basic programming projects. As with all your previous practical work in Computing, your programming work should be stored in your „home directory‟ on the school‟s file server. The Visual Basic default setting is to save your programming work on your local computer‟s hard disk (it‟s C: drive), and we need to change this. From the „Tools‟ menu select „Options‟ as shown. In the Options window, select „Projects and Solutions‟ then click the button shown to select a new location. Navigate to your programming folder. This should be located inside the Computing folder inside your home directory. Ask your teacher for help if necessary. If you move to another machine in your class, you must repeat these steps again. C Wilson, 2007 -6- Programming in Visual Basic Express Now we‟re ready to start programming… Hooray! C Wilson, 2007 -7- Programming in Visual Basic Express FOUNDATION LEVEL C Wilson, 2007 -8- Programming in Visual Basic Express Displaying Information (TextBox) In our first program we shall get Visual Basic to display a message in what is called a „textbox‟. Create a „command button‟ and a „textbox‟ as shown below. Double click the command button to enter program code below… Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'My First Program 'Visual Basic Express 'Your name 'Today's date Start typing here TextBox1.Text = "Hello World!" Finish typing here End Sub End Class Run your program and correct any mistakes if necessary. „Save All‟ when done. Exercise: Write a program to make the name of your favourite band / singer appear on screen C Wilson, 2007 -9- Programming in Visual Basic Express Displaying Several Lines of Information (ListBox) So far we have looked at getting Visual Basic to display a single line of text in a text box. In this program we shall get Visual Basic to display a message several lines long in what is called a „listbox‟. Create a new project called „ListBox‟, then add a „command button‟ and a „listbox‟ as shown below. Double click the command button to enter program code as follows… Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Listbox Program 'Visual Basic Express 'Your name 'Today's date ListBox1.Items.Add("Hello World!") ListBox1.Items.Add("Computing is fun!") ListBox1.Items.Add("") ListBox1.Items.Add("And, Programming is easy!") Start typing here Finish typing here End Sub End Class Run your program and correct any mistakes if necessary. „Save All‟ when done. C Wilson, 2007 - 10 - Programming in Visual Basic Express SUMMARY Copy the following into your jotter. Command Button Textbox Allows the user to run program code when pressed. Allows the program to display a single line of text. E.g. textbox1.text=”Hello” Allows the program to display multiple lines of text. E.g. listbox1.items.add(“Hello”) listbox1.items.add(“My name is Elvis”) Listbox To clear a listbox of text, enter listbox1.items.clear() To display a blank line, enter listbox1.items.add(“”) Any text starting with „ will be ignored by the computer. These lines are known as comments and are used by Comments programmers to include short notes about the program. Every program you write should contain some comments. C Wilson, 2007 - 11 - Programming in Visual Basic Express Simple Calculations Create a new project called „Calculate‟. Add a „command button‟, a „listbox‟ and two „textboxes‟ as shown below. Textbox1 Textbox2 Double click the command button to enter program code as follows… Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Simple Calculations Program 'Visual Basic Express 'Your name 'Today's date TextBox1.Text = ("") TextBox2.Text = ("") ListBox1.Items.Clear() 'clear the contents of textbox1 if any 'clear the contents of textbox2 if any 'clear the content of listbox1 if any ListBox1.Items.Add("4 + 5") ListBox1.Items.Add(4 + 5) TextBox1.Text = 4 + 5 TextBox2.Text = "4+5" End Sub End Class Using speech marks makes the program display the exact text inside the speech marks. Without speech marks the computer can display the answer to a calculation. Run your program to see what happens. Do you understand it? Run your program and correct any mistakes if necessary. „Save All‟ when done. C Wilson, 2007 - 12 - Programming in Visual Basic Express Variables Variables provide temporary storage for information that will be needed while a program is running. A programmer can imagine a variable as being a box into which information can be placed. When a programmer wants to store something, she or he gives a storage location a name and tells the computer what to put there. Using that name later (the name of the variable), you can get out (recall) the stored information at any time. For example, a program to calculate the area of a rectangle might use the following variables. When the program is running the data can be entered by the user and then stored, or it can be automatically calculated by the computer and then stored. The stored data may change every time the program is run, but the variable names remain the same. A programmer may have as many variables in a program as she or he needs. All that matters is that the variables have different names. Data Types Variables can store different types of data. The above example stores integer numbers, but there are others. Before a variable can be used in a program it must be „declared‟. Data Type Examples Visual Basic declaration Integer 3, 7, -2, -99, 54 Dim length as integer Decimal 1.5, 3.14, -6.758 Dim length as decimal String Mary, joe, dog, Dim name as string Sounds confusing? Don‟t worry, look at the following example… C Wilson, 2007 - 13 - Programming in Visual Basic Express Worked Example - Area We are going to write a program to allow the user to enter the length and breadth of a rectangle. The program will then calculate and display the area. Method: I will take user input from two textboxes and store them in variables called ‘length’ and ‘breadth’. I’ll then get the computer to perform a calculation to find the area and store it in a variable called ‘area’. Finally, I’ll display the area in a third textbox. To avoid confusion I’ll label all the objects on the screen. Create a new Visual Basic project and call it „‟Area‟. Create a „command button‟, three „labels‟ and three „textboxes‟ as shown below. Textbox1 C Wilson, 2007 Textbox2 Textbox3 - 14 - Programming in Visual Basic Express Changing „button‟ and „label‟ text To change the text for our command button and labels do the following: Click once on the command button to highlight it. In the „Properties‟ window at the bottom right of the screen change the „Text‟ value from „Button1‟ to „Calculate Area‟ as shown below. Your command button should now look like this (you may need to re-size it a little to see all the text). Repeat the above steps to change the text on the labels to „length‟, „breadth‟, and area. Remember to highlight them first! C Wilson, 2007 - 15 - Programming in Visual Basic Express Your final layout should look like the one below. Now double click the command button to enter program code as follows… (Notice some of the code has already been entered for you – you will get used to this) Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Area Program 'Visual Basic Express 'Your name 'Today‟s Date Dim length As Decimal Dim breadth As Decimal Dim area As Decimal 'Create variables length = TextBox1.Text breadth = TextBox2.Text 'Get inputs and store them area = length * breadth 'Calculate Area and store it TextBox3.Text = area 'Display Area Start typing here Finish typing here End Sub End Class C Wilson, 2007 - 16 - Programming in Visual Basic Express Run your program to test it works as expected. First, enter values for length and breadth. Now click the „Calculate Area‟ command button. Using a calculator if needed, check that the expected result is the same as the actual result. „Save All‟ when done. C Wilson, 2007 - 17 - Programming in Visual Basic Express Finishing Touches – Printing Output The PrintForm component for Visual Basic 2005 must be added to the Toolbox before you can use it for the first time1. Ask your teacher if you should carry out the steps below to add the PrintForm component to your Visual Basic toolbox. This should be a „one-off‟ task for you to complete at the machine you use for your programming. Installing the PrintForm Component The following procedure describes how to add the component to the Toolbox. To add the PrintForm component to the Toolbox 1. Click the „Common Controls‟ heading in the toolbox to highlight it. 2. From the Tools menu, select Choose Toolbox Items. 3. In the Choose Toolbox Items dialog box, select PrintForm from the .NET Framework Components list and click the checkbox next to it. 4. Click OK to add it to the Toolbox. 1 The PrintForm Component is available as an additional download from Microsoft.com. If necessary, search for ‘PrintForm Component’. Once installed on a computer, each individual user wishing to use it must add it to their own Visual Basic toolbox. C Wilson, 2007 - 18 - Programming in Visual Basic Express Using the PrintForm Component Once the PrintForm Component is installed, you can create an extra command button on your program forms to allow the user to print at any time when the program is running. Drag the PrintForm tool onto your form. Notice that it does not actually appear on the form itself. It is displayed at the bottom of the window as shown. Click once on the PrintForm icon and change the „PrintAction‟ from „PrintToPrinter‟, to „PrintToPreview as shown. This will allow you to check your printout on screen before sending it to the printer. C Wilson, 2007 - 19 - Programming in Visual Basic Express Now we need a command button to press in order to print our program while it is running… Drag another command button onto your layout and label it „Print‟. Double-click on this new button and add the following one line of code. Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click PrintForm1.Print() 'allows the user to print form End Sub Finish off by adding a label and entering your name on the form and by changing the text title of the form to Area problem. Your final screen should look like the one below. Run your program and make sure it all works. „Save All‟ when you are happy with it. C Wilson, 2007 - 20 - Programming in Visual Basic Express SUMMARY Your finished code should look like the code below. Note that it actually contains two „subroutines‟, one for each command button. Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Area Program 'Visual Basic Express 'Your name 'Today‟s Date Dim length As Decimal Dim breadth As Decimal Dim area As Decimal 'Create variables length = TextBox1.Text breadth = TextBox2.Text 'Get inputs area = length * breadth 'Calculate Area TextBox3.Text = area 'Display Area End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click PrintForm1.Print() 'allows the user to print form End Sub End Class Exercise For each of the following tasks, make sure that all objects are labelled and that the final output can be printed by the user. Let your teacher see each program running when finished. 1. Write a program to enter three numbers and calculate the total. 2. Modify your program above to calculate the average of the numbers. 3. Write a program to calculate the area of a circle. C Wilson, 2007 - 21 - Programming in Visual Basic Express SQA Assessment Task Practical Abilities Foundation Level Your mark for this task will be used by the Scottish Qualifications Authority in deciding your overall award. C Wilson, 2007 - 22 - Programming in Visual Basic Express COMPUTING PRACTICAL ABILITIES TASK STANDARD GRADE FOOD MIXERS a programming task assessing grades 5, 6 and 7 Name ________________________________________ Class _______________ Centre ________________________________________ Date _______________ Your teacher will outline how you should do this task and give you opportunities for discussion. Read and follow all instructions carefully, use hardware and software properly and write your report neatly. Instead of being paid an hourly rate, some workers are paid for the number of items they make each week. Ann Hay assembles 86 food mixers and is paid £3.50 for each one. You are required to write a program to calculate and display her earnings. The user should be asked to enter the number of mixers and payment for each mixer. You should use meaningful variable names such as mixers. 1 DESCRIBE METHOD - Analysis 3 marks Show that you understand what is required by describing how you will do this task. ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ 2 LIST STEPS - Design 2 marks The main steps are Calculate Wage, Get Inputs, and Show Wage. Write the steps in the correct order below. 1 __________________________________________________________________________ 2 __________________________________________________________________________ 3 __________________________________________________________________________ C Wilson, 2007 - 23 - Programming in Visual Basic Express 3 ENTER PROGRAM - Implementation 5 marks Create the program. Include internal commentary. Correct any mistakes that you make. Save your program. 4 TEST PROGRAM - Testing 4 marks Work out Ann’s wage for assembling 86 mixers at £3.50 each. You may use a calculator. What was your answer? £___________ Run the program to find its answer for 86 mixers at £3.50 each. What was the program’s answer? £___________ Work out Ann’s wage for assembling 90 mixers at £4.10 each. You may use a calculator. What was your answer? £___________ Run the program to find its answer for 90 mixers at £4.10 each. What was the program’s answer? £___________ Compare your answers with the program’s answer and write a comment. ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ 5 GET PRINTOUTS - Implementation 2 marks Get two printouts with your name on them. One should show your code and the other a run using one set of test data given above. 6 SUGGEST IMPROVEMENT - Evaluation 2 marks Write down one way in which your program could be better. ____________________________________________________________________________ ____________________________________________________________________________ 7 JUDGE PERFORMANCE - Evaluation 2 marks Read this task sheet again. Describe how well you think you have done the task. ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ C Wilson, 2007 - 24 - Programming in Visual Basic Express Loops (FOR loop) In computer programming, a loop is an instruction or sequence of instructions that is continually repeated over and over. Instead of typing out the code 10 times we can tell the computer to repeat a single line of code until it has done it 10 times. Example In a new Visual Basic project, create a „command button‟ and a listbox as shown below. Double click the command button to enter program code as follows… Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim NumberOfTimes As Integer 'create a variable for our loop For NumberOfTimes = 1 To 10 ListBox1.Items.Add("Hello") Next 'loop ten times End Sub End Class Start typing here Finish typing here Run your program. The message „Hello‟ should be displayed ten times. C Wilson, 2007 - 25 - Programming in Visual Basic Express Worked Example: Punishment Exercise Program Task Design and write a program to write 100 punishment exercise „lines‟ for a naughty pupil. The line to be repeated will be entered by the pupil using the keyboard (screen design on next page). Method: I have to write a program to write punishment exercises lines. The program will take user input in a textbox and then repeat it 100 times in a listbox when a command button is pressed. I will use a FOR loop to repeat the lines. To avoid confusion I’ll label all the objects on the screen. Design 1. Get user to input „line‟ in textbox 2. Do 100 times 3. Display „line‟ in listbox 4. Display a blank line in listbox 5. Next Code Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)Handles Button1.Click 'Punishment Exercise Program 'Visual Basic Express 'by Me 'June 07 'declare variables Dim line As String Dim no_of_lines As Integer line = TextBox1.Text ' get user input 'loop 100 times to complete lines For no_of_lines = 1 To 100 ListBox1.Items.Add(line) 'display punishment exercise line ListBox1.Items.Add("") 'display a blank line Next End Sub End Class C Wilson, 2007 - 26 - Programming in Visual Basic Express Sample Runs C Wilson, 2007 - 27 - Programming in Visual Basic Express SQA Assessment Task Practical Abilities Foundation Level Your mark for this task will be used by the Scottish Qualifications Authority in deciding your overall award. C Wilson, 2007 - 28 - Programming in Visual Basic Express COMPUTING STANDARD GRADE PRACTICAL ABILITIES TASK CAR STICKERS a programming task assessing grades 5, 6 and 7 Name ________________________________________ Class _______________ Centre ________________________________________ Date _______________ Your teacher will outline how you should do this task and give you opportunities for discussion. Read and follow all instructions carefully, use hardware and software properly and write your report neatly. You are required to write a program for a firm that makes stickers for car windows. The user should input the sticker text at the keyboard. The program will display that text four times as shown right. There should be a blank line after each line of text. A FOR … NEXT loop should be used. YOU ARE DRIVING TOO CLOSE! YOU ARE DRIVING TOO CLOSE! YOU ARE DRIVING TOO CLOSE! YOU ARE DRIVING TOO CLOSE! 1 DESCRIBE METHOD - Analysis 3 marks Show that you understand what is required by describing how you will do this task. 2 LIST STEPS - Design 2 marks Write down the main steps in the program. C Wilson, 2007 - 29 - Programming in Visual Basic Express 3 ENTER PROGRAM - Implementation 5 marks Create the program. Include internal commentary. Correct any mistakes that you make. Save it. 4 TEST PROGRAM - Testing 3 marks Describe how you tested that your program worked. ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ 5 GET PRINTOUTS - Implementation 2 marks Get two printouts with your name on them. One should show your code and the other a run. 6 WRITE INSTRUCTIONS - Documentation 3 marks Write a short explanation on how to run and use your program after it has been loaded. ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ 7 SUGGEST IMPROVEMENT - Evaluation 2 marks Write down one way in which your program could be better. ____________________________________________________________________________ ____________________________________________________________________________ 8 JUDGE PERFORMANCE - Evaluation 2 marks Read this task sheet again. Describe how well you think you have done the task. ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ C Wilson, 2007 - 30 - Programming in Visual Basic Express Checklist Before moving on to the next section, make sure you are fully happy with the following essential skills… User Interface Creating a TextBox Creating a ListBox Creating Command Buttons Creating Labels Program Code Using a TextBox to obtain input Using a TextBox to display output Using a ListBox to display output Creating variables (and data types) Performing calculations FOR loop Program comments You MUST let your teacher know if you are unsure about anything before continuing. C Wilson, 2007 - 31 - Programming in Visual Basic Express GENERAL LEVEL C Wilson, 2007 - 32 - Programming in Visual Basic Express MODULES AND SUBROUTINES When programmers have to write big long Area Problem programs, they divide the program into sections and just write a small section Get inputs (module) at a time. Calculate Area Display Area You are not going to write a big long program, but you are going to learn how to divide a program into sections (modules). In Visual Basic these sections are called subroutines. Each subroutine starts with Sub and ends with End Sub. Here is a program you have done before. However, this time we shall use subroutines to write it. Tip: One of the best ways to break a problem up into smaller ones is to split it into three main sections to start with – input, process and output. Example Design and write a program to calculate the area of a rectangle. The length and breadth are to be entered from the keyboard. DESIGN Top Level 1. Get inputs The „top level‟ of our 2. Calculate area design is a list of what our 3. Display area Refinements 1.1 Prompt for and input length 1.2 Prompt for and input breadth program will need to do. The „refinements‟ allow us to specify exactly how these main steps will be carried out. 2.1 Set area to length * breadth Note the numbering 3.1 Display message and area system used for each of the refinements. C Wilson, 2007 - 33 - Programming in Visual Basic Express Program Code Public Class Form1 'Area Program with Subroutines 'Visual Basic Express 'C Wilson 'June 2007 'All variables must be declared before use Dim length As Decimal Dim breadth As Decimal Dim area As Decimal Using subroutines, shared variables (variables used by more than one subroutine), are declared at the very start of the program code. THIS IS IMPORTANT!!! Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Main Program / Top Level DESIGN 'Steps here are used to call subroutines get_inputs() calculate_area() display_area() End Sub Top Level 1. Get inputs 2. Calculate area 3. Display area Sub get_inputs() 'Prompt for, and store length and breadth length = TextBox1.Text breadth = TextBox2.Text End Sub Refinements 1.1 Prompt for and input length Sub calculate_area() 'store the value for area in a variable area = length * breadth End Sub 1.2 Prompt for and input breadth 2.1 Set area to length * breadth Sub display_area() 'display the stored value for area TextBox3.Text = area End Sub 3.1 Display message and area End Class Note that this program also makes good use of internal comments throughout. You should do the same in all of your own programs. Open your earlier project called „Area‟ and change the code so it matches that above. „Save All‟ when you have it working. C Wilson, 2007 - 34 - Programming in Visual Basic Express IF … THEN (Selection) So far our programs have done everything we have asked them to – all the instructions we have entered have been carried out by the computer. Sometimes we might want the computer to choose whether or not to run some of our code. This is known as „selection‟ and can be very useful when programming. Examples If age > 17 Then TextBox1.Text = "You can vote" End If If age is 19 then you can vote appears on the screen. If age is 12 then nothing happens. Rather than do nothing in some situations, you can have have alternative code by using the „else‟ command. If test_score < 50 Then TextBox1.Text = "Sorry, you failed." Else TextBox1.Text = "Well done, you passed!" End If Let‟s look at a worked example… C Wilson, 2007 - 35 - Programming in Visual Basic Express Worked Example – Car Sales Joe Quimby owns a second-hand car showroom. He is a very tough boss and sets sales targets of £50,000 per day for each of his staff! At the end of each day he gathers in sales figures from his staff for the day. No employees are allowed to sell less than five cars per day or they‟re fired! Also, the total sales for the day for each employee must be greater than £50,000 or they will also be fired! Write a program to calculate the total sales of five cars for an employee. The program should then display an appropriate message saying whether the employee is fired or not. Call your Visual Basic project „Car Sales‟. Method: The program will take 5 user inputs (car1, car2, car3, car4 and car5) from TextBoxes when a command button is pressed. I’ll then calculate the total sales for the employee. Finally, I’ll display the total sales and then, using an IF condition, I’ll display an appropriate message about the employee. Screen Design Two command buttons – Calculate Total and Print Seven textboxes – 5 for car sales, 1 for total, 1 for message Labels as appropriate C Wilson, 2007 - 36 - Programming in Visual Basic Express Program Code & Design Public Class Form1 'Car Sales Program 'Visual Basic Express 'by Me 'June 07 'declare variables Dim car1 As Decimal Dim car2 As Decimal Dim car3 As Decimal Dim car4 As Decimal Dim car5 As Decimal Dim total As Decimal Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Main Program / Top Level get_sales() calculate_total() display_message() End Sub Sub get_sales() 'input sales data car1 = TextBox1.Text car2 = TextBox2.Text car3 = TextBox3.Text car4 = TextBox4.Text car5 = TextBox5.Text End Sub Sub calculate_total() 'calculate total sales total = car1 + car2 + car3 + car4 + car5 End Sub Sub display_message() 'display program outputs TextBox6.Text = total If total > 50000 Then TextBox7.Text = "Well done!" Else TextBox7.Text = "You're fired!" End If End Sub Top Level 1. Get sales 2. Calculate total sales 3. Display outputs Refinements 1.1 Prompt for and input car1 price 1.2 Prompt for and input car2 price 1.2 Prompt for and input car3 price 1.2 Prompt for and input car4 price 1.2 Prompt for and input car5 price 2.1 Set total = car1+car2+car3+car4+car5 3.1 3.2 3.3 3.4 3.5 3.6 Display total in textbox 6 if total >£50,000 then Display “Well done!” in textbox 7 else Display “You‟re fired!” in textbox 7 end if Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click PrintForm1.Print() End Sub End Class C Wilson, 2007 - 37 - Programming in Visual Basic Express Sample Runs C Wilson, 2007 - 38 - Programming in Visual Basic Express COMPUTING STANDARD GRADE PRACTICAL ABILITIES TASK SCHOOL HEATING a programming task assessing grades 3, 4, 5 and 7 Name ________________________________________ Class _______________ Centre ________________________________________ Date _______________ Your teacher will outline how you should do this task and give you opportunities for discussion. Read and follow all instructions carefully, use hardware and software properly and write your report neatly. The heating system in a school should be switched on if the average temperature is less than 17 degrees Celsius (˚C). The average temperature is found from the temperatures in the Art, English and Music Departments. You are required to write a program that allows the user to input the three temperatures. The program calculates and displays the average temperature then displays ‘Heating should be on.’ or ‘Heating should be off.’ as appropriate. 1 DESCRIBE METHOD - Analysis 3 marks Show that you understand what is required by describing how you will do this task. ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ 2 LIST STEPS - Design 6 marks On a separate sheet of paper, show the main steps and refinements. 3 ENTER PROGRAM - Implementation 5 marks Create the program. Include internal commentary. Correct any mistakes that you make. Save it. C Wilson, 2007 - 39 - Programming in Visual Basic Express 5 marks 4 TEST PROGRAM - Testing Complete the table below, by entering test data. You should enter sets of three temperatures then calculate the average and indicate whether heating should be on or off. The first set should have an average below 17˚C, the second set an average of exactly 17˚C and the third average should be above 17˚C. Complete the last two columns by recording the program’s output with your chosen test data. Art temperature English temperature Music temperature calculated average temperature calculated on or off program’s average temperature program’s on or off Compare your calculations with the program’s output and write an appropriate comment. ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ 5 GET PRINTOUTS - Implementation 2 marks Get two printouts with your name on them. One should show your code and the other a run using one of your sets of test data. 6 SUGGEST IMPROVEMENT - Evaluation 2 marks Write down one way in which your program could be better. ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ 7 JUDGE PERFORMANCE - Evaluation 2 marks Read this task sheet again. Describe how well you think you have done the task. ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ Your mark for this task will be used by the Scottish Qualifications Authority in deciding your overall award. C Wilson, 2007 - 40 - Programming in Visual Basic Express Some new interface tools… So far, all of our user interface objects have been created using the toolbox to drag objects onto our forms. This is fine, but our screen might become „cluttered‟ with textboxes and buttons etc. that we have no further use for after the user has entered their information. Visual Basic allows the programmer to use other techniques to show some special objects on the screen only while the program is running and at a time chosen by the programmer. Two common examples are the „MessageBox‟ and the „InputBox‟. The MessageBox A „MessageBox‟ displays a message in a „dialogue box‟ and then waits for the user to click a button before going on with the program. Look at the following examples and the program code required to produce them on screen. MsgBox("Bye bye!") [The word „Demo‟ is taken from the project title.] MsgBox("Bye bye!", , "Finish Program") [Rather than use the project title, the programmer can code their own title for each MessageBox. Notice that this code requires two commas side-by-side.] C Wilson, 2007 - 41 - Programming in Visual Basic Express MsgBox("Bye bye!", MsgBoxStyle.Critical, "Finish Program") [See the „critical‟ graphic!] The examples above are all very easy to add to your programs. The window displays a message and waits for the user to click OK. The user has no choice but to click OK. Now look at the following example, MsgBox("Are you sure you want to exit?", MsgBoxStyle.YesNo, "Finish Program") This a little more interesting – the user has a choice of buttons to click! This might seem all too easy, but the code required to make this choice actually work is a little more complicated. We have already learned that to write code to deal with selection or choice we use the IF command. With this in mind here‟s what the design for the above MessageBox should look like… Design 1. Prompt user to make choice Notice that we don‟t actually need to use an 2. If choice = “yes” then „else‟ in this case. If the user clicks „No‟ then 3. the program will not finish. Exit Program 4. End if Now let‟s look at actually creating some MessageBoxes… C Wilson, 2007 - 42 - Programming in Visual Basic Express To create an „Exit‟ command button with choice… Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click 'Code for Exit command button with message box Dim response As Integer response = MsgBox("Are you sure you want to exit?", MsgBoxStyle.YesNo, "Finish Program") If response = vbYes Then End 'Exit program End If End Sub To create a „Print‟ command button with choice… Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click 'Code for printing button with message box Dim response As Integer response = MsgBox("Are you sure you want to print?", MsgBoxStyle.YesNo, "Print") If response = vbYes Then PrintForm1.Print() 'Print End If End Sub Exercise For your earlier programs, „Total‟, „Average‟ and „Area‟, do the following… Add „Exit‟ and „Print‟ command buttons to them that will present the user with a choice as shown above. Be sure to „Save All‟ your work when done. C Wilson, 2007 - 43 - Programming in Visual Basic Express The InputBox An InputBox is a small window which only appears on the screen while the program is running and input is needed from the user. The user‟s input can then be stored in a variable so that the rest of the program can use it. The InputBox can be especially useful when lots of inputs are required from the user and creating lots of TextBoxes with labels would be too time consuming and take up lots of screen space. The code for an input box looks like this: Variable_Name = InputBox(“Prompt”, “Title for box”) The things in italics will be changed to suit your program. E.g. Dim Name As String Name = InputBox("Please enter your name", "Enter Name") The above example will produce this on the screen when the line of code runs: i) Title T i Prompt t l e Space for input In this example the variable called „Name‟ would now be storing the data „Darth‟ when the user clicks OK. C Wilson, 2007 - 44 - Programming in Visual Basic Express Try this, Create a new project called „Message‟. Design a form like the one below. Enter the code below for your command button. Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)Handles Button1.Click 'InputBox Demo 'Visual Basic Express 'by Me 'June 07 Dim Name As String Name = InputBox("Please enter your name", "Enter Name") 'Display message TextBox1.Text = "Hello " & Name End Sub End Class „Save All‟ when you have it working. Exercise Modify your program above so that it also asks your age. The program should then display, in another textbox, a sentence like, „You are 14 years old‟. C Wilson, 2007 - 45 - Programming in Visual Basic Express Worked Example – Currency Converter Write a program to calculate and display a table showing the amount of currency available for each pound. The program needs the name of the country, the currency and the exchange rate of the currency. These will be entered from the keyboard by the user. If France is the destination, then a message should be displayed informing the user of a special offer. Method: The program will take all user inputs (country, currency and exchange rate) from inputboxes when a command button is pressed. As each is entered I will display it in a textbox on the screen. I will display table headings in a listbox and then use a FOR loop to display the actual conversion table in the listbox. I’ll use an IF condition to display a special message if the country is France. Since the program may be run more than once, I’ll make sure that the listbox and all the textboxes are cleared at the start of the program. Screen Design Two command buttons – convert and print. Three textboxes for output - country, currency and exchange rate. One listbox – output conversion table. Labels as appropriate. Inputboxes for user input. C Wilson, 2007 - 46 - Programming in Visual Basic Express Program Design Top Level 1. 2. 3. 4. Clear previous data Get data Display table Special Offer Refinements 1.1 1.2 1.3 1.4 Clear Textbox1 Clear Textbox2 ClearTextbox3 Clear Listbox1 2.1 2.2 2.3 2.4 2.5 2.6 Prompt for and input country Display country in textbox1 Prompt for and input currency Display currency in textbox2 Prompt for and input exchange rate Display exchange rate in textbox 3 3.1 3.2 3.3 3.4 3.5 Display table headings in listbox columns – pounds and currency Display blank line Do 20 times Display pounds in column 1, pounds*exchange rate in column 2 Next 4.1 4.2 4.3 4.4 If country is France then Display message in listbox – We‟ll convert your currency back for free Display message in listbox – We like France! End if Note that only the steps for solving the problem need to be shown in your designs. If you wish to include other buttons such as „Exit‟ and „Print‟, you do not need to add them to your design. C Wilson, 2007 - 47 - Programming in Visual Basic Express Program Code Public Class Form1 'Currency Converter Program 'Visual Basic Express 'Joe Bloggs 'June 07 Dim country As String Dim currency As String Dim exchange_rate As Decimal Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Main Program Top Level clear_data() get_data() display_table() special_offer() 1. 2. 3. 4. Clear previous data Get data Display table Special Offer End Sub Refinements Sub clear_data() 'clear textboxes and listboxes if program has already been run TextBox1.Text = "" TextBox2.Text = "" TextBox3.Text = "" ListBox1.Items.Clear() End Sub Sub get_data() 'Allow user to supply input via inputboxes and display in textboxes country = InputBox("Please enter country...") TextBox1.Text = country currency = InputBox("Please enter currency...") TextBox2.Text = currency exchange_rate = InputBox("Please enter exchange rate...") TextBox3.Text = exchange_rate End Sub Sub display_table() 'Output Table headings ListBox1.Items.Add("Pounds" & VbTab & currency) ListBox1.Items.Add("") 'prints a blank line 1.1 1.2 1.3 1.4 Clear Textbox1 Clear Textbox2 ClearTextbox3 Clear Listbox1 2.1 2.2 2.3 2.4 2.5 2.6 Prompt for and input country Display country in textbox1 Prompt for and input currency Display currency in textbox2 Prompt for and input exchange rate Display exchange rate in textbox 3 3.1 Display table headings 3.2 Display blank line 'loop to output conversion from 1 to 20 pounds Dim pounds As Integer For pounds = 1 To 20 ListBox1.Items.Add(pounds & VbTab & pounds * exchange_rate) Next End Sub 3.3 Do 20 times 3.4 Display table row 3.5 Next Sub special_offer() 'Display special offer if appropriate If country = "france" Then ListBox1.Items.Add("") ListBox1.Items.Add("We'll convert your currency back for free!") ListBox1.Items.Add("We like France!") End If End Sub 4.1 If country is France then 4.2 Display message in listbox … 4.3 Display message in listbox … 4.4 End if Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click PrintForm1.Print() End Sub End Class C Wilson, 2007 - 48 - Programming in Visual Basic Express Sample Runs C Wilson, 2007 - 49 - Programming in Visual Basic Express SQA Assessment Task Practical Abilities General Level Your mark for this task will be used by the Scottish Qualifications Authority in deciding your overall award. C Wilson, 2007 - 50 - Programming in Visual Basic Express COMPUTING STANDARD GRADE PRACTICAL ABILITIES TASK CAR HIRE a programming task assessing grades 3, 4, 5 and 7 Your teacher will outline how you should do this task and give you opportunities for discussion. Read and follow all instructions carefully, use hardware and software properly and write your report neatly. Cherair Car Hire Company has a range of cars for rent. Charges start at £20 a day for the cheapest to £70 a day for the most expensive. Cherair requires a program that gives customers printed details of charges. The program asks the user for a car make, model and daily rate then displays a table of daily charges for between one and fourteen days. If the make is Ford, a message indicating a gift of a free road atlas is displayed. An example of output is shown below. The output from your program may look different but must meet the specification. C Wilson, 2007 - 51 - Programming in Visual Basic Express 1 DESCRIBE METHOD - Analysis 3 marks Show that you understand what is required by describing how you will do this task. ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ 2 LIST STEPS - Design 6 marks On a separate sheet of paper, show the main steps and refinements. 3 ENTER PROGRAM - Implementation 5 marks Enter the program listing. Include internal commentary. Correct any mistakes that you make. Save the listing. 4 TEST PROGRAM - Testing 5 marks On a separate sheet of paper, show how you tested that your program worked properly. Use two sets of test data, one involving a Ford car and one not. Compare your expected output with the program’s output and write an appropriate comment. 5 GET PRINTOUTS - Implementation 2 marks Get two printouts with your name in the footer. One should show your listing and the other a run using one of your sets of test data. 6 SUGGEST IMPROVEMENT - Evaluation 2 marks Write down one way in which your program could be better. ____________________________________________________________________________ ____________________________________________________________________________ 7 JUDGE PERFORMANCE - Evaluation 2 marks Read this task sheet again. Describe how well you think you have done the task. ____________________________________________________________________________ ____________________________________________________________________________ C Wilson, 2007 - 52 - Programming in Visual Basic Express RUNNING TOTALS & COUNTERS Often a program will require the user to enter a list of data that includes numbers. The program may be required to output the total of this numeric data or output a count of the number of times a specific item of data was entered. Keeping a „running total‟ is easy – simply add each number entered onto the value of a variable that might be called „total‟. Keeping a „count „ might require a little more care – if a certain condition is met, then add one to the value of our counter. In either case, it is very important to set the value of the running total and counter to zero before the user starts to enter their data. Examples count = 0 … If answer = correct Then count = count + 1 End If In a program adding a sequence of numbers, each numbered entered is added to a running total. In a quiz program, if the user‟s answer is correct, one is added to the count, if not, nothing happens, so „count‟ stays the same. running_total = 0 … For loop_counter = 1 To 3 number = InputBox("Enter a number...") running_total = running_total + number Next TextBox1.Text = running_total C Wilson, 2007 - 53 - Programming in Visual Basic Express LOOPS & CONTROL VARIABLES Examples of loops used so far have always been „fixed loops‟ – they have always been carried out a number of times decided by the programmer. Sometimes, the number of loops should be decided by the user‟s actions when the program is actually running. This requires an additional input by the user to specify the number of times some code should be looped. Example The following design and code could be for a program to help a teacher enter class lists. The program would start by asking how many pupils are in the class and then use a loop to allow the teacher to enter the names of the required number of pupils. Design 1. prompt for and input class size 2. loop for 1 to class size times 3. enter name 4. add name to list 5. end loop Code Dim class_size As Integer Dim name As String class_size = InputBox("Enter class size", "Class Lists") Dim loops As Integer For loops = 1 To class_size name = InputBox("Enter name", "Class Lists") ListBox1.Items.Add(name) Next C Wilson, 2007 - 54 - Programming in Visual Basic Express Totals & Counters – an everyday example… You empty out your pockets and find the following coins… You want to know two things: 1. How much money you have found in total, 2. Being a little greedy, how many of them were pound coins? Sounds easy? Of course it is. Your years of experience just allow you to work it out. But what if you had to tell a computer how to do it? It actually takes quite a bit of thought to work out just how you managed to do this simple thing, but here goes… Study the following table and design very carefully before moving on. Coin Total Count of £1 coins £1 £1 1 50p £1.50 10p £1.60 £1 £2.60 50p £3.10 5p £3.15 2p £3.17 2p £3.19 5p £3.24 1p £3.25 20p £3.45 £1 £4.45 5p £4.50 Design set total to 0 set pound_counter to 0 2 prompt for and enter no_of_coins For each coin Examine coin Set total = total + coin_value If coin_value is £1 Then Set pound_counter = pound_counter + 1 End If Next coin 3 display total display pound_counter It‟s not until you actually look at the design that you realise how well programmed your own brain already is! C Wilson, 2007 - 55 - Programming in Visual Basic Express Worked Example – Rainfall Program Meteorologists are involved in the study of weather from information obtained from the land, sea and air. One area of study is rainfall patterns. In order to speed things up, a meteorologist would like to computerise the recording and analysis of this work and has asked you to write a computer program to deal with this. Design and write a program to allow the user to input daily rainfall figures for an entire month. The program should then display the total rainfall amount for the month and the number of days on which there was no rain at all. Method: The program will take all user inputs (month, number of days and daily rainfall in mm) from InputBoxes when a command button is pressed. As each is entered I will display it on the screen. Since the number of days in a month can vary I will use a FOR loop to allow the user to enter daily rainfall figures until the number of days in the month has been reached. Screen Design TextBox1 As the data is entered by the user, I’ll keep a running total for the rainfall and a counter to keep a track of the number of ‘dry days’ entered. I’ll use an IF condition to update the dry days counter. When all the rainfall figures for the month have been entered, I’ll display the final values for the total rainfall and the dry days counter. Since the program may be run more than once, I’ll make sure that the listbox and all the textboxes are cleared at the start of the program. ListBox1 TextBox2 TextBox3 [Notice that this screen design also uses the „GroupBox‟ tool to group together some of the objects on the screen. Try it!] C Wilson, 2007 - 56 - Programming in Visual Basic Express Program Design Top Level 1. setup 2. enter rainfall data 3. display summary Refinments 1.1 Clear TextBox1 1.2 Clear TextBox2 1.3 Clear TextBox3 1.4 Clear ListBox1 1.5 set total to zero 1.6 set dry days counter to zero 2.1 Prompt for and enter month 2.2 Display month in TextBox 2.3 Prompt for and input no. of days 2.4 Loop for no. of days 2.5 prompt for and input rainfall for day 2.6 Display rainfall in listbox 2.7 set total = total + rainfall 2.8 If rainfall = 0 Then 2.9 set dry_days = dry_days + 1 2.10 End If 2.11 End loop 2.12 Display message “Thank you” 3.1 Display total 3.2 Display no. of dry days C Wilson, 2007 - 57 - Programming in Visual Basic Express Program Code Public Class Form1 'Rainfall Survey Program 'Visual Basic Express 'by Me 'June 07 Dim month As String Dim no_of_days As Integer Dim rainfall As Decimal Dim total As Decimal Dim dry_days As Integer Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Main Program / Top Level Top Level clear_screen() enter_data() display_summary() 1. 2. 3. setup enter rainfall data display summary End Sub Sub clear_screen() „clear previously entered data and zero counters TextBox1.Text = "" TextBox2.Text = "" TextBox3.Text = "" ListBox1.Items.Clear() total = 0 dry_days = 0 End Sub Refinments 1.1 Clear Textbox1 1.2 Clear Textbox2 1.3 Clear Textbox3 1.4 Clear Listbox1 1.5 Set total to zero 1.6 Set dry days counter to zero Sub enter_data() 'Allow user to enter all data and update running totals and counts 2.1 Prompt for and enter month 2.2 Display month in TextBox month = InputBox("Enter month...", "Month") 2.3 Prompt for and input no. of days TextBox1.Text = month no_of_days = InputBox("Enter no. of days in month...", "Days") 2.4 Loop for no. of days 3.1 3.2 Display Total Display no. of dray days Dim day As Integer 2.5 prompt for and input rainfall for day For day = 1 To no_of_days rainfall = InputBox("Enter rainfall in (mm) for day " & day, "Rainfall Data") ListBox1.Items.Add("Day " & day & VbTab & rainfall) 2.6 Display rainfall in listbox total = total + rainfall 2.7 set total = total + rainfall If rainfall = 0 Then 2.8 If rainfall = 0 Then dry_days = dry_days + 1 2.9 set dry_days = dry_days + 1 End If 2.10 End If Next 2.11 End loop MsgBox("Thank you") 2.12 Display message “Thank you” End Sub Sub display_summary() 'display summary of entered data TextBox2.Text = total TextBox3.Text = dry_days End Sub C Wilson, 2007 - 58 - Programming in Visual Basic Express Sample Run(1) C Wilson, 2007 - 59 - Programming in Visual Basic Express Sample Run(2) C Wilson, 2007 - 60 - Programming in Visual Basic Express COMPUTING PRACTICAL ABILITIES TASK STANDARD GRADE OVER FORTY a programming task assessing grades 3, 4, 5 and 7 Name ________________________________________ Class _______________ Centre ________________________________________ Date _______________ Your teacher will outline how you should do this task and give you opportunities for discussion. Read and follow all instructions carefully, use hardware and software properly and write your report neatly. You are required to write a program to count the number of pupils in a class of twelve who score over 40 in a test out of 60. The pupils’ marks are to be entered at the keyboard. The output is a message that indicates the number of pupils who score more than 40. 1 DESCRIBE METHOD - Analysis 3 marks Show that you understand what is required by describing how you will do this task. ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ 2 LIST STEPS - Design 6 marks On a separate sheet of paper, show the main steps and refinements. 3 ENTER PROGRAM - Implementation 5 marks Create the program. Include internal commentary. Correct any mistakes that you make. Save it. C Wilson, 2007 - 61 - Programming in Visual Basic Express 5 marks 4 TEST PROGRAM - Testing Complete the table below, firstly by writing three more sets of test data under the twelve marks listed. The given marks are all above 40. The next set should all be below 40. The next set should have marks above, below and including 40. The last set should only have marks 39, 40 and 41. Complete the second column by counting and writing down how many marks in each set are over 40. Complete the last column by recording the program’s output with your test data. pupils’ marks my count over 40 program’s count over 40 46, 54, 51, 41, 49, 58, 45, 44, 53, 50, 57, 43 Compare your count of marks over 40 with the program’s output and write an appropriate comment. ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ 5 GET PRINTOUTS - Implementation 2 marks Get two printouts with your name on them. One should show your code and the other a run using one of the sets of test data above. 6 SUGGEST IMPROVEMENT - Evaluation 2 marks Write down one way in which your program could be better. ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ 7 JUDGE PERFORMANCE - Evaluation 2 marks Read this task sheet again. Describe how well you think you have done the task. ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ C Wilson, 2007 - 62 - Programming in Visual Basic Express Checklist Before moving on to the next section, make sure you are fully happy with the following essential skills… User Interface Displaying a MessageBox Using an InputBox for user input Program Design Top Level & Refinements Program Code Running Totals & Counters FOR loops with control variables You MUST let your teacher know if you are unsure about anything before continuing. C Wilson, 2007 - 63 - Programming in Visual Basic Express CREDIT LEVEL C Wilson, 2007 - 64 - Programming in Visual Basic Express Complex conditions – AND, OR A "complex condition" contains two or more simple conditions linked by „logic operators‟ (AND and OR). They are frequently used in IF statements and some types of programming loops. Examples When might I wear shorts and a T-shirt? IF it is summer AND it is hot THEN I‟ll wear shorts and a T-shirt END IF Any other times? IF (it is summer AND it is hot) OR (it is winter AND I‟ve gone completely mad!) THEN I‟ll wear shorts and a T-shirt END IF Some example code dealing with test marks might require a complex condition like this… If score1 > 50 And score2 > 50 Then TextBox1.Text = "You passed both the tests." End If Loops (WHILE loop) A complex condition can also be used to test whether or not a section of program code should run. This can be done using a special type of loop known as a WHILE loop. In a WHILE loop, the condition is first evaluated. If the condition is true, the code within the loop is then executed. Example Design 1. Prompt for and get user to enter age 2. WHILE age < 0 OR age > 120 DO 3. 4. Prompt for and get user to enter age ENDWHILE A WHILE loop differs to a FOR loop because: A FOR loop will always run code within the loop a pre-determined number of times. A WHILE loop will run code within the loop an unknown number of times – it often depends on the user. A WHILE loop may not run the code in the loop at all in some cases! C Wilson, 2007 - 65 - Programming in Visual Basic Express Input Validation Users are constantly inputting data to running programs. They also make mistakes – particularly when called upon to enter data via the keyboard. „Input validation‟ means to check that data entered by the user while the program is running is „valid‟ or „allowable‟. Any attempt by the user to enter „illegal data‟ will be rejected by the program. It is perfectly possible that invalid data entered by a user might cause a program to crash and data to be lost. A good programmer will take every step possible to prevent their programming crashing or producing inaccurate results due to invalid data being entered by the user. Whilst it is impossible to predict every possible mistake a user might make in using a program there are some basic methods of validating input and preventing problems from occurring. Some basic approaches to validation we will look at are: 1. MessageBoxes 2. Pre-defined functions 3. User defined functions 1. MessageBoxes We have already met messageboxes. Message boxes are useful methods of input validation because they restrict input by the user. A typical example of such restriction would be a messagebox presenting the user with a „Yes‟ or „No‟ button choice as below. The only input possible here by the user is to click on „Yes‟ or „No‟. There are no other inputs possible and the user cannot type any input at this point. By programming code to deal with this messagebox, the programmer can be sure that user input will always be valid. Simple! C Wilson, 2007 - 66 - Programming in Visual Basic Express 2. Pre-defined functions. Earlier testing of your programs may have thrown up some small problems when run that the use of some pre-defined functions might be able to prevent. A pre-defined function is a piece of pre-written code that is actually part of the programming language. Many programming languages will actually have a library of these pre-defined functions, each of which is designed to perform a frequently needed task for the programmer. Here are a few useful Visual Basic pre-defined functions: Function Example Code Val Int Description number = Val("2457") 'sets number to 2457. number = Val(" 2 45 7") 'sets number to 2457 number = Val("24 and 57") 'sets number to 24. number = Val(TextBox1.Text) „converts an empty toxtebox value to 0. It is particularly useful for converting empty textboxes to the value 0 in order to avoid program crashes. MyNumber = Int(99.8) ' Returns 99. The Int function returns integer portions of numbers. In the case of a negative number, the Int function returns the first negative integer less than or equal to the number MyNumber = Int(-99.8) ' Returns -100. MyNumber = Int(-99.2) ' Returns -100. mynumber = CInt(99.8) CInt ' Returns 100. mynumber = CInt(-99.8) ' Returns -100. mynumber = CInt(-99.2) ' Returns -99. UCase The Val function actually returns the numbers contained in the data. Val stops converting at the first character that cannot be interpreted as a numeric digit or white space. City = InputBox("Enter capital city of France...") If UCase(City) = "PARIS" Then Correct = Correct + 1 Else MsgBox("Wrong!") End If CInt rounds to the nearest integer instead of „truncating‟ the fractional part of numbers as the Int function does. UCase converts lowercase letters to uppercase. Very useful for text comparisons (e.g. quiz programs) where a match is required but, the programmer cannot anticipate the exact use of capital letters made by the user. These may seem a little confusing at the moment but these pre-defined functions may be useful to refer back to in later problems. C Wilson, 2007 - 67 - Programming in Visual Basic Express 3. User-defined functions – Input Validation Programming languages like Visual Basic can have a pre-defined function library containing hundreds of useful operations like the ones described earlier. Even so, during the course of developing a programming project the need for a specific function may arise that is not part of the built-in function library. That‟s why many languages, such as Visual Basic, give programmers the ability to create their own functions. One typical example of the need for this is the ability to validate numeric input by the user. E.g. When entering a value for age it would be silly (invalid) to enter an age like -16 or 200. Using what‟s called a „range check‟ it is possible for a programmer to write a very flexible function that can validate numeric input made by the user in a variety of different situations. Example: A program might ask the user to enter the following information about pupil test scores: Name English (out of 20) Maths (out of 25) French (out of 30) Computing (out of 30) Geography (out of 40) Physics (out of 25) Art (out of 30) It is impossible to validate a name (there‟s just too many possibilities), but the program can validate the scores entered as between a minimum and maximum score. Design – Validate number 1. Prompt user to enter a number 2. WHILE number is <= min OR number >= max 3. Prompt user to re-enter number 4. ENDWHILE The above design could be applied to the entry of each of the subject test scores. There are two ways of doing this: 1. Just repeatedly enter the similar code over and over for each score – lots of code! 2. Use a function – write a function that tells the computer how to apply this idea to each score entered and then call it appropriately each time required – less lines of code. Compare the following example solutions… C Wilson, 2007 - 68 - Programming in Visual Basic Express Repeatedly entering the similar code… pupil_name = InputBox("Enter name...") english = InputBox("Enter English test score...") While english < 0 Or english > 20 MsgBox("Please enter a whole number between 0 and 20", , "Error!") english = InputBox("Enter English test score...") End While maths = InputBox("Enter Maths test score...") While maths < 0 Or maths > 25 MsgBox("Please enter a whole number between 0 and 25", , "Error!") maths = InputBox("Enter Maths test score...") End While french = InputBox("Enter French test score...") While french < 0 Or french > 30 MsgBox("Please enter a whole number between 0 and 25", , "Error!") french = InputBox("Enter french test score...") End While Extension: Reduce program crashes by using Val (inputbox… computing = InputBox("Enter computing test score...") While computing < 0 Or computing > 30 MsgBox("Please enter a whole number between 0 and 30", , "Error!") computing = InputBox("Enter computing test score...") End While geography = InputBox("Enter geography test score...") While geography < 0 Or geography > 40 MsgBox("Please enter a whole number between 0 and 40", , "Error!") geography = InputBox("Enter geography test score...") End While physics = InputBox("Enter physics test score...") While physics < 0 Or physics > 25 MsgBox("Please enter a whole number between 0 and 25", , "Error!") physics = InputBox("Enter physics test score...") End While art = InputBox("Enter art test score...") While art < 0 Or art > 30 MsgBox("Please enter a whole number between 0 and 30", , "Error!") art = InputBox("Enter art test score...") End While Using a function… pupil_name = InputBox("Enter name...") english = validate_number(0, 20, "Enter English test score...") maths = validate_number(0, 25, "Enter Maths test score...") french = validate_number(0, 30, "Enter French test score...") computing = validate_number(0, 30, "Enter Computing test score...") geography = validate_number(0, 40, "Enter Geography test score...") physics = validate_number(0, 25, "Enter Physics test score...") art = validate_number(0, 30, "Enter Art test score...") Extension: Reduce program crashes by using Val (inputbox… Function validate_number(ByVal min, ByVal max, ByVal message) Dim number As Decimal number = InputBox("Please enter a whole number between " & min & " and " & max, message) While number < min Or number > max MsgBox("Please enter a number between " & min & " and " & max, , "Error!") number = InputBox("Please enter a number between " & min & " and " & max, message) End While Return number End Function Obviously, using a function requires less lines of code. In fact if more test scores were included, the function method would only add one more line of code per test score. Without the function, each additional test score would require an additional five lines of code per test. Each of these lines would require some customisation to suit the particular test. C Wilson, 2007 - 69 - Programming in Visual Basic Express SUMMARY Using functions to validate the input of numeric variables is very efficient in terms of time to develop code and also the number of lines of code required to program. Functions actually work by coding a procedure or set of rules, and then supplying data to that particular set of rules. The following example of validation supplies three items of data (or „parameters‟) to validate input: min max message … grade = validate_number(1, 7, "Enter your computing grade...") „function call … Extension: Reduce program crashes by using Val (inputbox… Function validate_number(ByVal min, ByVal max, ByVal message) Dim number As Decimal number = InputBox("Please enter a number between " & min & " and " & max, message) While number < min Or number > max MsgBox("Please enter a number between " & min & " and " & max, , "Error!") number = InputBox("Please enter a number between " & min & " and " & max, message) End While Return number End Function The parameters within the function are substituted with data supplied by the code which „calls‟ the function. In the example above the parameter values are entered as follows: All occurrences of the parameter min become the value „1‟ All occurrences of the parameter max become the value „7‟ All occurrences of the parameter „message‟ become „Enter your computing grade…” The function above named „validate_number‟ can be used to validate whole numbers in your own programs without a single line being changed. Only the „function call‟ line of code should be tailored to suit the problem you are solving. . Exercise You should now enter and save this function code (and only the function code) using a text editor such as „WordPad‟. This will allow you to easily „copy & paste‟ this code into your future Visual Basic programs when required. Save the code with the filename „validate‟. C Wilson, 2007 - 70 - Programming in Visual Basic Express Extension – Functions for validating integers & validating decimals So now we know how to use a function to validate numeric input within a minimum and maximum. This is very useful, but one problem still remains. Consider a program to accept football scores. In this case data entered should lie within an acceptable range, but should also only be accepted if it is a whole number or integer such as 0, 1, 2, 3, 4 etc. but nothing in between. It is impossible to score 2.5 goals! Validating decimals (e.g. 3.14) This is the same code as earlier – only the name has been changed in order to clarify its purpose. Function validate_decimal(ByVal min, ByVal max, ByVal message) Dim number As Decimal number = Val(InputBox("Please enter a whole number between " & min & " and " & max, message)) While number < min Or number > max MsgBox("Please enter a number between " & min & " and " & max, , "Error!") number = Val(InputBox("Please enter a number between " & min & " and " & max, message)) End While Return number End Function Validating integers (e.g. 3) It only takes a couple of changes to our earlier function, but now we can ensure that the program will only accept integers within our range. Function validate_integer(ByVal min, ByVal max, ByVal message) Dim number As Decimal number = Val(InputBox("Please enter a whole number between " & min & " and " & max, message)) While number < min Or number > max Or (Int(number) <> number) MsgBox("Please enter a number between " & min & " and " & max, , "Error!") number = Val(InputBox("Please enter a WHOLE number between " & min & " and " & max, message)) End While Return number End Function Keeping both of these functions in a „code library‟ helps programmers to quickly write programs with correctly validated input when possible. C Wilson, 2007 Note that both these user-defined functions also make use of the pre-defined function ‘Val’ as discussed earlier. - 71 - Programming in Visual Basic Express Program Testing Once a program has been written, there then follows the testing stage. The most crucial aspect is to test that the program does what it is supposed to do and does not crash. Test Data A programmer should create sets of test data to feed the software to find out how it behaves. Here are some of the important points about making up such sets: The expected results from a test data set must be known in advance, so that they can be checked against the actual results. One set should test “normal” operation of the software, to make sure that there are no unexpected results in ordinary use. One set should test the operation “limits” of the software, to make sure that the boundary conditions are handled properly. One set should test “exceptions” to the normal operating conditions. This set will show whether or not the software can react to unexpected inputs in an effective way, without crashing. Testing must be systematic and comprehensive. It is systematic when you plan a table of test data with expected outcomes and then test the program with that data. It is comprehensive when you test as many eventualities as possible. For example if you were testing a program that took in marks out of 100 in a test you must test: Normal Data Test Data 45 78 26 Expected Result Data accepted Data accepted Data accepted Actual Result As expected. As expected. As expected. Comment Program appears OK Program appears OK Program appears OK Limits Test Data 0 100 Expected Result Data accepted Data accepted Actual Result As expected As expected Comment Program appears OK Program appears OK Exceptions Test Data -5 109 34.75 Five x Expected Result Not Accepted Not Accepted Not Accepted Not accepted Not accepted Actual Result Not Accepted Accepted Not Accepted Not Accepted Not accepted Comment Prompt to re-enter Prompt to re-enter Program continues!!! Program crash!!! Program crash!!! C Wilson, 2007 - 72 - Programming in Visual Basic Express Worked Example – Can you drive? A program is required to ask the user to enter their age and then what type of driving license (if any) that person holds. You may drive a car if you are in possession of a full driving license or if you are at least 17 years old in possession of a provisional driving license (you must have an experienced full license holder with you though). Design and write a program to allow the user to enter their age and license type. The program should then display a summary of the user inputs together with a statement indicating their entitlement to drive a car.. Method: The program will take all user inputs (age and license type) from InputBoxes when a command button is pressed. All inputs will later be summarised in a ListBox. The license type will be a number entered by the user as follows: 1. no license of any type 2. provisional license 3. full license Since all input is numeric, it will be validated. I will use an ‘IF’ statement with a ‘complex condition’ to work out if a person is allowed to drive. Finally, I will display a summary on the screen. ListBox1 TextBox1 C Wilson, 2007 - 73 - Programming in Visual Basic Express Program Design Top Level 1. 2. 3. 4. Clear the screen and initialise variables Get inputs Calculate entitlement to drive Display entitlement to drive Refinements 2.1 2.2 Prompt for, and validate, age Prompt for, and validate, current license type from menu 2.1.1 2.1.2 2.1.3 2.1.4 2.1.5 Obtain user input WHILE number is < min allowed OR number > max allowed DO Display error message Obtain user input ENDWHILE Refine step 2.2 As 2.1 above (but without a function in this case) 3.1 3.2 3.3 3.3 Set „can drive‟ entitlement to "no" IF license type = 3 OR (age >= 17 AND license type = 2) THEN set „can drive‟ to "yes" END IF 4.1 4.2 4.3 4.4 4.5 4.6 Display 2 blank lines IF „can drive‟ = "yes" THEN Display "You can drive a car." ELSE Display "You are not allowed to drive a car." ENDIF C Wilson, 2007 - 74 - Programming in Visual Basic Express Program Code Public Class Form1 'Can you drive? 'Visual Basic Express 'by Me 'June 07 Dim age As Integer Dim license_type As Integer Dim can_drive As String Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Top Level / Main Program setup() Top Level get_inputs() calculate_output() display_output() 1. Clear the screen and initialise variables End Sub Sub setup() can_drive = "no" ListBox1.Items.Clear() TextBox1.Clear() End Sub Sub get_inputs() 'validate age using a function age = validate_number(0, 100, "Enter your age") ListBox1.Items.Add("Age:" & vbTab & vbTab & age) 2. 3. 4. Get inputs Calculate entitlement to drive Display entitlement to drive Refinements 2.1 2.2 Prompt for, and validate, age Prompt for, and validate, current license type from menu 'validate license type (a number) using hand-typed code 'note: vbCR stands for 'carriage return' and means 'take a new line' license_type = InputBox("Enter a license type (1-3)" & vbCr & "1. None" & vbCr & "2. Provisional" & vbCr & "3. Full") While license_type < 1 Or license_type > 3 license_type = InputBox("Error! Enter a license type (1-3)" & vbCr & "1. None" & vbCr & "2. Provisional" & vbCr & "3. Full") End While ListBox1.Items.Add("License type:" & vbTab & license_type) End Sub 2.1.1 Obtain user input Function validate_number(ByVal min, ByVal max, ByVal message) 'from code library 2.1.2 WHILE number is not in range DO Dim number As Decimal number = InputBox("Please enter a number between " & min & " and " & max, message) While number < min Or number > max MsgBox("Please enter a number between " & min & " and " & max, , "Error!") number = InputBox("Please enter a number between " & min & " and " & max, message) End While Return number 2.1.3 Display error message End Function Sub calculate_output() 'if you have a full license you can drive... 'OR, if you are at least 17 AND have a provisional license you can drive If license_type = 3 Or (age >= 17 And license_type = 2) Then can_drive = "yes" End If End Sub Sub display_output() 'display program output in textbox If can_drive = "yes" Then TextBox1.Text = "You can drive a car." Else TextBox1.Text = "You are not allowed to drive a car." End If End Sub End Class C Wilson, 2007 4.1 4.2 4.3 4.4 4.5 2.1.4 2.1.5 3.1 3.2 3.3 Obtain user input ENDWHILE IF license type … set „can drive‟ to "yes" END IF IF „can drive‟ = "yes" THEN Display "You can drive a car." ELSE Display "You are not allowed to drive a car." ENDIF - 75 - Programming in Visual Basic Express Sample Runs Program Testing Normal Data Test Data Age = 17, license type =1 Age = 17, license type = 2 Age = 40, license type = 3 Expected Result Can‟t drive. Can drive. Can drive Actual Result As expected. As expected. As expected. Comment Program appears OK Program appears OK Program appears OK Limits Test Data Age = 0, license type =1 Age = 100, license type =3 Exceptions Test Data Age = -99 Age = 17.5 Age = Five License type = to kill License type = -99 C Wilson, 2007 Expected Result Can‟t drive. Can drive Actual Result As expected As expected Comment Program appears OK Program appears OK Expected Result Not Accepted Not Accepted Not Accepted Not accepted Not accepted Actual Result Not Accepted Accepted Not Accepted Not Accepted Not accepted Comment Program appears OK Program continues OK. Program crash Program crash Program continues OK. - 76 - Programming in Visual Basic Express COMPUTING PRACTICAL ABILITIES TASK STANDARD GRADE LANGUAGE COURSE a programming task assessing grades 1, 2, 3 and 7 Your teacher will outline how you should do this task and give you opportunities for discussion. Read and follow all instructions carefully, use hardware and software properly and write your report neatly using the headings given below. Students taking a language course must pass examinations in French and German or French and Spanish to pass. A pass is half marks or more. A program is required to take in the three marks which are validated as being whole numbers between 0 and 30. The output indicates if the student has passed or failed and gives the percentage mark to the nearest whole number. Examples of output are shown. The outputs from your program may look different but must meet the specification. C Wilson, 2007 - 77 - Programming in Visual Basic Express 1 DESCRIBE METHOD - Analysis 3 marks Show that you understand what is required by describing how you will do this task. 2 LIST STEPS - Design 6 marks Show the main steps and refinements. 3 ENTER PROGRAM - Implementation 5 marks Enter the program listing. Include internal commentary. Correct any mistakes that you make. Save the listing. 4 TEST PROGRAM - Testing 6 marks Describe in detail how you tested fully that your program – including input validation - worked as specified. 5 GET PRINTOUTS - Implementation 2 marks Get two printouts with your name in the footer. One should show your listing. The other printout should show a run using one of your sets of test data. It should demonstrate input validation and show accurate output. 6 CHANGE PROGRAM - Maintenance 2 marks Describe how you would change the program to make a pass in Italian an additional requirement to pass the course. 7 SUGGEST IMPROVEMENT - Evaluation 2 marks Suggest one way in which your program could be better apart from the maintenance given above. C Wilson, 2007 - 78 - Programming in Visual Basic Express Random numbers Many programs require the use of random data. For example, a game should be different every time you play it, otherwise it would become very boring. Generating random events or data is performed by programming the computer to calculate random numbers and then using these numbers to decide what happens next. In order to generate random numbers the programmer uses a pre-defined function to initialize a random number generator and then writes a line of code to produce a random number within an appropriate range. Example – throwing a dice In the real world, when we throw a dice we do not know what the outcome will be. All we do know is that the result will be a number between 1 and 6. Randomize() dice = Int(6 * Rnd() + 1) The code on the left could be used to simulate throwing a dice and will generate a random number between 1 and 6. The number generated will then be assigned to the variable named „dice‟. All that‟s missing is the code to display the number (variable name is dice How does it work? It is important to understand the above code in order to generate our own random numbers. Visual Basic programmers use the formula below: randomnum = int(highestno - lowestno+1) *rnd() + lowestno) Examples Range required 1 to 6 0 to 6 4 to 18 50 to 100 Code Number = Int(6 * Rnd() + 1) Number = Int(7 * Rnd() + 1) Number = Int(15 * Rnd() + 4) Number = Int(51 * Rnd() + 50) [Don‟t forget to use the Randomize() function before entering your code!] C Wilson, 2007 - 79 - Programming in Visual Basic Express Boolean variables So far we have covered the data types: Integer, Decimal and String. Another important data type is Boolean. Boolean variables hold only two possible values, True or False. They should have names that make it obvious what is meant when they are True or False. For example, ValidMark should be true if the mark is valid otherwise false, if the mark is invalid. Boolean variables are sometimes called Flags or Switches as they are either On (True) or Off (False). Example – “Are we there yet?” (The Simpsons) During a long car journey,…You know the one. This rather silly example illustrates the idea of testing for a condition and, when the condition is met, the boolean variable is allowed to change its value. In this case, a loop is allowed to terminate as a result of the change to the value of the Boolean variable. Design Set destination to false While destination is false do Ask “Are we there yet?” If answer is “yes” Set destination to true End if End while Display “Coooool!” Program Code Dim destination As Boolean = False Dim answer As Integer While destination = False 'loop while boolean variable has value 'false' answer = MsgBox("Are we there yet?", MsgBoxStyle.YesNo, "Message from Bart...") If answer = vbYes Then destination = True 'set boolean variable to 'true' - can now exit loop End If End While MsgBox("Coooool!", , "Message from Bart") Code it and see – you only require a single command button on your form! C Wilson, 2007 - 80 - Programming in Visual Basic Express Worked Example – Dice Game You have been asked to write a computer program to simulate a game of dice. To spice things up a little, the game will involve simulated money at stake. Players will start off with £100 to gamble. Once they have lost all their money they can no longer play. Players will throw two dice. Each time a player throws a double, they win £20, and this should be added to their „bank balance‟. If a player throws a double-six, they win £50! Method: The program will simulate throwing dice by repeatedly generating two random numbers between 1 and 6 inclusive. The two random numbers will be compared using an IF condition. If they are the same the player wins, and £20 pounds is added to their balance. Using a complex IF condition, the program will also test for a double six and add £50 pounds to the players balance if appropriate. The program will display meaningful messages at all times and update the players balance after every throw. The program must stop when the player’s balance reaches zero. Screen Design C Wilson, 2007 - 81 - Programming in Visual Basic Express Program Design Top Level 1. 2. 3. 4. 5. 6. 7. 8. 9. Display balance If player has money left (balance >0) , let them roll dice Set win to false Roll dice Note: only steps 4,5 and 6 Check result need to be refined. Display result Else Display “You‟re out of money!” End if Refinements 4.1 4.2 4.3 Generate random number for dice 1 Generate random number for dice 2 Display dice 1 and dice 2 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 5.10 If a double is rolled (dice 1 = dice 2) Set win to true If double is „double 6‟ Set balance = balance + £50 Else Set balance = balance + £20 End if Else Not a double, set balance = balance -10 End if 6.1 6.2 6.3 6.4 6.5 6.6 If win is true Display message “You win!” Else Display message “You lose.” End if Display updated balance in textbox1 C Wilson, 2007 - 82 - Programming in Visual Basic Express Program Code Public Class Form1 'Dice Game 'Visual Basic Express 'by Me 'June 07 Dim dice1 As Integer Dim dice2 As Integer Dim win As Boolean = False Dim balance As Decimal = 100 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'subroutine attached to loading form - will display balance when program starts TextBox1.Text = balance End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Top Level / Main Program If balance > 0 Then 'if player still has money, let them play win = False 'set winning throw to false roll_dice() check_result() display_result() Else 'no money left to gamble MsgBox("You're out of money!", MsgBoxStyle.Critical, “Dice Game”) End If End Sub Sub roll_dice() ' code for generating random num is... ' ...randomnum = int(highestno - lowestno+1) *rnd() + lowestno) Randomize() dice1 = Int(6 * Rnd() + 1) 'random number for dice 1 dice2 = Int(6 * Rnd() + 1) 'random number for dice 2 ListBox1.Items.Add(dice1 & " , " & dice2) 'display dice throw End Sub Sub check_result() If dice1 = dice2 Then win = True If dice1 And dice2 = 6 Then balance = balance + 50 Else balance = balance + 20 End If Else win = False balance = balance – 10 End If End Sub 'a winning throw 'set winning throw to true 'with a double six! 'wins £50 'just any other double, wins £20 'a losing throw 'lose £10 Sub display_result() If win = True Then ListBox1.Items.Add("You win!") Else ListBox1.Items.Add("You lose.") End If TextBox1.Text = balance End Sub End Class C Wilson, 2007 'update balance on screen - 83 - Programming in Visual Basic Express Sample Runs C Wilson, 2007 - 84 - Programming in Visual Basic Express COMPUTING PRACTICAL ABILITIES TASK STANDARD GRADE GUESS NUMBER a programming task assessing grades 1, 2, 3 and 7 Your teacher will outline how you should do this task and give you opportunities for discussion. Read and follow all instructions carefully, use hardware and software properly and write your report neatly using the headings given below. A program is required to prompt the user to guess a randomly-chosen whole number between 1 and 20. The input should be validated. If the guess is incorrect, the user should be told if the target number is bigger or smaller. This process should continue until the target number is guessed correctly. The user should then be told how many valid guesses were made. An example of output is shown below. The output from your program may look different but must meet the specification. C Wilson, 2007 - 85 - Programming in Visual Basic Express 1 DESCRIBE METHOD - Analysis 3 marks Show that you understand what is required by describing how you will do this task. 2 LIST STEPS - Design 6 marks Show the main steps and refinements. 3 ENTER PROGRAM - Implementation 5 marks Enter the program listing. Include internal commentary. Correct any mistakes that you make. Save the listing. 4 TEST PROGRAM - Testing 6 marks Describe in detail how you tested fully that your program – including input validation - worked as specified. 5 GET PRINTOUTS - Implementation 2 marks Get two printouts with your name in the footer. One should show your listing. The other printout should show a run using one of your sets of test data. It should demonstrate input validation and show accurate output. 6 WRITE TECHNICAL GUIDE - Documentation 3 marks Write a short technical guide that describes how to install the programming language that you used and the system requirements. 7 CHANGE PROGRAM - Maintenance 3 marks Describe how you would change the program to make it count the total number of guesses and not just the valid ones. 8 SUGGEST IMPROVEMENT - Evaluation 2 marks Suggest one way in which your program could be better apart from the maintenance given above. Your mark for this task will be used by the Scottish Qualifications Authority in deciding your overall award. C Wilson, 2007 - 86 - Programming in Visual Basic Express Arrays Imagine you have been asked to write a program that will allow the user to enter a list of the names of five people and then display these names on the screen. Here is the sort of program you might write. DO NOT TYPE THIS IN!!! Public Class Form1 '5 Names without an array 'Visual Basic Express 'by Me 'June 07 Dim name1 As String Dim name2 As String Dim name3 As String Dim name4 As String Dim name5 As String Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Top Level / Main Program get_names() display_names() End Sub Sub get_names() name1 = InputBox("Type in name 1 ") name2 = InputBox("Type in name 2 ") name3 = InputBox("Type in name 3 ") name4 = InputBox("Type in name 4 ") name5 = InputBox("Type in name 5 ") End Sub Sub display_names() ListBox1.Items.Add(name1) ListBox1.Items.Add(name2) ListBox1.Items.Add(name3) ListBox1.Items.Add(name4) ListBox1.Items.Add(name5) End Sub End Class Imagine changing this program to deal with 250 names, or even over a million names! There is an easier way to write this kind of program involving the use of „arrays‟ rather than simple „variables‟. C Wilson, 2007 - 87 - Programming in Visual Basic Express Remember we said earlier, that variables were just boxes in the computers memory. Inside these boxes we can store a single item of data or information. Image if we could store more than one item of data inside a variable… To make things a little clearer… In the previous example we know we are storing names. We know we are storing five names. These five items of data are very similar in nature, so it‟s like storing a list of data. Why on earth then, should we waste time creating 5 very similar variables (or 250, or over a million similar items of data)? The idea of storing a „list‟ of data, rather than using several individual variables, is what is known as an „array‟. Using an array, we can still access each individual item of data on the list if we need to. Each individual item in the array has its own position, or location on the list. Comparison of separate variables with an array… Using individual variables… Using an array… Dim name1 As String Name1 Homer Dim name2 As String Name2 Marge Dim name3 As String Name3 Bart Dim firstname(5) As String 1 2 3 4 5 Homer Marge Bart Lisa Maggie This is the name of the array in memory. This is the data stored in location firstname(4) Dim name4 As String Name4 Lisa Dim name5 As String Name5 Maggie This is the element number or location for each item of data in the name array. In order to use special array variables like this we have to learn some new commands… C Wilson, 2007 - 88 - Programming in Visual Basic Express Arrays – Typical examples of code used Create an array. The code required to create the array could be something like this2. Dim firstname(5) As String Note: we specify the name of the array, its size, and its data type. 1 Homer 2 Marge 3 Bart 4 Lisa 5 Maggie Store a single item of data. The code required to store „Bart‟ in element number 3 is firstname(3) = "bart" Display a single item of data. The code required to display the contents of element number 4 could be ListBox1.Items.Add(Firstname(4)) Get the idea? Now look at this… Display the entire array. The code required to display the entire list of all names can be easily written using a FOR loop as follows. Dim row As Integer For row = 1 To 5 ListBox1.Items.Add(firstname(row)) Next This code would be just as simple with a list of a million names! Store a list of user data. Rather than have all the names entered by the programmer when writing the code, we can also use a FOR loop to allow the user to enter their own names into the array. Dim person As Integer For person = 1 To 5 firstname(person) = InputBox("Enter a name", "Address Book") Next Prompt for, and display a single item of data. We can even retrieve individual items of information. Dim element As Integer element = InputBox("Enter a number between 1 and 5", "Address Book") MsgBox("You picked " & firstname(element)) 2 VB Express uses ‘zero-indexing’ and so will actually create 6 elements – the extra being firstname(0). We will ignore this element at this level. C Wilson, 2007 - 89 - Programming in Visual Basic Express Task Design the form shown and then enter the program code below. NOTE: Be careful when entering your code. Each command button calls only one subroutine. i.e. There are four command buttons – each one calls its own subroutine code below. Experiment by running the program several times and make sure you fully understand its workings before moving on. Public Class Form1 'Address Book using arrays 'Visual Basic Express 'by Me 'June 07 Dim firstname(5) As String Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Code to automatically enter 5 items of data defined by the programmer into the firstname array ListBox1.Items.Clear() firstname(1) = "homer" firstname(2) = "marge" firstname(3) = "bart" firstname(4) = "lisa" firstname(5) = "maggie" End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click 'Code to allow the program user to enter ANY 5 items of data for storage in the firstname array ListBox1.Items.Clear() Dim person As Integer For person = 1 To 5 firstname(person) = InputBox("Enter a firstname", "Address Book") Next End Sub Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click 'It doesn't matter how the data was stored in the array. 'This code will display whatever data has been most recently stored in the five elements. Dim row As Integer For row = 1 To 5 ListBox1.Items.Add(firstname(row)) Next End Sub Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click 'Allow the user to query the array Dim element As Integer element = InputBox("Enter a number between 1 and 5", "Address Book") MsgBox("You picked " & firstname(element)) End Sub End Class C Wilson, 2007 - 90 - Programming in Visual Basic Express Worked Example - Golden Ticket Willy Wonka and his chocolate factory have fallen on hard times. His chocolate is just not as popular as it used to be. Remembering the success of his earlier promotional event involving an international hunt for five „golden tickets‟, he is now hoping to repeat this success. This time he is desperate enough to offer many more golden tickets than before. In fact, he is considering hiding one in every fifty Wonka Bars produced, each at a reduced sale price of 49 pence. Out of curiosity, he has asked you to write a program that will simulate the purchase of Wonka Bars where one in every fifty bars could be a winner with a golden ticket inside. Method: The program will prompt the user to continue to buy as many Wonka Bars as he/she wishes, so a while loop will be required. We will keep a running total/count of three things: The amount of money spent on Wonka Bars (at 49p each) The number of bars bought in our search for a golden ticket The number of golden tickets found Since, on average, one in every fifty bars will be a winner, we will use an array (with fifty elements) to simulate each batch of fifty Wonka Bars produced. We will set each element of this array to be ‘no win’. Following this, we will select one element of this array at random, and change its element from ‘no win’ to ‘golden ticket’. Next, we allow the user to buy a Wonka Bar. Every time the user buys a Wonka Bar another random number will be generated (between one and fifty). If this number is the same as the Wonka Bar golden ticket number, the user is a winner. Each time the user purchases a Wonka Bar the running totals/counts must be updated. The user should also be informed whether or not they are a winner each time they buy a Wonka Bar. C Wilson, 2007 - 91 - Programming in Visual Basic Express Program Design 1. 2. 3. 4. 5. 6. 7. Initialise counters and total variables While user wishes to buy more chocolate Hide Golden Ticket Buy Chocolate Update Summary As if user would like to buy more chocolate End While Hide Golden Ticket 3.1 3.2 3.3 3.4 3.5 For chocolate_bar = 1 To 50 Set all elements of ticket array to “no win” Next Select random number between 1 and 50 inclusive as winner Set ticket array (winner) as "Golden Ticket!" Buy Chocolate 4.1 4.2 4.3 Select random number between 1 and 50 inclusive as purchased bar of chocolate Set amount_spent to amount_spent + price Set bars_bought to bars_bought + 1 Update Summary 5.1 5.2 5.3 If random bar purchased equals random winner Set golden_tickets to golden_tickets + 1 Display „congratulations‟ message and summary of bars bought and amount spent. 5.4 5.5 Else 5.6 End If 5.7 5.8 5.9 Display amount spent in textbox Display no. of bars bought in textbox Display no. of golden tickets in textbox Display „sorry‟ message and summary of bars bought and amount spent. C Wilson, 2007 - 92 - Programming in Visual Basic Express Program Code Public Class Form1 Dim ticket(50) As String Dim winner As Integer Dim bar_purchased As Integer Dim amount_spent As Decimal Dim bars_bought As Integer Dim golden_tickets As Integer Public Const price As Decimal = 0.49 Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Top Level / Main Program setup() 1. Set up counters and total variables Dim response As Integer 2. While user wishes to buy more chocolate While response <> vbNo 3. Hide Golden Ticket hide_golden_ticket() 4. Buy Chocolate buy_chocolate() update_summary() 5. Update Summary response = MsgBox("Would you like to buy more?", MsgBoxStyle.YesNo, "Buy Chocloate?") End While 6. As if user would like to buy more chocolate End Sub 7. End While Sub setup() amount_spent = 0 bars_bought = 0 golden_tickets = 0 End Sub Sub hide_golden_ticket() 'there should be no guarantee that buying 50 bars will get a golden ticket 'so every time a bar is purchased, the winning ticket moves position in array 'Nasty! 'Set all bars to no win... Dim chocolate_bar As Integer For chocolate_bar = 1 To 50 ticket(chocolate_bar) = "No win." Next Hide Golden Ticket 3.1 3.2 3.3 3.4 3.5 For chocolate_bar = 1 To 50 Set all elements of ticket array to “no win” Next Select random number between 1 and 50 inclusive as winner Set ticket array (winner) as "Golden Ticket!" 'then set a random ticket element to golden ticket! Randomize() winner = Int(50 * Rnd()) + 1 ticket(winner) = "Golden Ticket!" End Sub Buy Chocolate Sub buy_chocolate() 'pick a bar of chocolate at random (from the sweety shop counter) Randomize() bar_purchased = Int(50 * Rnd()) + 1 amount_spent = amount_spent + price bars_bought = bars_bought + 1 End Sub 4.1 4.2 4.3 Select random number between 1 and 50 inclusive as purchased bar of chocolate Set amount_spent to amount_spent + price Set bars_bought to bars_bought + 1 Sub update_summary() Update Summary 'open the bar of chocolate...Is there a golden ticket? 'if the random number for the golden ticket = random number for the chocolate bar purchased... 5.1 If random bar purchased equals random winner If bar_purchased = winner Then 5.2 Set golden_tickets to golden_tickets + 1 golden_tickets = golden_tickets + 1 RichTextBox1.Text = "Congratulations. You have won a golden ticket!!! Willie Wonka looks forward to seeing you (and one family member), at the Chocolate Factory soon. You have purchased " & bars_bought & " bars of chocolate, spending £ " & amount_spent & ". We hope you enjoy your visit!" 5.3 Display „congratulations‟ message and summary of bars bought and amount spent. Else 'if the random number for the golden ticket is different to the current random number for golden ticket... RichTextBox1.Text = "Sorry. No golden ticket this time!!! Willie Wonka looks forward to seeing you, if only you would buy more chocolate and find a golden ticket. You have purchased " & bars_bought & " bars of chocolate, spending £ " & amount_spent & ". We hope you're enjoying your chocolate!" End If 'update summary details TextBox1.Text = "£ " & amount_spent TextBox2.Text = bars_bought TextBox3.Text = golden_tickets End Sub End Class C Wilson, 2007 5.4 5.5 Else 5.6 End If 5.7 5.8 5.9 Display amount spent in textbox Display no. of bars bought in textbox Display no. of golden tickets in textbox Display „sorry‟ message and summary of bars bought and amount spent. - 93 - Programming in Visual Basic Express Sample Runs C Wilson, 2007 - 94 - Programming in Visual Basic Express COMPUTING STANDARD GRADE PRACTICAL ABILITIES TASK CHARITY LOTTERY a programming task assessing grades 1, 2, 3 and 7 Your teacher will outline how you should do this task and give you opportunities for discussion. Read and follow all instructions carefully, use hardware and software properly and write your report neatly using the headings given below. A group of twelve office workers decides to have a weekly charity lottery. Each worker is asked to contribute £1 and a draw is made. The winner gets half of the contributions with the other half going to charity. If the person selected has not paid that week, all contributions go to charity. You are required to write a program that selects a winner from a set of workers’ names read from data statements and held in an array. The user is asked if the selected person has paid that week. The input should be validated. An appropriate message is given. Examples of output are shown. The outputs from your program may look different but must meet the specification. C Wilson, 2007 - 95 - Programming in Visual Basic Express 1 DESCRIBE METHOD - Analysis 3 marks Show that you understand what is required by describing how you will do this task. 2 LIST STEPS - Design 6 marks Show the main steps and refinements. 3 ENTER PROGRAM - Implementation 5 marks Enter the program listing. Include internal commentary. Correct any mistakes that you make. Save the listing. 4 TEST PROGRAM - Testing 6 marks Describe in detail how you tested fully that your program – including input validation - worked as specified. 5 GET PRINTOUTS - Implementation 2 marks Get two printouts with your name in the footer. One should show your listing. The other printout should show a run using one of your sets of test data. It should demonstrate input validation and show accurate output. 6 CHANGE PROGRAM - Maintenance 3 marks Describe how you would change the program to make it ask if each worker had contributed before the draw was made. 7 SUGGEST IMPROVEMENT - Evaluation 2 marks Suggest one way in which your program could be better apart from the maintenance given above. Your mark for this task will be used by the Scottish Qualifications Authority in deciding your overall award. C Wilson, 2007 - 96 - Programming in Visual Basic Express Checklist Well, we‟re just about done. Here‟s your final checklist… User Interface No new skills Program Code Complex conditions – AND/OR WHILE loop Input validation Pre-defined functions User defined functions Generating random numbers Boolean variables Arrays – create, store single item, display single item, display entire array, store list in array Evaluation Program testing – normal data, limits, exceptions Now, just for fun… some maths! Design and write a program which will be useful for a Primary school to assist young children in learning arithmetic. The program should allow pupils to enter answers to 10 different addition sums. Only two numbers will require to be added in each sum, the two numbers being chosen at random and not being greater than 10. The program should indicate whether the pupil‟s answers are correct or not and on completion a summary of the number of correct answers should be given. C Wilson, 2007 - 97 -