Presentation is loading. Please wait.

Presentation is loading. Please wait.

20/10/20151 3.1 Working with Data Declaring Variables, Overflow.

Similar presentations


Presentation on theme: "20/10/20151 3.1 Working with Data Declaring Variables, Overflow."— Presentation transcript:

1 20/10/20151 3.1 Working with Data Declaring Variables, Overflow

2 220/10/2015 Learning Objectives Explain what a variable is and what they are used for. Explain how to declare variables and explain the necessity for doing so. Explain why using comments is useful, how to enter them and what VB does with them. Explain the Overflow error.

3 320/10/2015 Variables When a program runs, any data that it uses is stored in RAM. A variable is a name made up by the programmer to identify the address in RAM where a particular piece of data is stored. Our programs so far have managed to avoid using variables but this restricts what can be done.

4 420/10/2015 Variables / Identifiers e.g. lblInput.Text = txtNumber.Text Makes the label lblInput display whatever the user has typed into the textbox txtNumber. But to store what is in the textbox and use what is stored after the user has typed something else into the textbox, we would need a variable.

5 520/10/2015 Conventions for Naming Variables Always use meaningful names / identifiers. You cannot use spaces. Best to follow the convention of making each word start with a capital e.g. DateOfPayment Using the first capital will also help differentiate variable names / identifiers from control names.

6 620/10/2015 Data Types Main Data Types Data Types Range / Fractional Real Precision Storage Requirements (bytes) Text (Characters) / String in VB Any characters 1 per character Char Any character 1 byte Integer (Numeric, Whole numbers, no fractions) Byte 0 - 255 1 Integer In Access stored by 2 bytes so +/- 32,768. In VB stored by 4 bytes so approx. +/- 2 billion 2 - 4 Long (Integer) In Access stored by 4 bytes so approx. +/- 2 billion. In VB stored by 8 bytes so approx. +/– 9.2...E+18. 4 – 8 Floating Point (Fractional Real Numbers) Single7 4 Double15 8 Decimal28 12 Boolean (Y/N True/False) Often 1 byte is reserved Date/Time 8

7 720/10/2015 Summary of Data Types Storage Requirements Data Type Storage Requirements (bytes) Text 1 byte per character Char 1 byte Byte 0 – 255 1 byte Integer > 255 4 bytes Decimal 8 bytes Boolean (True/False – Yes/No – 2 answers only) 1 byte Date / Time 8 bytes Note: Use this summary in exam questions. The previous slide is for general interest only.

8 820/10/2015 Dim Use this statement to declare variables. Dim (Variable name) As (Data Type) e.g. Dim MyName As Text Dim MyName As Text Dim Number As Integer Dim Number As Integer Dim Payment As Decimal Dim Payment As Decimal Dim DataOfPayment As Date Dim DataOfPayment As Date Dim Paid As Boolean Dim Paid As Boolean Boolean = True or False Dim InsuranceRating As Char Dim InsuranceRating As Char Char = One letter only (e.g. A, B or C only).

9 920/10/2015 Words that cannot be used as identifiers Experiment using different words as identifiers: e.g. e.g. Total Price Of Order Must not contain any spaces. Must not contain any spaces.Total:Price Must not contain punctuation characters. Must not contain punctuation characters.Sum&Price Must not contain certain special symbols. Must not contain certain special symbols.5Totals Names must begin with a letter. Names must begin with a letter.Date Names can’t be keywords or reserved words which are words special to the language and have defined meanings for that language. Names can’t be keywords or reserved words which are words special to the language and have defined meanings for that language. e.g. Dim Date As Date cannot be used the word Date is a data type and already has meaning.

10 1020/10/2015 Declaring Variables Means to tell Visual Basic two things about a variable: Its name or identifier. Its name or identifier. Its data type. Its data type.

11 Working with variables Imagine 3 people: Mr User Ms Programmer Ms Processor (CPU) Ms Programmer and Ms CPU communicate in the Visual Basic programming language (which I will show by underlining). Ms Programmer designs a form with some text boxes for Mr User to fill in and a button for Mr User to click when he has finished. Mr User fills out the form and clicks the button. See next slide.

