Title: 157212 Week 2 Lecture 1
1157212 Week 2 Lecture 1
- Hardware
- Visualisations
- Cards
- VB Syntax
- We may not finish all this, if not we will
overflow to tomorrow
2Hardware
- How much/what do we need to know about hardware?
- Dynamic memory (RAM)
- Lost on close
- Used for all our exercises
- Bits and Bytes
- CS-type knowledge
- Not needed for us at this level
3Visualisations
- Different ways to visualise an application
- Diagramatically
- Pseudocode
- Code
- Or, most often, a combination
4Reaction time - Rethink
Exit or cancel?
Get the user ready?
Instructions?
Your reaction time is 0.29s
Architecture?
Language?
Eliminate navigation?
5What is pseudocode?
- Pseudocode consists of short, English phrases
used to explain specific tasks within a program's
algorithm. - Pseudocode should not include keywords in any
specific computer languages. It should be written
as a list of consecutive phrases. - You should not use flowcharting symbols but you
can draw arrows to show looping processes. - Indentation can be used to show the logic in
pseudocode as well. - One programmer should be able to take another
programmer's pseudocode and generate a program
based on that pseudocode.
6Why is pseudocode useful?
- The programming process is a complicated one.
- You must first understand the program
specifications, then you need to organise your
thoughts and create the program. - This is a difficult task when the program is
non-trivial. - You must break the main tasks that must be
accomplished into smaller ones in order to be
able to eventually write fully developed code. - Writing pseudocode WILL save you time later
during the construction testing phase of a
program's development - Do Not just jump onto the PC and start to code
think first!
7How do I write pseudocode?
- First, you may want to make a list of the main
tasks that must be accomplished on a piece of
paper. - Then, focus on each of those tasks. Generally,
you should try to break each main task down into
very small tasks that can each be explained with
a short phrase. - There may eventually be a one-to-one correlation
between the lines of pseudocode and the lines of
the actual VB code that you write after you have
finished pseudocoding.
8Pseudocode Example
- Original Program Specification
- Write a program that obtains two integer numbers
from the user. It will print out the sum of those
numbers. - Pseudocode
- Prompt the user to enter the first integer
- Obtain user's first integer input
- Prompt the user to enter a second integer
- Obtain user's second integer input
- Add first integer and second integer
- Store the result in another variable
- Display an output prompt that explains the answer
as the sum and displays the result
9Observations about the Pseudocode Example
- It is not necessary in pseudocode to mention the
need to declare variables. It is wise however to
show the initialization of variables. - You can use variable names in pseudocode but it
is not necessary to be that specific
10Observations Contd.
- Overall, remember that the purpose of pseudocode
is to help the programmer efficiently write code. - Therefore, you must honestly attempt to add
enough detail and analysis to the pseudocode - Sometimes in the professional programming world,
the people who write pseudocode are not the same
people that write the actual code for a program - In fact, sometimes the person who writes the
pseudocode does not know what programming
language will be used to eventually write the
program.
11Visualisation in Actual Code
- As a beginner, you will not be able to do this
- However, by the end of the course you will find
that you will visualise the code for everyday
events and systems How sad will you be then?
12Cards
- Pick a card, any card
- Look at it, memorise it
- Put it back in the pack
- I will use my powers to tell you the card that
you picked
13Everything is a system
- Original Program Specification
- Write a program that allows the user to pick a
card value from a list of possible values. It
will present the user with a prediction of the
chosen value. - Pseudocode
- Prompt the user to memorise a single value from a
list of possible values - Obtain user's input as verification
- Generate a random selection from the list of
possible values - Display selection
- Ask user for verification that guess was
correct - How did you memorise the card value?
14Variables, Constants and Calculations
- Programming In
- Visual Basic.NET
15Variables Constants
- Variable
- Memory locations that hold data that can be
changed during project execution - Ex hours_worked
- Named Constant
- Memory locations that hold data that cannot be
changed during project execution - Ex GST_rate
16Constants
- Named
- User defined
- Intrinsic
- System defined within Visual Studio
17Declaration
- Variables and Named Constants must bedeclared
before being used in code - When you declare a Variable or Named Constant VB
- Reserves an area of memory
- Assigns it a name called an Identifier
- Declaration statements are coded either
- Beginning of a procedure
- General Declarations of a module
18Declaration Statements
- DIM used to declare Variables
- CONST used to declare Named Constants
- Declaration includes
- Name, follow Naming Convention Rules
- Data Type
- Required Value for Constants
- Optional Initial Value for Variables
19Data Types (p 97 Table 3.1)
- Boolean
- Byte (0 to 255)
- Char
- Date
- String
- Decimal
- Object
- Short (-32,768 to 32,767)
- Integer (-2,147,483,648 to 2,147,483,647)
- Long (larger whole numbers)
- Single (floating point accuracy to 6 digits)
- Double (floating point accuracy to 14 points)
20Data Types Memory Usage
- Boolean 2 bytes
- Byte 1 byte
- Char 2 bytes
- Date 8 bytes
- String varies
- Decimal 16 bytes
- Object 4 bytes
- Short 2 bytes
- Integer 4 bytes
- Long 8 bytes
- Single 4 bytes
- Double 8 bytes
21Data Types Prefixes
- Boolean bln
- Byte byt
- Char chr
- Date dat
- String str
- Decimal dec
- Object depends on type of object
- Short sht
- Integer int
- Long lng
- Single sng
- Double dbl
22Declaration Examples
Dim strName, strSSN As String Dim intAge As
Short Dim decPayRate As Decimal 8.25 Dim
datHireDate As Date Dim blnInsured As
Boolean Dim lngPopulation As Long Const
decDISCOUNT_RATE As Decimal .15
Note Constants are named using all uppercase
letters EXCEPT the prefix.
23Type-Declaration Characters
- Append single character to the end of the
Constant's Value to indicate the Data Type
- Decimal D
- Single F
- Double R
24Variables Scope Lifetime
- Global/Public (use sparingly and cautiously)
- Available to all modules and procedures of
Project - Initialized at start of Project
- Module/Private (Form)
- Available to one module and all procedures within
that module - Initialized 1st time the Form is loaded
- Local
- Available only to the procedure it is declared in
- Initialized every time the Procedure runs
- Block
- Available only to the block of code inside a
procedure it is declared in - Initialized every time the Procedure runs
25Scope Declaring Naming
- Global/Public g prefix
- Declare in General Declarations as Public
- Dim gstrName as String
- Module/Private m prefix
- Declare in Modules General Declarations as
Private - Dim mstrName as String
- Local no prefix required
- Declare in Event Procedures
- Dim strName as String
26Declaring Module Level Variables Example
27Calculations
- Calculations can be performed using properties of
certain objects, variables, constants, and
numeric literals - Do Not use Strings in calculations
- Values from Text property of Text Boxes
- Are Strings, even if they contain numeric data
- Must be converted to a Numeric Data Type
28Conversion Functions
- Functions perform an action and return a value
- Expression to operate on is called the Argument
- Conversion Functions convert arguments into a
numeric value of the correct data type - Conversion Functions on Text Boxes fail if user
enters nonnumeric data or leaves the Text Box
blank
29Conversion Functions (cont.)
Function Convert To CInt Integer CDec Decimal
CStr String
CInt rounds to the nearest Even Number
30Conversion Examples(also review examples p 113)
intQuantity CInt(txtQuantity.Text) decPrice CD
ec(txtPrice.Text) Converting to
String strValue resultdecimal.ToString()
Function Name
Argument To Be Acted Upon
31Conversion Examples(Parse method p106)
intQuantity Me.Integer.Parse(txtQuantity.Text) d
ecPrice Me.Decimal.Parse(txtPrice.Text) intWhole
Number CInt(decFractionalValue) decDollars CDe
c(intDollars) strValue CStr(decValue)
Function Name
Argument To Be Acted Upon
32Mathematical Operators
Operator Operation Addition Subtraction
Multiplication / Division \ Integer
Division Mod Modulus (division's
remainder) Exponentiation
33Mathematical Order of Operations
- Computers solve math formulas based on a specific
order 1st, then left to right - 1. Parentheses
- 2. Exponentiation
- 3. Multiplication Division
- 4. Integer Division
- 5. Modulus
- 6. Addition Subtraction
34Mathematical Examples
- Note the use of parentheses to control
342 11 Multiply then add (34)2
14 Parentheses control add then multiply 8/42
4 Same level, left to right divide then multiply
35Option Explicit
- On by default - should be left on
- If turned off
- Variables can be used without first being
declared - They will be defined by VB as data type Object
- To turn off
- Code Option Explicit Off or Option Explicit in
General Declarations - Set in Project Properties dialog box
36Option Strict
- Off by default - should be turned on
- If turned on
- VB becomes strongly typed language
- Will not allow implicit conversions from a wider
data type to a narrower one or between String and
numeric data types - To turn on
- Code Option Strict On in General Declarations
- Set in Project Properties dialog box
37FormatCurrency Function
- General Form
- FormatCurrency(NumericExpression)
- Returns a string of characters formatted as
dollars and cents - Includes a Dollar Sign, commas, and 2 decimal
places by default - Value returned is a String and can no longer be
used in calculations
38FormatNumber Function
- General Form
- FormatNumber(NumericExpression , Decimal Places
, Leading Digit , Use Parentheses for
Negative Numbers , Grouping for Digits ) - Formats with commas and specified number of
decimal places (2 by default)
Line Continuation not included on this slide
39FormatPercent Function
- General Form
- FormatPercent(NumericExpression, Decimal
Places, Leading Digit, Use Parentheses for
Negative Numbers, Grouping for Digits ) - Returns a string of characters formatted as a
percent - Multiplies the argument by 100, adds a percent
sign and rounds to 2 decimal places by default
Line Continuation not included on this slide
40FormatDateTime Function
- General Form
- FormatDateTime(Expression , Named Format )
- Expression can be
- String that holds a date or time
- Date type variable
41Named Formats - FormatDateTime Function
42Handling Exceptions
- Exceptions occur when user enters
unexpected/invalid data and program code does not
anticipate this possibility, such as - User enters nonnumeric data in Text Box and code
attempts to run a Numeric Conversion Function - User enters data that results in division by zero
43Try/Catch Blocks
- Used to catch and handle exceptions referred to
as error trapping or handling - Enclose statements that might cause an error
within Try/Catch Block - If an error occurs control is transferred to the
Catch Block - Include a Finally statement to indicate code that
should execute last whether or not an exception
occurred
44Try Block - General Form
Try statements that may cause error Catch
VariableName as ExceptionType statements for
action when an exception occurs Finally statemen
ts that always execute before exit of Try
block End Try
See p 125 for list of common Exception Classes
45Try Block - Example 1Catches All Exceptions
Try intQuantityCInt(txtQuantity.Text) lblQuanti
ty.TextCStr(intQuantity) Catch lblMessage.Text"
Error in input data." End Try
46Try Block - Example 2Catches Specific Exception
Try intQuantityCInt(txtQuantity.Text) lblQuanti
ty.TextCStr(intQuantity) Catch MyErr as
InvalidCastException lblMessage.Text"Error in
input data." End Try
Conversion exception, usually caused by
nonnumeric or blank data
47Try Block - Example 3Catches Multiple Specific
Exceptions
Try statements that may cause errors Catch MyErr
as InvalidCastException error messages and
statements for nonnumeric data Catch MyErr as
ArithmeticException error messages and
statements for calculation problems Catch MyErr
as Exception error messages and statements for
any other exception End Try
48MessageBox Object
- Use Show Method of MessageBox to display special
type of window - Arguments of Show method
- Message to display
- Optional Title Bar Caption
- Optional Button(s)
- Optional Icon
49MessageBox Syntax
- The MessageBox is an Overloaded Method
- Signatures correspond to the Argument list
- There are multiple Signatures to choose from
- Arguments must be included to exactly match one
of the predefined Signatures
MessageBox.Show (TextMessage, TitlebarText, _
MessageBoxButtons, MesssageBoxIcon)
50MessageBoxButtons Constants
- OK
- OKCancel
- RetryCancel
- YesNo
- YesNoCancel
- AbortRetryIgnore
51MessageBoxIcon Constants
- Asterisk
- Error
- Exclamation
- Hand
- Information
- None
- Question
- Stop
- Warning
52Counting Accumulating Sums
- Must use Module/Form level variables since
Local/Event level variables reset to 0 each time
the procedure is called - Summing
- mdecOrderTotal mdecOrderTotal decItemPrice
- Counting
- mintNumItems mintNumItems 1
- mintNumItems mintNumItems
- Averaging
- mdecAveSale mdecOrderTotal / mintNumItems
53Lets look at..
- Reaction time example pseudocode
- Pseudocode _for_Reaction_Time.doc
54The End
- Friday - Decisions and Conditions
- Questions?