Lecture 10 - Boolean Variables, Formatting and Errors


Home


Objectives

Contents


1. Boolean Variables

So far we have covered the data types: Integer, Double and String. Another important data type is Boolean. Boolean variables hold the value True or False. Boolean variables should have names that make it obvious what is meant when they are True or False e.g. customerFound (if it is True the customer has been found; if it is False they haven't been found), validMark (if it is True the mark is valid otherwise the mark is invalid (wrong)). Boolean variables are sometimes called Flags or Switches as they are either On (True) or Off (False).

Example

Problem 1: Display whether it is a weekday or weekend

Pseudo Code

displayDayType()
 
 
 
 
 
 
 
 
 
 
STOP

Data Dictionary

 
 
 
 

Visual Basic Code

' Name:    displayDayType
' Purpose: Display whether it is a weekday or a weekend
' Author:  Tim Whitfort
Option Compare Database
Option Explicit
Sub Main()
    'Declare variables
    Dim day As String  ' The day name
    Dim isWeekday As Boolean  ' Is it a weekday
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
End Sub

Problem 2: Calculate a grade for a numeric mark

Pseudo Code

calcGrade()
    validMark = True
    input mark
    IF mark > 100 THEN
        validMark = False
    ELSE
        IF mark >= 80 THEN
            grade = "A"
        ELSE
            IF mark >= 70 THEN
                grade = "B"
            ELSE
                IF mark >= 60 THEN
                   grade = "C"
                ELSE
                    IF mark >= 50 THEN
                        grade = "D"
                    ELSE
                        IF mark >= 0 THEN
                            grade = "N"
                        ELSE
                            validMark = False
                        ENDIF
                    ENDIF
                ENDIF
            ENDIF
        ENDIF
    ENDIF
    IF validMark = True THEN
        Display grade
    ELSE
        Display "Error: mark must be between 0 and 100"
    ENDIF
STOP

Data Dictionary

Name Data Type Description
grade String The grade corresponding to the mark e.g. A, B, ...
mark Integer The numeric mark e.g. 85%. Valid marks are from 0 to 100 inclusive.
validMark Boolean Is the mark valid.

2. Debug.Print

Debug.Print can be used to print out any number of values, whether they be literal vales (e.g. "Name =", "kph") or variables values.

When a semicolon is used the value is printed immediately after the previous value. Whereas a comma means display the value in the next column. Columns are 14 characters wide e.g. they start at character position 1, 15, 29, 43 etc. Ending a Debug.Print line with a semicolon results in the current and next line being displayed on the same line. To display a blank line, use Debug.Print without any values.

Examples: (speed = 123, x = 3, y = 9)

 
 
 
 
 
 
 

Example Run

 
 
 
 
 
 

3. Formatting Code and Naming Variables

Programs are often used for many years and are changed over their lifetime. How easy they are to maintain and understand will depend on the quality of the design, layout and documented. A program that is easy to understand is more likely to be error free and stay that way throughout its lifetime.

Many organisations have coding conventions that provide guidelines for coding. Formatting conventions specify the layout of code such as indentation. This helps makes the code more uniform and therefore makes it easier to read, understand and maintain.  Indentation and Whitespace are forms of formatting.

Indentation

Indentation is horizontal spacing of lines of pseudo code or program code. Indentation is used to show the scope (what it includes) of statements. For example, the statements in a While loop are indented between the While and Wend to clearly shown the start and end of the loop and the statements that are within the loop.

Some rules for indentation in Access Basic:

Indent the line following a:

Unindent lines with an:

The equivalent statements in Pseudo code have the same indentation.

The following keywords should line up:

Whitespace

Whitespace is the name given to spaces, tabs and blanks lines. Whitespace makes it easier to read code by making careful use of blank areas (horizontally or vertically) to emphasize code.

Spaces are used as indentation or between variables, operators and keywords e.g.

a = b * 3 / (i - 1 + j) ' is easier to read than: a=b*3/(i-1+j)

Lines of code that perform an identifiable sub-task are often grouped together in a program. This helps the reader understand the structure and purpose of the program. Separating each group by a blank line helps emphasise that the lines within a group are related, and makes it easier to identify sub-tasks.

Naming

It it is important that variables (and other things we name in a program) are meaningful to someone reading the program. This makes the program easier to understand, and therefore easier to change. Carefully choosing meaningful names takes a little effort but can make a huge difference to the readability of a program.

Examples

Both of the following programs work identically, however one is easier to understand. Systems are often in use for a long period of time (over 10 years), and undergo many changes during this time. Which of the following would you like to work on?

Example 1

Option Compare Database
Option Explicit
Sub Main()
Dim c As Double
Dim cpm As Double
Dim day As String
Dim d As Long
Dim t As Long
day = InputBox("Day name ? ")
d = InputBox("Duration (minutes) ? ")
If day="Saturday" Then
cpm=0.15
Else
If day="Sunday" Then
cpm=0.1
Else
t=InputBox("Time (24 hour time) ? ")
If t>=7 And t<=19 Then
cpm=0.3
Else
cpm=0.15
End If
End If
End If
c=d*cpm
Debug.Print "Call cost $"; Format(c, "0.00")
End Sub

Example 2

' Name: calcPhoneCallCost
' Purpose: Calculate the cost of a phone call
' Author: Tim Whitfort

Option Compare Database
Option Explicit

Sub Main()

    ' Declare variables
    Dim callCost As Double ' The cost of the phone call
    Dim callCostPerMinute As Double ' The cost of the call in dollars per minute
    Dim day As String    ' the day name e.g. "Saturday"
    Dim duration As Long ' the duration of the call in minutes
    Dim time As Long     ' The hour the call was made in 24 hour time

    ' Input the day name
     day = InputBox("Day name ? ")
    ' Input the duration in minutes
    duration = InputBox("Duration (minutes) ? ")

    ' Determine the costPerMinute from the day and if necessary the time
    If day = "Saturday" Then
        callCostPerMinute = 0.15
    Else
        If day = "Sunday" Then
            callCostPerMinute = 0.1
        Else
            ' Input the time in hours the call was made
            time = InputBox("Time (24 hour time) ? ")
            If time >= 7 And time <= 19 Then
                callCostPerMinute = 0.3
            Else
                callCostPerMinute = 0.15
            End If
        End If
    End If

    ' Calculate call cost
    callCost = duration * callCostPerMinute

    ' Display call cost
    Debug.Print "Call cost $"; Format(callCost, "0.00")

End Sub

4. Types of Errors

Syntax Errors

Before the program can be run it must be free of Syntax Errors. A Syntax Error results from the incorrect use of the language - the program code does not conform to the rules of the language. This is equivalent to using incorrect grammar in English (e.g. "The car were blue") - except that a compiler is far picker about language than a grammar checker. The Compiler is a program that (amongst other things) checks for syntax errors. Syntax errors are also known as Compiler Errors.

Syntax errors can be detected by the compiler and highlighted in Access Basic when: (a) typing in a line of code, or (b) when compiling the whole program.

Some examples of syntax errors are:

 
 
 
 
 
 

Logic Errors

Logic Errors occur when the program is running. They are a mistake in the logic of the program. This is equivalent to a grammatically correct sentence in English that doesn't make any sense or doesn't state what was intended (e.g. "The car was raining", "two plus two is five").

The logic error may stem from (a) not understanding the problem, (b) not developing the correct logic for the problem (pseudo code) or (c) not correctly translating the pseudo code into code. Logic errors can be minimised by taking the time to understand the problem then carefully designing, developing and checking a solution.

Experience shows that even the best programmers make mistakes, so remember to check your logic (desk check) and thoroughly test your program.

Option Explicit is used to assist the programmer by indicating any variables that aren't declared.

Examples of logic errors are:

		
		
		
		
		

Run-time Errors

Run-time Errors occur when the program is running. A run-time error is when a program attempts an illegal operation. Often run-time errors are difficult to detect until the program is running, and might only occur under certain unusual circumstances when variables have particular values. In some cases the error could be considered a logic error as the run-time error could have been avoided if the logic detected and avoided the situation.

Some examples of run-time errors:

 
 
 
 
 

What's Next?

In the next few lecturers we will look at repetition (also called iteration or looping). So far we have only been able execute a statement once in a program run. Repetition is used where we want to execute statements a number of times.

Key Points

Further Reading


Written by Tim Whitfort.