12 1220/10/2015 Name: txtFirstNumber Name: txtSecondNumber Name: lblTotal Name: butEnter 3 2 3 2

13 Ms Programmer then instructs Ms CPU “Get ready! Later you will either be given an integer or asked to calculate an integer and I want you to call it FirstNumber.”. Ms CPU will now find an empty place (box) in her memory (RAM), reserve it and name it FirstNumber. Dim FirstNumber As Integer Similarly: Dim SecondNumber As Integer Dim Total As Integer Working with variables Do NOT confuse the word “box” here with a text box. The word “box” here refers to a “space” or “box” in memory (RAM), which is not visible to a user.

14 Working with variables The details entered into the form by the user are the “text” entered into the text boxes on the form. Ms Programmer then instructs Ms CPU to “Store (copy) the number in the first text box on the form Mr User filled in, in the box you reserved earlier in your memory called FirstNumber.”. FirstNumber = txtFirstNumber.Text Similarly for: SecondNumber = txtSecondumber.Text

15 Working with variables Ms Programmer then instructs Ms CPU to “Calculate the addition of what you have stored in the boxes in your memory called FirstNumber and SecondNumber, and store the answer in the box you reserved earlier in your memory called Total.”. Total = FirstNumber + SecondNumber

16 Working with variables Ms Programmer then instructs Ms CPU to “Display (show) the total in the text of the total label so that Mr User can see it.”. lblTotal.Text = Total 3 2 5

17 1720/10/2015 Standard Code for a Program using Variables Declare your variables (one for each data entered and one for a result) : Dim VariableNameToStore1 As (DataType) Dim VariableNameToStore1 As (DataType) Dim VariableNameToStore2 As (DataType) Dim VariableNameToStore2 As (DataType) … Dim VariableNameToDisplay As (DataType) Dim VariableNameToDisplay As (DataType) Store data enter by a user in a text box: VariableNameToStore1 = txt(ControlName).Text VariableNameToStore1 = txt(ControlName).Text VariableNameToStore2 = txt(ControlName).Text VariableNameToStore2 = txt(ControlName).Text …Formulae: … VariableNameToDisplay = VariableNameToStore1 +-*/ VariableNameToStore2 VariableNameToDisplay = VariableNameToStore1 +-*/ VariableNameToStore2Display: lbl(ControlName).Text = VariableNameToDisplay lbl(ControlName).Text = VariableNameToDisplay

18 1820/10/2015 Code Comments As programs become more complicated it is useful to be able to write explanations of the logic of each line of code but obviously we want VB to ignore them. This is achieved by using apostrophes ‘. All programs from now on must contain comments.

19 1920/10/2015 Program 3.1 Add two numbers Specification: Allow the user to enter two numbers and display the sum. Allow the user to enter two numbers and display the sum.

20 2020/10/2015 Program 3.1 Add two numbers Create a new project named ‘Add two numbers’. Change the form’s Text property to ‘Add two numbers’.

21 2120/10/2015 Name: txtFirstNumber Name: txtSecondNumber Name: lblTotal Name: butEnter

22 2220/10/2015 Program 3.1 Add two numbers Double click butEnter and enter the following code in the butEnter’s code proceduretemplate. Double click butEnter and enter the following code in the butEnter’s code procedure template. FirstNumber = txtFirstNumber.Text FirstNumber = txtFirstNumber.Text SecondNumber = txtSecondNumber.Text SecondNumber = txtSecondNumber.Text Press enter or click into another line so VB can check your code. Note that there will be errors (blue squiggly lines), please move onto the next slide for an explanation.

23 2320/10/2015 Program 3.1 Add two numbers You will get a blue squiggly line underneath the variable name FirstNumber. Hover over this and you will get a message saying ‘Name ‘FirstNumber’ is not declared’. Why? The variable has not been declared! The variable has not been declared! Delete the lines of code you entered previously.

24 2420/10/2015 Program 3.1 Add two numbers Now enter the following code Dim FirstNumber As Integer ‘Declares a variable for the 1 st number. Dim FirstNumber As Integer ‘Declares a variable for the 1 st number. Dim SecondNumber As Integer ‘Declares a variable for the 2 nd number. Dim SecondNumber As Integer ‘Declares a variable for the 2 nd number. Dim Total As Integer ‘Declares a variable for the sum of the 2 numbers. Dim Total As Integer ‘Declares a variable for the sum of the 2 numbers. Press enter or click into another line so VB can check your code.

25 2520/10/2015 Program 3.1 Add two numbers You will get a green squiggly line underneath the variable name FirstNumber. Hover over this and you will get a message saying ‘Unused local variable: ‘FirstName’’. Why? VB is simply trying to help by informing you that you have declared a variable but have not used it in your code yet. VB is simply trying to help by informing you that you have declared a variable but have not used it in your code yet.

26 2620/10/2015 Program 3.1 Add two numbers Enter the following code after the declarations you have already: ‘Stores the number entered into the First Number text box into the variable FirstNumber. ‘Stores the number entered into the First Number text box into the variable FirstNumber. FirstNumber = txtFirstNumber.Text FirstNumber = txtFirstNumber.Text ‘Stores the number entered into the Second Number text box into the variable SecondNumber. ‘Stores the number entered into the Second Number text box into the variable SecondNumber. SecondNumber = txtSecondNumber.Text SecondNumber = txtSecondNumber.Text ‘Calculate the total. ‘Calculate the total. Total = FirstNumber + SecondNumber Total = FirstNumber + SecondNumber ‘Display the total. ‘Display the total. lblTotal.Text = Total lblTotal.Text = Total

27 2720/10/2015 Program 3.1 Add two numbers Run and test the program. If and when working OK publish the program.

28 2820/10/2015 FirstNumber = txtFirstNumber.Text In programming “=”, in this case, is an arithmetical operator meaning to assign. It does not mean “it is equal” it means “make it equal”. It does not mean “it is equal” it means “make it equal”. Left Side -> Right Side

29 2920/10/2015 Implicit Variable Use You do not actually have to explicitly declare variables, you can implicitly declare variables by simply using them in your code. However, it is good programming practice and efficient to do so as certain errors/problems can occur if you don’t: Naming-conflict errors – using a variable name/identifier which VB already uses for its own purposes. Naming-conflict errors – using a variable name/identifier which VB already uses for its own purposes. Spelling mistakes – spelling a variable name/identifier one way the first time you use it and then accidentally spelling another way later in the code. Spelling mistakes – spelling a variable name/identifier one way the first time you use it and then accidentally spelling another way later in the code. VB assigns the Object data type if the data type of a variable is not declared – this is slower to access and uses more memory. VB assigns the Object data type if the data type of a variable is not declared – this is slower to access and uses more memory.

30 3020/10/2015 Option Explicit On - VB looks for undeclared variables as you type in the code (so forcing you to do so). Off – VB does not look for undeclared variables as you type in the code but runtime errors may occur (as described on the previous slide). It is On by default, you can check it is on by: 1. On the Tools menu, choose Options. 2. Open the Projects and Solutions node. 3. Choose VB Defaults.

31 3120/10/2015 Overflow Run the program and try entering the number 3000000000 You will get an Overflow error. This is caused by the variable being asked to hold a number outside its Data Type’s range. Have a look at the table on slide 7.

32 Alpha Testing Performed by the programmers involved in writing the program. Focus on error free processing.

33 33 Logic errors A mistake in the way the program solution has been designed. e.g. e.g. If you had written Total = FirstNumber - SecondNumber Total = FirstNumber - SecondNumber instead of Total = FirstNumber + SecondNumber Total = FirstNumber + SecondNumber In the previous program. These errors will not stop your program running, it just would not work correctly and produce “unexpected results”. So do not assume that if a program does not crash that this means it works. You must test your programs by thinking of data, working out what should happen, entering this data and seeing if it does. This is called Black Box Testing.

34 Black box testing Use of different input values to determine whether the program gives you expected results (compare actual results with expected ones) and can cope with them without crashing. These values should include These values should include Different types of input e.g. Typical values Typical values Borderline values Borderline values Unacceptable values Unacceptable values Cannot see into the box (program) all you see is what comes out at the end.

35 Example 1 of Black Box Testing A program which uses marks out of 100 from a math's examination as input. Normal data like: 27, 73.., Normal data like: 27, 73.., Borderline data: 0 and 100 Borderline data: 0 and 100 Invalid data like: –34, 123, 16.345 Invalid data like: –34, 123, 16.345 Note that you should try one piece of invalid data at a time otherwise, if there is an error or problem, you will not be able to tell which piece of invalid data is causing the problem (one, more than one or all). For example using -16.445 means that, if there was an error, you would not know if it was because you used a negative (-) number or because you used a decimal (real) number. For example using -16.445 means that, if there was an error, you would not know if it was because you used a negative (-) number or because you used a decimal (real) number. You should use -16 and then 16.445 (in any order) first, if there are no errors, then you could try -16.445. You should use -16 and then 16.445 (in any order) first, if there are no errors, then you could try -16.445.

36 Example 2 of Black Box Testing A program to work out the mean of three numbers. 1, 2, 3 Will integers give an integer answer? 1, 2, 3 Will integers give an integer answer? 1, 2, 4 Can the software cope with a recurring decimal answer? 1, 2, 4 Can the software cope with a recurring decimal answer? (Note that “1, 2, 4 to test a different set of integers” would not get a mark because the reason for the test is not different) 1, 2.5, 3 Can the program handle decimal inputs? 1, 2.5, 3 Can the program handle decimal inputs? 1, 2½, 3 Are fractions allowed? 1, 2½, 3 Are fractions allowed? -1, -2, -3 Can negative numbers be handled? -1, -2, -3 Can negative numbers be handled? 1, 2 What happens when only two values are input? 1, 2 What happens when only two values are input?

37 3720/10/2015 Debugging Tools Debugging tools to allow programmers to investigate conditions where errors occur. The following slides describe some debugging tools.

38 3820/10/2015 Traces / Variable Watch A trace is where the program is run and the values of all the relevant variables are printed out, as are the individual instructions, as each instruction is executed. In this way, the values can be checked to see where they suddenly change or take on an unexpected value. For how to do this in VB - see next two slides.

39 3920/10/2015 Switch over to see the your code. Press F8 to ”step into” or run the program line by line. Basically press F8 repeatedly to run each line, the “next line” to be executed or run is highlighted in yellow. In the program in this presentation you will need to enter numbers and click the “Enter” button to get things started. In the program in this presentation you will need to enter numbers and click the “Enter” button to get things started. Note the highlighted line is next it does NOT mean the line just run (that would be the previous line). Note the highlighted line is next it does NOT mean the line just run (that would be the previous line). Traces / Variable Watch F8

40 4020/10/2015 Traces / Variable Watch OR 1.Just point to each variable to see its value. Then press F8 repeatedly to execute each line and watch the values of the variables change (as each line is run. 1.Debug menu – Windows – Watch. 2.Right click all variables and click Add Watch.

41 4120/10/2015 Break Points / Variable dumps Note that the program will not run the line you choose until you press F8, so ideally you should choose the line after the actual line you are interested in. You can also press F8 as before to run the program line by line from this break point. At specified parts of the program, the values of all the variables are displayed to enable the user to compare them with the expected results. This enables the programmer to see where sudden, unexpected changes occur. To do this in VB click the line/s (in the grey column on the left) you wish the program to stop on (the break point/s) and then look at the values of each variable as in Variable Watch (see previous slides).

42 4220/10/2015 White Box Testing / Dry Runs / Desk Checking The user works through every logical path of the program instructions manually, keeping track of the values of the variables. Basically manual tracing or variable watches. Basically manual tracing or variable watches. Most computer programs require a very large number of instructions to be carried out, so it is usual to only dry run small segments of code that the programmer suspects of harboring an error. Testing knowing the code. Testing the structure and logic of all the algorithms within the code. Known as “white box” as testing is done by looking at the code so the program is like a transparent box. Known as “white box” as testing is done by looking at the code so the program is like a transparent box. This is basically another way to check for “unexpected results” or logical errors.

43 4320/10/2015 Cross-referencing This software checks the program that has been written and finds places where particular variables have been used. This lets the programmer check to make sure that the same variable has not been used twice for different things. In VB use Ctrl+F.

44 4420/10/2015 Debugging Tools Use these debugging tools, on any program in the future, when you need to find out where errors are and what is causing them.

45 4520/10/2015 Advice for writing programs 1.Insert a number of textboxes and labels into your form. One textbox for each piece of information to be entered and a description label. One textbox for each piece of information to be entered and a description label. One label for each result. One label for each result. 2.Declare your variables (one for each data entered and one for a result) : Dim VariableNameToStore1 As (DataType) Dim VariableNameToStore1 As (DataType) Dim VariableNameToStore2 As (DataType) Dim VariableNameToStore2 As (DataType) … Dim VariableNameToDisplay As (DataType) Dim VariableNameToDisplay As (DataType) 3.Store data enter by a user in a text box: VariableNameToStore1 = txt(ControlName).Text VariableNameToStore1 = txt(ControlName).Text VariableNameToStore2 = txt(ControlName).Text VariableNameToStore2 = txt(ControlName).Text … 4.Formulae: … VariableNameToDisplay = VariableNameToStore1 +-*/ VariableNameToStore2 VariableNameToDisplay = VariableNameToStore1 +-*/ VariableNameToStore2 5.Display: lbl(ControlName).Text = VariableNameToDisplay lbl(ControlName).Text = VariableNameToDisplay

46 Summary of advice for writing programs 1.Declare your variables (the number of text boxes + 1 for the result). 2.Store (the contents of each text box into the appropriate variables). 3.Calculate (Result = …. +-/* etc..). 4.Display (lblName.Text = Result). 4620/10/2015

47 4720/10/2015 Extension Programs Change the program to add three numbers. Someone to enter an original price and a percentage discount. The program should display how much they should actually pay. A seller to enter a cost price and a required percentage profit. The program should display the selling price required. Extension: Include VAT of 17.5%. Extension: Include VAT of 17.5%. Someone to enter an amount of money placed in a high interest account and a number of years to leave it there. The program should display how much money they will receive after that time (10% per year). Write a program for a motorist who wishes to work out how many kilometres per litre their car is doing. Someone to enter their income, personal allowance and tax rate. The program should display how much tax they should pay. Someone to enter the number of hours worked, normal rate per hour, number of hours overtime (assume overtime rate is double normal rate). The program should display their salary.

48 4820/10/2015 Plenary Explain what a variable is and what they are used for. A variable is a name made up by the programmer to identify the address in RAM where a particular piece of data is stored. A variable is a name made up by the programmer to identify the address in RAM where a particular piece of data is stored. To store data for later use. To store data for later use.

49 4920/10/2015 Plenary Explain why using comments is useful, how to enter them and what VB does with them. They explain the logic of the code both to programmer to help writing and debugging and to any reader of the code. They explain the logic of the code both to programmer to help writing and debugging and to any reader of the code. Use ‘ at the end of a line before a comment. Use ‘ at the end of a line before a comment. Comments are ignored by VB. Comments are ignored by VB.

50 5020/10/2015 Plenary Explain how to declare variables and explain the necessity for doing so. Dim (Variable name) As (Data Type) Dim (Variable name) As (Data Type) If you do not declare variables VB will not what know what to do with a name it does not recognise and runtime errors will occur. If you do not declare variables VB will not what know what to do with a name it does not recognise and runtime errors will occur. Explain the Overflow error. This is caused by the variable being asked to hold a number outside its Data Type’s range. This is caused by the variable being asked to hold a number outside its Data Type’s range.


Download ppt "20/10/20151 3.1 Working with Data Declaring Variables, Overflow."

Similar presentations


Ads by Google