Information Technology (IT)
DELPHI STUDY GUIDE
Contents
Concise summary of CAPS ............................................................................................................. 1
Basic layout of a gr 12 paper .......................................................................................................... 3
Basic Delphi components and properties summary ....................................................................... 4
Programming structures ...................................................................................................................... 6
Choice structure ............................................................................................................................... 6
IF ..................................................................................................................................................... 6
CASE When you have more than two options for the SAME criteria ............................... 6
SETS (in) ....................................................................................................................................... 7
Repeat structure ............................................................................................................................... 7
FOR loop: repeat for a known number of times (unconditional loop) ................................. 7
WHILE loop: repeat for an unknown number of times (conditional loop) ........................... 7
REPEAT loop: repeat for an unknown number of times (conditional loop) ......................... 7
Basic data structures in Delphi ........................................................................................................... 8
Basic data types (single elements) ................................................................................................ 8
Compound data types (collection of basic data types) ............................................................... 8
Arrays ............................................................................................................................................. 8
Objects – used in OOP nature of Delphi .................................................................................. 9
Files ................................................................................................................................................ 9
Lama example to explain the difference between for, while and repeat ..................................... 9
Assignment........................................................................................................................................ 9
Solution .............................................................................................................................................. 9
CONVERSIONS ................................................................................................................................. 11
Richedit component ........................................................................................................................... 12
Pocket money example to show formatting of rich edit component ........................................... 12
Assignment...................................................................................................................................... 12
Solution ............................................................................................................................................ 13
ALGORITHMS .................................................................................................................................... 14
Basic algorithms ............................................................................................................................. 14
Assignment........................................................................................................................................ 14
Solution ............................................................................................................................................ 16
Mathematical functions (built-in) .................................................................................................. 22
Assignment...................................................................................................................................... 22
Solution ............................................................................................................................................ 24
Binary logic example .......................................................................................................................... 30
Assignment...................................................................................................................................... 30
Solution ............................................................................................................................................ 30
INFORMATION TECHNOLOGY | Delphi Study Guide | ii
String handling .................................................................................................................................... 31
Basic built-in functions and procedures ...................................................................................... 31
Basic string handling algorithms ...................................................................................................... 31
Assignment...................................................................................................................................... 31
Solution ............................................................................................................................................ 37
Text files .............................................................................................................................................. 46
Basic text file instructions .............................................................................................................. 46
Assignment...................................................................................................................................... 47
Solution ............................................................................................................................................ 50
Arrays (1D) ...................................................................................................................................... 55
Learner example to illustrate basic 1D array handling algorithms .............................................. 56
Assignment...................................................................................................................................... 56
Solution ............................................................................................................................................ 59
Arrays (2D) ...................................................................................................................................... 66
Crossword example to illustrate basic 2D array handling algorithms ........................................ 66
Assignment...................................................................................................................................... 67
Solution ............................................................................................................................................ 67
OOP (Object Orientated Programming).......................................................................................... 69
Introduction...................................................................................................................................... 69
Own objects / units / classes ........................................................................................................ 70
Assignment...................................................................................................................................... 71
Solution ............................................................................................................................................ 72
Database handling ............................................................................................................................. 75
SQL ...................................................................................................................................................... 75
Some basic structure(s): ........................................................................................................... 75
Basic structure of a SQL statement to display information .................................................. 75
Examples to display information on the dbgrid: SELECT .................................................... 76
Built-in functions and calculated fields / aggregate functions:............................................. 77
SQL statements: DELETE / INSERT / UPDATE ....................................................................... 79
ADO- tabels / DML (data management language) / Delphi code construct and Access ........ 80
Instructor example to show use of Delphi construct and (ADO) database handling ............... 81
Assignment...................................................................................................................................... 81
Solution ............................................................................................................................................ 83
Basic error messages with possible solution ................................................................................. 88
INFORMATION TECHNOLOGY | Delphi Study Guide | iii
1. Introduction
1.1 This study guide covers selected parts of the different programming topics of
the CAPS Grade 12 Information Technology (IT) curriculum. The study guide
does NOT cover the entire CAPS curriculum, but it does focus on core content
of each programming area.
1.2 You must work your way through this study guide to improve your
understanding, identify your areas of weakness and correct your own
mistakes. To ensure a high-quality pass, you should also cover the remaining
parts of the curriculum using other textbooks, latest examination guidelines,
past NSC examination question papers and the Annual Teaching Plan (Grade
10 – 12). It is important to note that content from Grade 10, 11 and 12 will be
examined in the final NSC examination.
2. How to use the Study Guide
The selected parts of each topic are presented in the following way:
2.1 A study guide, ordered in topics, to get an understanding of the Delphi
programming content.
2.2 Questions are arranged in folders from Question 1 to Question 4 as examined
in the NSC Final Examination.
2.3 Questions and data from past NSC final examinations are included for you to
answer. Complete the NSC questions on your own, then check your answers
with the solutions provided.
2.4 Additional activities, based on exam-type questions, are included with
questions, and data for you to answer. Complete the activities on your own
then check your answers with the solutions provided.
2.5 Questions and activities should be completed in Delphi on your computers as
informal assessments.
3. Pictures to indicate
3.1 General information
3.2 Work to study
3.3 Assignments
3.4 Solutions
INFORMATION TECHNOLOGY | Delphi Study Guide | iv
Concise summary of CAPS
Logical Database
Components Basic algorithms Functions operators String handling programming
form frm Smallest /Largest Mod < + / Concat Open
button/bitbutton btn Swapping of values Div > Copy First
label lbl Even/Odd numbers Random >= Delete Last
panel pnl Factors RandomRange <= Insert Next
radio group rgp Prime numbers Round Not Pos Previous
Number properties e.g.
Length RecordCount
edit box edt negative/odd/prime.... RoundTo And
labeled edit edt Multiples Trunc Or UpperCase EOF
richedit red Sqr <> UpCase Fieldbyname
spinedit spn Reversed strings Power LowerCase Tablename['fieldname']
memo mem Remove vowels Sqrt [] Insert
combo box cmb Count words Ceil Type cast Trim Delete
check box chb Palindrome Floor IntToStr Ord Edit
list box lst Replace characters Int StrToInt Chr Post
image img Frac FloatToStr
timer tmr Text files Odd StrToFloat Arrays SQL
pagecontrol pgc FileExists Pi DateToStr Add/Insert select
menu mnu Reset Abs StrToDate Delete from
Append Succ TimeToStr Search (binary) where
Rewrite Pred StrToTime Search (linear) group by
Dynamic Readln Date CurrToStr Replace Having
Showmessage Read Time Insert order by
Messagedlg Writeln DayOf Duplicates distinct
InputBox Write MonthOf Aggregates as [heading]
InputQuery EOF YearOf Insert Into
CloseFile CurrentYear Update
INFORMATION TECHNOLOGY | Delphi Study Guide | 1
DaysInMonth Validation methods Formatting Delete
incYear TryStrToInt Format
incDay TryStrToFloat FloatToStrF SQL Operators
incMonth Val Between
Database components DaysBetween Try... Except In
StringGrid sgd YearsBetween In [ ] OOP Like
DBGrid dbg Procedures DayOfWeek Constructor Is Null
ADOTable adt Inc Yesterday Mutator
ADOQuery adq Dec Today Accessor SQL Formatting
DataSource dts Tomorrow Auxiliary Round
DBText dbt DayOfTheYear toString Int
DBEdit dbe Format
SQL String SQL Aggregate
functions functions
Left Sum
Mid Average
You may not use build-in functions to “bybass” basic programming skills and techniques Len Min
E.G. [ ] in field names Max
ContainsText/replacestring/min(array) / max(array) / reversestring / ado.locate / ado.filter / Right Count
ado.sort/ ado.InsertRecord / No savetofile/readfromfile when working with text files / IntToHex Concatenation/”&"
InStr SQLDate functions
UCase Year
LCase Day
Month
Date
DateValue
INFORMATION TECHNOLOGY | Delphi Study Guide | 2
Basic layout of a gr 12 paper
Remember that this is only a very broad layout of principles according to past papers
– it CAN be different.
Question 1
1.1 Formatting and/or basic calculations
1.2 Make use of grade 10 functions
1.3 Selection structures
1.4 Loop structures
1.5 String handling
Question 2
2.1.1 Display all, order by
2.1.2 Display certain fields, make use of where
2.1.3 Use a compound “where”.
Aggregated functions with a heading
Group By.
2.1.4 Make use of parameters
2.1.5 Make use of both tables/Group by with HAVING
2.1.6 Insert / Delete / Update
2.2.1 Loop through all the information of the table
2.2.2 Edit/delete for specific record / active record.
2.2.3 Insert
2.2.4 Use of both tables
2.2.5 Display / count specific records
Question 3
Can make use of a text file within the object class or the form class
3.1.1 Constructor create – can have another name (with or without parameters)
3.1.2 -3.1.X At least 1 Accessor, 1 Mutator, 1 Auxiliary method
3.1.X To string/Display method
Declaration of the object can be given
3.2.1 Create the object
3.2.2 Call all the methods
Question 4
Will probably include 1D and/or 2D arrays and/or text files
Problem-solving, without lots of instructions
Start with easy question like display information
Marks awarded for coding principles and not necessarily for each and every step.
INFORMATION TECHNOLOGY | Delphi Study Guide | 3
Basic Delphi components and properties summary
NOTE: some properties are the same for more than one component Richedit (red)
the *,$ and # characters indicate these properties in order to save space and All * attributes/properties except.caption
not retype them several times… .lines.add(‘text_words’) {Do not use:=}
.paragraph.tabcount.:= number
Form (frm) {state number of columns}
.caption:= ‘text_words’* Button (btn) .paragraph.tab[number].:= number
.height:= number*# All * attributes/properties {state column position}
size
.width:= number*# .enabled.:= true / false*# .paragraph.alignment:= ta….
.color:= cl…* .top.:= number*# .clear.
position
.font.color:= cl…* .left.:= number*# .alignment:= ta….
.Name:= ‘Font type’* .visible.:= true /false*# .selattributes.color:= cl…
{can use.show &.hide}
.style:= [fs.., fs..] * .Name:= ‘Font type’
.showhint.:= true /false*#
:= [] for no style
.hint.:= ‘text_words’*#
.style:= [fs.., fs..]
.size:= number*
.wordwrap.:= true /false
Edit (edt) Image (img)
All * attributes/properties Label (lbl) All # attributes/properties
Labelededit (edt)
.text:= ‘text_words’ All * attributes/properties All * attributes/properties .picture.loadfromfile(‘filename’)
.alignment:= ta…. .text:= ‘text_words’ .wordwrap.:= true /false .stretch.:= true /false
.alignment:= ta…. .transparent.:= true /false #
Spinedit (sed) .labelposition:= lp,,,
All * attributes/properties .labelspacing:= number
.text:= ’text_words’ Panel (pnl)
.editlabel {. with all lbl properties} All * attributes/properties
.value:= integerValue
INFORMATION TECHNOLOGY | Delphi Study Guide | 4
Inputbox (dynamic component ) Dialogue box (dynamic component)
sVariable:= inputbox(‘message,’example’,’inputvalue’); messagedlg(‘message,mt…,[mb..],0);
InputQuery('Enter a value','e.g. 7',sValue); { Do not use:=} Mt = messagetype, mb = messagebutton, mr = messagereply
ShowMessage(‘Message’);
Radiogroup (rgp)
All * attributes/properties
Memo (mem)
.columns:= number All * attributes/properties
.items.add(‘text_words’) {Do not use:=}$ .lines.add(‘text_words’) { Do not use:=}
.itemindex {the position on selected item in list} $ .clear.
{itemindex = -1 no selection}
.alignment:= ta….
.items[rgp.itemindex] { the value of the selected item} $
Variables
• Must be declared
Listbox (lst) VAR
All * and $ attributes/properties except.caption sVariable: string;
.columns:= number iVariable: integer/byte;
.sorted.:= true / false rVariable: real;
• Must assign a value {input}
_Variable:= …….;
Combo box (cmb) • Global {form class variable}
All * and $ attributes/properties except.caption All event handlers can use variable
.text {the value of the selected item} Initialise in OnActivate
.sorted.:= true / false • Local {method variable}
Only event handlers where variable is
declared can use variable
Checkbox (chb)
All * attributes/properties Constants
.wordwrap.:= true /false • Declare and initialise
.checked:= true/false CONST
sVariable = -------;
INFORMATION TECHNOLOGY | Delphi Study Guide | 5
Programming structures
Choice structure
IF When specific code must be executed if certain criteria is met….
Examples of logic expressions (criteria):
value > 10 sValue <> ‘Stop’ (iValue > 20) and (iValue<50)
(iValue <= 20) or (iValue>50)
if <logical expression> if <logical expression> if <logical expression> if <logical expression>
then …. then …….; then begin then begin
else …..; …… ; …… ;
……; ……;
end; //if then end //if then
else …….;
if <logical expression> Logical operators:
then begin =
…..; >=
A composite instruction consists of
…..; <=
more than one instruction and must
end // if then and
be placed between a begin and end
else begin or
to group single instructions as one
…..; not
complex instruction
…..; <>
end; //if else
CASE When you have more than two options for the SAME criteria
case iValue of case cValue of case Value of case Value of
1: ……..; ‘1’: ……..; __: ……..; __: begin
2,5,6: …….; ‘2’,’5’,’6’: …….; __: …….; ……..;
9-15: ……..; ‘7’-‘9’: ……..; __: ……..; ……..;
End; //case End; //case else end; //option
………; __: begin
……..; ……..;
End; //case ……..;
end; //option
__: ……..;
__: ……..;
End; //case
Complex / composite criteria:
If (<logical expression>) and (<logical expression>) or (<logical expression>) …
AND: all the answers must be TRUE to have a final answer of TRUE
OR: one answer must be TRUE to have a final answer of TRUE
NOT: gives the opposite: if NOT (<logic expression>)
INFORMATION TECHNOLOGY | Delphi Study Guide | 6
SETS (in)
If cValue in [‘a’,’c’,’k’] If cValue in [‘a’..’z’,’A’..’Z’] If UpCase(cValue) in [’A’..’Z’]
Then ….. Then ….. Then …..
If iValue in [1,4,7] If iValue in [20..60]
Then ….. Then …..
Repeat structure
FOR loop: repeat for a known number of times (unconditional loop)
For iCounter:= firstValue to lastValue do
Begin
…;
…;
End; //for
For iCounter:= lastValue downto firstValue do
Begin
…;
…;
End; //for
WHILE loop: repeat for an unknown number of times (conditional loop)
FirstValue:=.... ; initialise – first value of control variable
While firstValue <> lastValue do test control variable
Begin
FirstValue:= nuweValue change control variable
End; //while
REPEAT loop: repeat for an unknown number of times (conditional loop)
NOTE: initialising the control variable not necessary outside the loop depending on the
logic of the code.
FirstValue:=.... ; initialise – first value of control variable
repeat
FirstValue:= change control variable
Until firstValue = lastValue ; test control variable
While: executes 0 / any number of times
Repeat: executes always at least once
INFORMATION TECHNOLOGY | Delphi Study Guide | 7
Basic data structures in Delphi
Basic data types (single elements)
var
// Integer data types: (ordinal)
Int1: Byte; //0 to 255
Int2: ShortInt; //-127 to 127
Int3: Word; //0 to 65,535
Int4: SmallInt; //-32,768 to 32,767
Int5: LongWord; //0 to 4,294,967,295
Int6: Cardinal; //0 to 4,294,967,295
Int7: LongInt; //-2,147,483,648 to 2,147,483,647
Int8: Integer; //-2,147,483,648 to 2,147,483,647
Int9: Int64; //-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
// string data types: (not ordinal -except char)
Str1: Char; //Holds a single character, small alphabet
Str2: WideChar; //Holds a single character, International alphabet
Str3: AnsiChar; //Holds a single character, small alphabet
Str4: ShortString; //Holds a string of up to 255 Char's
Str5: String; //Holds strings of Char's of any size desired
Str6: AnsiString; //Holds strings of AnsiChar's any size desired
Str7: WideString; //Holds strings of WideChar's of any size desired
// logical data types: (ordinal)
Log1: Boolean; //Can be 'True' or 'False'
//Date and type data types
Date1: TDateTime
Date2: TDate
Compound data types (collection of basic data types)
NOTE: we do not look at records and sets because it is not in the caps
Arrays
An array is a collection of a basic data type and is accessed by an index.
An array holds data in indexed 'slots' or ‘elements’.
Each slot/element is one variable of data.
Visualise arrays as lists.
Example of the declaration of arrays:
One dimensional:
arrDatatype: array[1..4] of String; arrDatatype: array[’C’..’J’] of Real;
arrDatatype: array[1..4] of Integer; arrDatatype: array[-20..10] of String;
arrDatatype: array[20..40] of String;
Two dimensional:
arrData: array[’A’..’J’,1..23] of Real; arrData: array[1..10,1..12] of String;
INFORMATION TECHNOLOGY | Delphi Study Guide | 8
Objects – used in OOP nature of Delphi
An object is an abstact / own data type consisting of a collection of both data and logic
structures. It can include multiple properties/attributes and methods.
They act like programs, but represent a data structure.
Files
Text files: consists of characters and no formatting, can be accessed by any application
Data files: consists of tables, records and fields.
Lama example to explain the difference between for, while and repeat
Assignment
Write code to imitate a walking lama from the left side of the form to the right side of the
form and back.
Solution
[FOR loop]
procedure TfrmLama.btnForClick(Sender: TObject);
var
K: Integer;
begin
imgLama.Stretch:= true; //display the full picture
For K:= 1 to 100 do
// known number of repetitions = 100
// initial value / first value of control variable K is 1
// the for loop increases the control variable (counter) automatically
begin
sleep(100); //freeze the image to be visible for human eye
imglama.left:= imglama.left + Random(20); //move image
imglama.height:= Randomrange(80,150); //change height and width
imglama.width:= Randomrange(80,150); //to imitate movement
repaint; //paint the form to display new position
end; //for
imglama.Picture.LoadFromFile('llama R.jpg'); // change picture
For K:= 1 to 100 do //move back to starting position
begin
sleep(100);
imglama.left:= imglama.left -Random(20);
imglama.height:= Randomrange(80,150);
imglama.width:= Randomrange(80,150);
repaint;
end; //for
INFORMATION TECHNOLOGY | Delphi Study Guide | 9
//Reset image position and picture
imglama.Picture.LoadFromFile('llama L.jpg');
imglama.Left:= 8;
end;
procedure TfrmLama.btnRepeatClick(Sender: TObject);
begin
imgLama.Stretch:= true;
//initial value of control is left property of image
Repeat
sleep(100);
imglama.left:= imglama.left + Random(20); //change value of control variable
imglama.height:= Randomrange(80,150);
imglama.width:= Randomrange(80,150);
repaint;
until imglama.left >= (frmLama.width - imglama.width);
// unknown number of repetitions = criteria / condition is needed
imglama.Picture.LoadFromFile('llama R.jpg');
Repeat
sleep(100);
imglama.left:= imglama.left - Random(20); //change value of control variable
imglama.height:= Randomrange(80,150);
imglama.width:= Randomrange(80,150);
repaint;
until imglama.left <= 8;
imglama.Picture.LoadFromFile('llama L.jpg');
end;
[WHILE loop]
procedure TfrmLama.btnWhileClick(Sender: TObject);
begin
imgLama.Stretch:= true;
//initial value of control is left property of image
// unknown number of repetitions = criteria / condition is needed
while imglama.left < (frmLama.width - imglama.width) do
begin
sleep(100);
imglama.left:= imglama.left + Random(20); //change value of control variable
imglama.height:= Randomrange(80,150);
imglama.width:= Randomrange(80,150);
repaint;
end; //while
imglama.Picture.LoadFromFile('llama R.jpg');
INFORMATION TECHNOLOGY | Delphi Study Guide | 10
while imglama.left > 8 do
begin
sleep(100);
imglama.left:= imglama.left - Random(20);
//change value of control variable
imglama.height:= Randomrange(80,150);
imglama.width:= Randomrange(80,150);
repaint;
end; //while
imglama.Picture.LoadFromFile('llama L.jpg');
end;
CONVERSIONS
FUNCTION WHEN COMPONENT EXAMPLE
StrToInt: input InputBox/Edit iNumber:= strtoint(edt. Text);
LabeledEdit iNumber:= sed. Value;
IntToStr: display Label/Edit/Panel sNumber:= IntToStr(inumber);
an integer ShowMessage
RichEdit
MessageDlg
StrToFloat: input InputBox/Edit iNumber:= StrToFloat(edt.Text);
FloatToStr / display a real Label/Edit lbl.Caption:=
Format FloatToStr(rnumber);
RichEdit lbl.Caption:=
Format(‘%10.2f’,[rnumber]);
MessageDlg
ShowMessage
Options for currency and fixed decimal places
RichEdit1.Lines.Add(FloatToStrF(rValue,ffCurrency,10,2);
RichEdit1.Lines.Add(CurrToStrF(rValue,ffCurrency,2);
RichEdit1.Lines.Add(Format('R%10.2f',[rValue]);
lbl.Caption:= FloatToStrF(rnumber,fffixed,10,2);
RichEdit1.Lines.Add(Format('%10.2m',[rValue]);
TimeToStr retrieve system time as string sVariable:= TimeToStr (time);
DateToStr retrieve system date as string sVariable:= DateToStr (date);
sVariable:= DateToStr (now);
StrToDate convert string to date dDate:=
StrToDate (‘2013/09/14’);
StrToTime convert string to time tTime:= StrToTime (’13:20’);
BoolToStr convert Boolean to string sBoole:= BoolToStr(true);
ERROR HANDLING: test for errors before conversion…
TryStrToInt string to integer if TryStrtoInt(sValue,iValue)
TryStrToFloat string to real (double) if TryStrToFloat(sValue,rValue)
INFORMATION TECHNOLOGY | Delphi Study Guide | 11
Richedit component
//set tabs in richedit
redOutput.Paragraph.TabCount:= 3; //3 spaces = 4 columns
redOutput.Paragraph.Tab[0]:= 50; //position where column starts
redOutput.Paragraph.Tab[1]:= 150;
redOutput.Paragraph.Tab[2]:= 250;
//set format of headings / format of a single line
redOutput.SelAttributes.Style:= [fsbold,fsItalic,fsUnderline]; //all styles
redOutput.SelAttributes.Style:= [fsbold,fsItalic ];
redOutput.SelAttributes.Style:= [fsbold];
redOutput.SelAttributes.Style:= [ ]; //no style
redOutput.SelAttributes.Color:= clred; // colour for one line
//can also use a number to set a color
redOutput.SelAttributes.Color:= 2345467;
//set font size for a single line
redOutput.selAttributes.Size:= 20;
//set font type for a single line
redOutput.SelAttributes.Name:= ‘Arial’;
redOutput.SelAttributes.Name:= 'Vladimir Script';
//set format for richedit as a whole
redOutput.font.size:= 23;
redOutput.font.color:= clGreen;
redOutput.color:=clblue;
REMEMBER THE SAME PRINCIPLES APPLY TO MOST COMPONENTS
Pocket money example to show formatting of rich edit component
Assignment
Retrieve the basic pocket money the year starts with from the spin edit component.
Button [CALCULATE]
Get the percentage increase per month as user input.
Display the month number and pocket money for each month of the year,
as well as the amount that will be earned for the year.
INFORMATION TECHNOLOGY | Delphi Study Guide | 12
Solution
procedure TfrmPocketMoney.btnCalculateClick(Sender: TObject);
var
iPocketMoney,iTotalAmount: real;
rPerc: real;
iCounter: integer;
begin
//retrieve the start value of first month's pocket money
iTotalAmount:= sedStartValue.Value;
//set tabs for richedit - only one space = 2 columns
redDisplay.Paragraph.TabCount:= 1;
redDisplay.Paragraph.Tab[0]:= 50;
//set format for headings
redDisplay.SelAttributes.Style:= [fsbold,fsItalic];
redDisplay.SelAttributes.Color:= clred;
//can also obtain a color by using a number:
redDisplay.SelAttributes.Color:= 2345467;
redDisplay.Lines.Add('Month' + #9 + 'Amount') ;
redDisplay.Lines.Add('') ;
iPocketMoney:= sedStartValue.Value; //Retrieve value from spinedit
rPerc:= StrToFloat(InputBox('Percentage increase?','','10'));
//display the amount in currency format for the first month
redDisplay.Lines.Add('1' + #9 + FloatToStrF(iPocketMoney,ffCurrency,10,2)) ;
for iCounter:= 2 to 12 do //should now only display month from 2 - 12
begin
//get new pocket money for the month
iPocketMoney:= iPocketMoney * rPerc/100 + iPocketMoney ;
//increase the total amount
iTotalAmount:= iTotalAmount + iPocketMoney;
//display amount and month number
redDisplay.Lines.Add( IntToStr(iCounter) + #9 +
FloatToStrF(iPocketMoney,ffCurrency,10,2 ));
end;
//display an open line
redDisplay.Lines.Add('') ;
//set font size
redDisplay.SelAttributes.Size:= 20;
//set font type
redDisplay.SelAttributes.Name:= 'Vladimir Script';
//display total amount
INFORMATION TECHNOLOGY | Delphi Study Guide | 13
redDisplay.Lines.Add('Total amount: ' + #9 +
FloatToStrF(iTotalAmount,ffCurrency,10,2 ));
//change background color of richedit
redDisplay.Color:= clGreen;
end;
ALGORITHMS
Basic algorithms
Assignment
The following GUI is provided:
Write code to do the following:
[OnActivate] event handler
Use a dialogue box to enter a real number and assign the number to a form unit
(global) variable.
Convert the real number to an integer number and assign the number to a form unit
(global) variable.
INFORMATION TECHNOLOGY | Delphi Study Guide | 14
Button [btnInteger]
Test and display if a number is a real or an integer number.
Button [btnPositive]
Display if a number is a positive or negative number.
Button [btnEven]
Display if a number is an even or odd number.
Button [btnCompleteSquare]
Display if a number is a perfect square or not or if it is a negative number.
Button [btnFactors]
Determine and display the factors as well as the number of factors for an integer
number in the label.
Button [btnMultiple]
Determine and display the first 10 multiples of a number.
Button [btnDivisible]
Use a dialogue box to enter a second number.
Determine and display any divisibility between this number and the original number.
Display a message if neither of them is a factor of each other.
Button [btnUnknown]
Use a dialogue box to enter an unknown number of numbers.
Stop the execution of the loop when the number 0 is entered.
Determine and display the sum, average and product of the numbers entered.
Button [btnStatistics]
Use a dialogue box to enter an unknown number of numbers.
Stop the execution of the loop when the number 0 is entered.
Determine and display the largest and smallest number entered.
Button [btnPrimeNumber]
Determine and display all the prime numbers less than the original number.
Button [btnGCD]
Use dialogue boxes to enter two numbers.
Determine and display the greatest common divider /highest common factor of two
numbers.
Button [btnLCM]
Use dialogue boxes to enter two numbers.
Determine and display the lowest common multiple of the two numbers.
INFORMATION TECHNOLOGY | Delphi Study Guide | 15
Button [btnSwap]
Use the two numbers in the given edit components.
Swap and display the swapped values in the edit components.
Solution
[OnActivate] event handler
procedure TfrmBasicAlgorithms.FormActivate(Sender: TObject);
begin
WindowState:= wsMaximized; //full screen in run time
//InputBox's data type is string and number is declared as real
//therefor conversion required
rNumber:= StrToFloat(InputBox('Enter a Number','eg 10','10'));
//some functions (buttons) require integer numbers....
iNumber:= Trunc(rNumber);
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 16
Button [btnInteger]
procedure TfrmBasicAlgorithms.btnIntegerClick(Sender: TObject);
begin
//if the fraction of a number is zero = integer
if frac(rNumber) = 0 then
pnlInteger.Caption:= 'Integer'
else pnlInteger.Caption:= 'Real';
end;
Button [btnPositive]
procedure TfrmBasicAlgorithms.btnPositiveClick(Sender: TObject);
begin
if rNumber > 0 then
pnlPositive.Caption:= 'Positive'
else pnlPositive.Caption:= 'Negative' ;
end;
Button [btnEven]
procedure TfrmBasicAlgorithms.btnEvenClick(Sender: TObject);
begin
if odd(iNumber) then
pnlEven.Caption:= 'Odd number'
else pnlEven.Caption:= 'Even Number';
end;
Button [btnCompleteSquare]
procedure TfrmBasicAlgorithms.btncompleteSquareClick(Sender: TObject);
begin
if iNumber > 0 then //sqrt only if number is positive
if frac(sqrt(iNumber)) = 0 then
pnCompleteSquare.Caption:= Perfect square'
else pnCompleteSquare.Caption:= 'Not perfect square'
else pnCompleteSquare.Caption:= ' Negative number';
end;
Button [btnFactors]
procedure TfrmBasicAlgorithms.btnFactorsClick(Sender: TObject);
//this procedure counts the number of factors and displays the number's factors
var
iFactors,iCounter: integer;
sFactors: string;
begin
//initialize
sFactors:= '1'; //wants to build a string to display factors next to each other
iFactors:= 2; //always has at least 2 factors
INFORMATION TECHNOLOGY | Delphi Study Guide | 17
//loop to see which numbers are factors
for iCounter:= 2 to iNumber div 2 do
//if numbers are divided and no remainder = factor
if iNumber mod iCounter = 0 then
begin
inc(iFactors); //increase the number of factors
//add to string for display
sFactors:= sFactors + ' ' + IntToStr(iCounter);
end;
//display only once therefor outside the loop
lblFactors.Caption:= 'NUMBER of factors of ' + IntToStr(iNumber) +
' is: ' + IntToStr(iFactors) + #13 + 'FACTORS:' + #13+
sFactors + ' '+ IntToStr(iNumber);
end;
Button [btnMultiple]
procedure TfrmBasicAlgorithms.btnMultipleClick(Sender: TObject);
//this procedure displays a specific number of multiples of a number
var
iMultiples,iCounter: integer;
sMultiples: string;
begin
//initialize
iMultiples:= iNumber ; //number itself is always first multiple
sMultiples:= IntToStr(iNumber); //start a string to display
for iCounter:= 2 to 10 do //loop to display number of multiples
// build string
sMultiples:= sMultiples + ' ' + IntToStr(iCounter * iNumber);
//display the string with multiples
lblMultiple.Caption:= '10 Multiples of ' + IntToStr(iNumber) + #13 + sMultiples;
end;
Button [btnDivisible]
procedure TfrmBasicAlgorithms.btnDivisibleClick(Sender: TObject);
//This procedure tests for divisibility of numbers
var
iNumber2: integer;
begin
iNumber2:= strtoint(InputBox('Enter a Number','eg 10','10'));
if iNumber mod iNumber2 = 0 then
pnlDivisible.Caption:= IntToStr(iNumber) + ' is divisible by ' + IntToStr(iNumber2);
if iNumber2 mod iNumber = 0 then
pnlDivisible.Caption:= IntToStr(iNumber2) + ' is divisible by ' + IntToStr(iNumber);
if (iNumber mod iNumber2 <> 0) and (iNumber2 mod iNumber <> 0) then
pnlDivisible.Caption:= ' No divisibility ';
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 18
Button [btnUnknown]
procedure TfrmBasicAlgorithms.btnUnknownClick(Sender: TObject);
//in this procedure an unknown number of numbers(values) are entered and
// the numbers are displayed below each other as well as the sum, average and product
var
iHowManyNumbers, iSum,iProduct: integer;
rAverage: real;
begin
//ALWAYS give initial values = initialize
iSum:= 0;
iHowManyNumbers:= 0;
iProduct:= 1;
//input
iNumber:= strtoint(InputBox('Enter a number','0 to stop','3'));
//loop for unknown number of numbers - loop stop if 0 is entered
while iNumber <> 0 do
begin
redOutput.Lines.Add(IntToStr(iNumber)); //display number
inc(iSum,iNumber); //Increase the total sum of numbers
inc(iHowManyNumbers); //Increase the number of numbers entered
iProduct:= iProduct * iNumber; //determine the product of the numbers
//get the next number
iNumber:= strtoint(InputBox('Enter a number','0 to stop','3'));
end; //while
//displays all summary values -- only once = out of loop
redOutput.Lines.Add('The sum is:' + IntToStr(iSum));
redOutput.Lines.Add('Average ' + FloatToStr(iSum/iHowManyNumbers));
redOutput.Lines.Add('Product ' + IntToStr(iProduct));
end;
Button [btnStatistics]
procedure TfrmBasicAlgorithms.btnStatisticsClick(Sender: TObject);
//this procedure enters an unknown number of numbers (values) and
//displays the numbers below each other as well as the largest and smallest
var
iLarge,iSmall: integer;
begin
//get input for first number
iNumber:= strtoint(InputBox('Enter a Number','0 to stop','3'));
//allocate first value to large and small variables
iLarge:= iNumber;
iSmall:= iNumber;
//loop for unknown number of numbers - loop stop if 0 is entered
while iNumber <> 0 do
begin
redOutput.Lines.Add(IntToStr(iNumber)); //display number
if iNumber < iSmall then //determine if it is smaller than the smallest
iSmall:= iNumber; //save new smallest number
if iNumber > iLarge then //determine if it is larger than the largest
INFORMATION TECHNOLOGY | Delphi Study Guide | 19
iLarge:= iNumber; //save new biggest number
//get input for next number
iNumber:= strtoint(InputBox('Enter a Number','0 to stop','3'));
end;
//displays all summary values -- only once = out of loop
redOutput.Lines.Add('The largest number is: ' + IntToStr(iLarge));
redOutput.Lines.Add('The smallest number is: ' + IntToStr(iSmall));
end;
Button [btnPrimeNumber]
procedure TfrmBasicAlgorithms.btnPrimeNumbersClick(Sender: TObject);
//this procedure displays ALL the prime numbers < than a specific number
var
iCounter,iPrimeNumber,ifactors: integer;
begin
//test for prime numbers
for iPrimeNumber:= 2 to iNumber do //1 is not a prime number hence starts at 2
begin
iFactors:= 0;
for iCounter:= 2 to iPrimeNumber div 2 do //start at 2 because 1 is a factor
if iPrimeNumber mod iCounter = 0 then
inc(iFactors);
//if a number has only 2 factors then it is prime and displays the number
//didn't look at 1 and the test number in the for - so factors are 0
if iFactors = 0 then
redPrimeNumbers.Lines.Add (IntToStr(iPrimeNumber));
end;
end;
Button [btnLCD]
procedure TfrmBasicAlgorithms.btnLCDClick(Sender: TObject);
var
Number1, Number2 , LCD,k: Integer;
begin
Number1:= StrToInt(InputBox('Enter a number','','18')) ;
Number2:= StrToInt(InputBox('Enter a second number','','15')) ;
for k:= 1 to Number1 do //Repeat from 1 to any one of the 2 numbers
//if both numbers are divisible
if (Number1 mod k = 0) and (Number2 mod k = 0) then
//remember (store) the number that can divide into both original numbers
LCD:= k;
//display
MessageDlg('Number 1 ' + IntToStr(Number1) + #13 + 'Number 2 ' +
IntToStr(Number2) + #13 + 'LCD ' + IntToStr(LCD), mtInformation,[mbOK],0);
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 20
Button [btnLCM]
procedure TfrmBasicAlgorithms.btnLCMClick(Sender: TObject);
var
Number1, Number2 , LCM,k: Integer;
begin
Number1:= StrToInt(InputBox('Enter a number','','18')) ;
Number2:= StrToInt(InputBox('Enter a second number','','15')) ;
k:= 1; //loop to multiply
repeat
LCM:= Number1 * k;
Inc(k);
until LCM mod Number2 = 0; //if divisible....
//Display
MessageDlg('Number 1 ' + IntToStr(Number1) + #13 + 'Number 2 ' +
IntToStr(Number2) + #13 + 'LCM ' + IntToStr(LCM),
mtInformation,[mbOK],0);
end;
Button [btnSwap]
procedure TfrmBasicAlgorithms.btnSwapClick(Sender: TObject);
//this procedure swap two numbers
//the same instructions are used to swap strings and characters
var
iNumber1,iNumber2: Integer;
iSwap: Integer; //declare a temp variable
begin
//input
iNumber1:= StrToInt(ledNumber1.Text);
iNumber2:= StrToInt(ledNumber2.Text);
//process
iSwap:= iNumber1;
iNumber1:= iNumber2;
iNumber2:= iSwap;
//display
ledNumber1.Text:= IntToStr(iNumber1);
ledNumber2.Text:= IntToStr(iNumber2);
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 21
Mathematical functions (built-in)
Assignment
The purpose of this assignment is to display the output for the different mathematical
built-in functions to be used (and learn by heart) in solutions when needed. Every button
has the caption of the function that must be used to display / see the result. The result is
displayed on the panel next to the appropriate button.
The following GUI is provided:
Functions must be part of a statement – although Delphi accepts the function as a
single statement the return value will NOT be stored anywhere and will not be accessible
later. The stored value of the variable DOES NOT change.
Write code to do the following:
Button [btnAbs]
Always returns the positive value of the input number in sedInteger.value
Button [btnDiv]
Divide the input value sedInteger.value with a user entered number and returns ONLY
the integer part of the result – function can only be applied to integer values.
Button [btnTrunc]
Always returns the integer part of the input number edtRealNumber.text as an integer
value – will normally apply this function to a real value to change to an integer value.
Button [btnMod]
Always returns the remainder part of the input number sedInteger.value when divided
by the user entered denominator - can only apply to integer values.
Button [btnOdd]
Test whether a number is odd and will return a -1 (or True) if it is an odd number else the
return value will be 0 (False).
INFORMATION TECHNOLOGY | Delphi Study Guide | 22
Button [btnPi]
Returns the value of pi.
Button [btnCeil]
Always returns a value rounded upwards to the next integer - obtain the nearest integer
greater than or equal to the input value edtRealNumber.text.
Button [btnFloor]
Always returns a value rounded downwards to the previous integer - obtain the nearest
integer equal or less than the input value edtRealNumber.text.
Button [btnRound]
Returns the input value edtRealNumber.text, rounded to the closest integer , and if the
number falls exactly between two integers the number is rounded off to an even number,
e.g 5.5 will become 6 but 4.5 will become 4.
Button [btnRoundto]
Returns the input value edtRealNumber.text rounded to the specified power of 10
Button [btnRandomRange]
Generates a Random Integer number within the given range with the upper limit
excluded. This example generates a Random number between 10 and 19 (both
included).
Button [btnRandom]
Generates a random integer number in a range starting at 0 and excluding the indicated
limit.To include the limit and exclude 0: add 1.
Button [btnRandom2]
Generates a Random real number smaller than 1 / decimal number.
Button [btnFrac]
Returns the fractional part of the input value edtRealNumber (a real number).
Button [btnInt]
Returns the integer part of the input value edtRealNumber (a real number) as a real
number.
Button [btnPower]
Returns the value from sedInteger raised to the power of a user entered input. Result is
always real.
Button [btnSqrt]
Returns the square root of the value from sedInteger. Result is always real.
Button [btnSqr]
Returns the square of the value from sedInteger.
INFORMATION TECHNOLOGY | Delphi Study Guide | 23
Procedures stands on its own – the stored value of the variable CHANGES when the
procedure is applied / executed.
Button [btnInc]
Increases the variable’s value (sedInteger.value) with one. Can only apply to integer /
char values.
Button [btnInc +]
Increases the variable’s value (sedInteger.value) with the user entered input value. Can
only apply to integer / char values.
Button [btnDec]
Decreases the variable’s value (sedInteger.value) with one. Can only apply to integer /
char values.
Button [btnDec +]
Decreases the variable’s value (sedInteger.value) with the user entered input value.
Can only apply to integer / char values.
REMARKS: The conversions are necessary for retrieving and displaying the numbers.
The values entered in the provided spin edit and edit box are used in the
solution.
To use a function ALWAYS start with the function name followed by brackets.
The value to use with the function will appear in the brackets of the function.
E.G. use the IntToStr function: IntToStr()
apply the funtion on a value: IntToStr(iNumber)
Solution
Button [btnAbs]
procedure TfrmMathematicalFunctions.btnAbsClick(Sender: TObject);
begin
//always returns the positive value of a number
pnlAbs.Caption:= IntToStr(abs(sedInteger.Value));
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 24
Button [btnDIV]
procedure TfrmMathematicalFunctions.btnDivClick(Sender: TObject);
var
iInputValue: integer;
begin
//Integer division - no decimals
iInputValue:= StrToInt(InputBox(' Divide ' + sedInteger.text,' by ','5')); //value to divide
with
pnlDiv.Caption:= IntToStr( sedInteger.Value div iInputValue );
end;
Button [btnTRUNC]
procedure TfrmMathematicalFunctions.btnTruncClick(Sender: TObject);
var
rInput: real ;
begin
rInput:= StrToFloat(edtRealNumber.Text);
//change a real number to an integer by throwing away the decimal
//returns an integer value
pnlTrunc.Caption:= IntToStr(trunc(rInput));
end;
Button [btnMOD]
procedure TfrmMathematicalFunctions.btnModClick(Sender: TObject);
var
iInputValue: integer;
begin
iInputValue:= StrToInt(InputBox('Enter a denominater','','5')); //value to divide with
//Integer division = returns the remainder as answer
pnlMod.Caption:= IntToStr( sedInteger.Value mod iInputValue );
end;
Button [btnODD]
procedure TfrmMathematicalFunctions.btnOddClick(Sender: TObject);
begin
//Determine whether a number is odd or not – display a -1 if it is an odd number
pnlOdd.Caption:= BoolToStr(odd(sedInteger.Value));
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 25
Button [btnPI]
procedure TfrmMathematicalFunctions.btnPiClick(Sender: TObject);
begin
//Display the value of Pi
pnlPi.Caption:= FloatToStr(pi);
end;
Button [btnCEILING]
procedure TfrmMathematicalFunctions.btnCeilingClick(Sender: TObject);
begin
//Always round up to the TOP nearest integer
pnlCeiling.Caption:= FloatToStr(ceil(StrToFloat(edtRealNumber.Text)));
end;
Button [btnFLOOR]
procedure TfrmMathematicalFunctions.btnFloorClick(Sender: TObject);
begin
//Always round down to the BOTTOM nearest integer
pnlfloor.Caption:= IntToStr(floor(StrToFloat(edtRealNumber.Text)));
end;
Button [btnROUND]
procedure TfrmMathematicalFunctions.btnRoundClick(Sender: TObject);
begin
//normal mathematical rounding
pnlRound.Caption:= FloatToStr(round(StrToFloat(edtRealNumber.Text)));
end;
Button [btnROUNDTO]
procedure TfrmMathematicalFunctions.btnRoundtoClick(Sender: TObject);
var
iInputValue: integer;
begin
iInputValue:= StrToInt(InputBox('Enter power of 10 to round to','','5'));
//round off to the place specified in the input box
pnlRoundto.Caption:=
FloatToStr(roundto(StrToFloat(edtRealNumber.Text),iInputValue));
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 26
[RANDOMRANGE]
procedure TfrmMathematicalFunctions.btnRangeClick(Sender: TObject);
begin
//get a Random number from 10 – 19
pnlRange.Caption:= IntToStr(Randomrange(10,20));
//NOTE: upper limit is excluded
end;
Button [btnRANDOM]
procedure TfrmMathematicalFunctions.btnRandomClick(Sender: TObject);
begin
//generates an integer Random number
pnlRandom.Caption:= IntToStr(Random(sedInteger.Value));
//NOTE: value entered in sedInteger is excluded
end;
[RANDOM < 1]
procedure TfrmMathematicalFunctions.btnRandom2Click(Sender: TObject);
begin
//get a Random number < 0 (decimal)
pnlRandom.Caption:= FloatToStr(Random());
end;
Button [btnFRAC]
procedure TfrmMathematicalFunctions.btnFracClick(Sender: TObject);
begin
//Returns only the decimal/fraction part = still a real number
pnlFrac.Caption:= FloatToStr(frac(StrToFloat(edtRealNumber.Text)));
end;
Button [btnINT]
procedure TfrmMathematicalFunctions.btnIntClick(Sender: TObject);
begin
// NOTE:returns only the integer part of a value = remains a real number
pnlInt.Caption:= FloatToStr(int(StrToFloat(edtRealNumber.Text)));
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 27
Button [btnPOWER]
procedure TfrmMathematicalFunctions.btnPowerClick(Sender: TObject);
var
iInputValue: integer;
begin
iInputValue:= StrToInt(InputBox('Enter a power','','5'));
//NOTE: Raise the number to the power entered by user – always a real answer
pnlPower.Caption:= FloatToStr(power(sedInteger.Value,iInputValue));
end;
Button [btnSQRT]
procedure TfrmMathematicalFunctions.btnSqrtClick(Sender: TObject);
begin
//calculate the square root of a value – always a real answer
if sedInteger.Value > 0 then
pnlSqrt.Caption:= FloatToStrF(sqrt(sedInteger.Value),fffixed,10,2)
else pnlsqrt.Caption:= 'Square root of negative numbers not allowed’;
end;
Button [btnSQR]
procedure TfrmMathematicalFunctions.btnSqrClick(Sender: TObject);
begin
//calculate the square of a value
pnlSqr.Caption:= IntToStr(sqr(sedInteger.Value));
end;
Button [btnINC]
procedure TfrmMathematicalFunctions.btnIncClick(Sender: TObject);
//NOTE: can only be used with integer and char values
var
iNumber: integer;
begin
//Increase a value by 1
iNumber:= sedInteger.Value;
inc(iNumber); // iNumber:= iNumber + 1;
pnlInc.Caption:= IntToStr(iNumber);
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 28
[INC +]
procedure TfrmMathematicalFunctions.btnIncMoreClick(Sender: TObject);
var
iNumber: integer;
iInputValue: integer;
begin
iInputValue:= StrToInt(InputBox('Enter a value to add to '+sedInteger.Text,'','5')); //
increase value
//Increase a value by any specified value
iNumber:= sedInteger.Value;
inc(iNumber,iInCreaseValue);
pnlincMore.Caption:= IntToStr(iNumber);
end;
Button [btnDEC]
procedure TfrmMathematicalFunctions.btnDecClick(Sender: TObject);
//NOTE: can only be used with integer and char values
var
iNumber: integer;
begin
//Decrease a value by 1
iNumber:= sedInteger.Value;
dec(iNumber); // iNumber:= iNumber -1;
pnlDec.Caption:= IntToStr(iNumber);
end;
[DEC +]
procedure TfrmMathematicalFunctions.btnDecMoreClick(Sender: TObject);
var
iInputValue,iNumber: integer;
begin
iInputValue:= StrToInt(InputBox('Enter a value to decrease from '+sedinteger.Text,' ','5'));
//Decrease a value by any specified value
iNumber:= sedInteger.Value;
dec(iNumber,iDecreaseValue);
pnlDecMore.Caption:= IntToStr(iNumber);
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 29
Binary logic example
Assignment
Retrieve a user entered decimal number from the edit component and display the
decimal number converted to a binary number.
Solution
procedure TForm1.btnDToBClick(Sender: TObject);
var
iRemainder,iNumber: integer;
rNumber,rBinary: real;
sBinary: string;
begin
rNumber:= StrToFloat(edtInput.Text); //retrieve value
iNumber:= trunc(rNumber); //integer part
sBinary:= ''; //empty string to build binary number
while iNumber <> 0 do //successive division until 0
begin
iRemainder:= iNumber mod 2; //find the remainder
iNumber:= iNumber div 2; //get next integer value
sBinary:= IntToStr(iRemainder) + sBinary; //add remainder to string
end;
sBinary:= sBinary + '.'; //decimal separator
rNumber:= frac(rNumber); //fraction part
while frac(rNumber) <> 0 do //successive multiplication until no fractions remain
begin
rNumber:= rNumber *2; //multiply by 2
rBinary:= int(rNumber); //get integer part of number
rNumber:= rNumber - int(rNumber); //subtract the integer part to keep only fraction
sBinary:= sBinary + IntToStr(trunc(rBinary)); //add to binary string
end;
edtOutput.Text:= sBinary; //display
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 30
String handling
Basic built-in functions and procedures
Func/ proc Explanation Example
Length returns the length iNumber:= Length(sString);
of a string
Pos returns the first iNumber:= pos(subString,sString);
position of a
substring in a string
Upcase change a single cChar:= upcase(sString[index]);
character to capital
letter
Uppercase change a string to sString:= uppercase(sString);
capitals
Lowercase change a string to sString:= lowercase(sString);
lowercase
[] Refer to a single cChar:= sString[index]
character in a string
Insert Insert a substring Insert(subString,sString,insertPosition);
into a string
Copy copy a part of a Copy(sString,StartPosition,NumberCharacters);
string
Delete delete a part of a Delete(sString,
string StartPosition,NumberCharacters);
Basic string handling algorithms
Assignment
The following GUI is provided:
INFORMATION TECHNOLOGY | Delphi Study Guide | 31
Write code to do the following:
Button [Reverse]
Reverse and display the reversed input string without the name of the person.
Example of output:
Button [Reverse every word]
Reverse and display every word in the input string.
Example of output:
Button [Remove special characters]
Remove all special characters (except spaces) from the input string. Display the string
without special characters.
Example of output:
Button [Remove all vowels]
Remove all vowels from the input string. Display the string without any vowels.
Example of output:
Button [Remove all consonants]
Replace each consonant with the next letter in the alphabet – e.g. B becomes a C, F a G
etc. Z must become an A.
Example of output:
INFORMATION TECHNOLOGY | Delphi Study Guide | 32
Button [Capital Letter]
Change the first letter of every word in the sentence to a capital.
Example of output:
Button [Build a string]
Write code to create a string consisting of three pairs of two Random characters.
Every pair must have a number (0 – 9) and an alphabetical character (A-F).
Separate the pairs with a “flower” (character 1421) e.g. 9A֍D4֍F1
Ensure that there is no duplicate Random character in the final string.
Example of output:
Button [Count words]
Count and display the number of words in the input string. A word consists of at least 3
characters.
Example of output:
Button [Palindrome?]
A palindrome is a word or sentence that is the same whether it is read from left to right or
right to left excluding any punctuation, e.g. madam.
Write code to receive an input from the user and test whether the input string is a
palindrome or not.
Examples of palindromes: Example of output:
race
car
INFORMATION TECHNOLOGY | Delphi Study Guide | 33
Button [Application 1]
Apply the knowledge obtained in the previous buttons.
Receive a code (a string) from a user and -
- determine if there is at least one number (digit) in the code
- if there is no number in the code: replace all vowels with numbers 1 – 5, where A = 1,
E = 2, I = 3, O = 4 and U = 5
- determine if there is still no digit and if not: add a 2 digit number Random number, less
than 100, at the end of the code string
Example of output:
Button [Application 2]
Apply the knowledge obtained in the previous buttons.
Enter a word or single character in the original input string which must be replaced and
the word that will replace the entered word or single character, in the provided edit
boxes.
Example of output:
Button [Change input string]
Get a new input string to use in the application.
Display the new input string on the pnlInputString component.
Example of output:
Button [Challenge]
Add a button and panel to display the input string in Morse code.
Output if input is ‘I did, did I?’
INFORMATION TECHNOLOGY | Delphi Study Guide | 34
Example of output:
The following GUI is provided
Button [Birth date]
Extract Bill Gates’ birthdate from the original input sentence and display Bill Gates’
birthdate on the pnlBirthDate component.
Example of output:
Button [Age]
Determine Bill’s exact age using the system date. Display his exact age and his age
rounded to the next year.
Example of output:
Button [Same birthday?]
Enter your birthdate in a dialogue box, determine and display whether your birthdate,
excluding the year, is same as Bill’s.
INFORMATION TECHNOLOGY | Delphi Study Guide | 35
Example of output:
Button [Past_Previous]
Use date functions to display yesterday’s, today’s and tomorrow’s dates.
Example of output:
Button [Day of year?]
Use date functions to display the day of the week, month and year on which Bill was
born.
Example of output:
Button [Validation]
Validate and display if the user input for the day and month of a birthdate are digits
(numbers) and valid.
Example of output:
INFORMATION TECHNOLOGY | Delphi Study Guide | 36
Solution
The following global (form unit) variables are declared:
private
sInput: string;
sTempSentence: string;
[onActivate]:
procedure TfrmCodeWords.FormActivate(Sender: TObject);
begin
WindowState:= wsMaximized;
sInput:= 'The computer was born to solve problems that did not exist before.';
end;
Button [Reverse]
procedure TfrmCodeWords.btnReverseSentenceClick(Sender: TObject);
var
sReverseSentence: string;
I: integer;
begin
sReverseSentence:= ''; //start with empty string to build reverse string
for I:= length(sInput) downto 1 do //start at end of string to reverse
sReverseSentence:= sReverseSentence + sInput[I]; //add each character
pnlReverse.Caption:= sReverseSentence; //display reversed string
end;
Button [Reverse every word]
procedure TfrmCodeWords.btnReverseEveryWordClick(Sender: TObject);
var
sSentence,sReverse: string;
i: byte;
begin
sReverse:= ''; //start with empty temporary string
sSentence:= InputBox('Enter a sentence','','It is Monday') + ' ';
//add space to include last word
while pos(' ',sSentence)> 0 do //test if there is still a space = another word
begin
for i:= pos(' ',sSentence)-1 downto 1 do //reverse the word
sReverse:= sReverse + sSentence[i]; //add to temp string
sReverse:= sReverse + ' '; //add a space
delete(sSentence,1,pos(' ',sSentence)); //delete the word
end;
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 37
Button [Remove special characters]
procedure TfrmCodeWords.BtnRemoveSpecialClick(Sender: TObject);
var
sTempSentence: string;
I: integer;
begin
sTempSentence:= sInput; //use temporary sentence
for I:= length(sTempSentence) downto 1 do //loop through all characters in sentence
if not (upcase(sTempSentence[I]) in ['A'..'Z']) then //if not an alphabetical character
delete(sTempSentence,I,1); //delete the character
pnlSpecial.Caption:= sTempSentence;
end;
Button [Remove all vowels]
procedure TfrmCodeWords.btnRemoveVowelsClick(Sender: TObject);
const
vowels = 'AEOUI';
var
k: byte;
sTempSentence: string;
begin
sTempSentence:= sInput;
for k:= length(sTempSentence) downto 1 do
//loop through the whole sentence from last to first character
if pos(upcase(sTempSentence[k]),vowels) > 0 then //if the character is a vowel
delete(sTempSentence,k,1); //delete it
pnlNoVowels.Caption:= sTempSentence;
end;
Button [Remove all consonants]
procedure TfrmCodeWords.btnReplaceConsonantsClick(Sender: TObject);
const
Consonants = 'BCDFGHJKLMNPQRSTVWXYZ'; //declare consonants constant variable
var
I: Integer;
sTempSentence: string;
begin
sTempSentence:= sInput;
for I:= 1 to Length(sTempSentence) do //loop through string
if Pos(UpCase(sTempSentence[I]),consonants) > 0 then //tests for consonants
case sTempSentence[I] of //if letter is a z/Z
'z': sTempSentence[I]:= 'a';
'Z': sTempSentence[I]:= 'A';
else
INFORMATION TECHNOLOGY | Delphi Study Guide | 38
sTempSentence[I]:= Char(Ord(sTempSentence[I])+1); //next letter
end;
pnlConsonants.Caption:= sTempSentence;
end;
Button [Capital Letter]
procedure TfrmCodeWords.btnCapitalLetterClick(Sender: TObject);
var
k: byte;
sTempSentence: string;
begin
sTempSentence:= sInput;
sTempSentence[1]:= upcase(sTempSentence[1]);
//make first letter / character a capital letter
for k:= 1 to length(sTempSentence) do //loop through the length of sentence
if sTempSentence[k] = ' ' then //if it's a space
sTempSentence[k+1]:= upcase( sTempSentence[k+1]);
//capitalize the (one) character after the space
pnlCapitalLetter.Caption:= sTempSentence;
end;
Button [Build a string]
procedure TfrmCodeWords.btnBuildStringClick(Sender: TObject);
//the pairs can be any order but must contain a number and a letter
//e.g. 9A֍D4֍F1
const
characters = 'ABCDEF';
numbers = '0123456789';
var
I,iType,iRandom: Integer;
sRandom: string;
begin
sRandom:= ''; //start with an empty string;
for I:= 1 to 3 do //must have 3 pairs
begin
iType:= Random(2); //choose whether numbers or characters are first
if iType = 0 then //if characters are first
begin
Repeat
iRandom:= Randomrange(1,7); //choose Random position
until pos(characters[iRandom],sRandom) = 0; // to ensure no duplicates
sRandom:= sRandom + characters[iRandom]; //add Random character
Repeat
iRandom:= Randomrange(1,11); //choose Random position
INFORMATION TECHNOLOGY | Delphi Study Guide | 39
until pos(numbers[iRandom],sRandom) = 0; // to ensure no duplicates
sRandom:= sRandom + numbers[iRandom] + Chr(1421);
end //if type = 0
else //reverse the process
begin
Repeat
iRandom:= Randomrange(1,11);
Until pos(numbers[iRandom],sRandom) = 0; // to ensure no duplicates
sRandom:= sRandom + numbers[iRandom];
Repeat
iRandom:= Randomrange(1,7);
Until pos(characters[iRandom],sRandom) = 0; // to ensure no duplicates
sRandom:= sRandom + characters[iRandom] + Chr(1421);
end
end;
Delete(sRandom,9,1); //delete the last ֍
pnlString.Caption:= sRandom; //display
end;
Button [Count number of words]
procedure TfrmCodeWords.btnCountWordsClick(Sender: TObject);
var
iNumberWords: byte;
sTempSentence: string;
begin
sTempSentence:= sInput + ' '; //to count last word
iNumberWords:= 0; //initialize the counter
while pos(' ',sTempSentence ) > 0 do //see if there is another space in sentence
begin
if pos(' ',sTempSentence ) > 3 then //Test for words with more than 2 characters
inc(iNumberWords);
delete(sTempSentence ,1,pos(' ',sTempSentence )); //delete word already counted
end;
pnlWords.Caption:= IntToStr(iNumberWords);
end;
Button [Palindrome?]
procedure TfrmCodeWords.btnPalindromeClick(Sender: TObject);
var
k: byte;
sTemp: string;
begin
//sInput and sTempSentence are global variables
sInput:= InputBox('Enter text to test for palindromes',' ','I did, did I?');
btnSpecial.Click; //remove special characters but not spaces
INFORMATION TECHNOLOGY | Delphi Study Guide | 40
sTemp:= ''; //unlike ' ', initialize empty string
//reverse the sentence / word
for k:= length(sTempSentence) downto 1 do
sTemp:= sTemp + sTempSentence[k];
//compare the original with temp without special characters
if sTemp = sTempSentence then
pnlPalindrome.Caption:= sInput + ' is a palindrome'
else pnlPalindrome.Caption:= sInput + ' is not a palindrome';
end;
Button [Application 1]
procedure TfrmCodeWords.btnApplication1Click(Sender: TObject);
const
Vowels = 'AEIOU'; Receive a code (a string) from a user and -
Digits = '12345'; - determine if there is at least one number (digit) in the code
- if there is no number in the code: replace all vowels with numbers 1 – 5,
where A = 1, E = 2, I = 3, O = 4 and U = 5
var - determine if there is still no digit and if not:
bValid,bValid2: boolean; add a 2 digit number Random number,
k: byte; less than 100, at the end of the code string
begin
sTempSentence:= sInput;
bValid:= false; //presume that the code word has no digits
//check if there is a number (digit) in the code
k:= 1; //counter
while not bValid and (k <= length(sTempSentence)) do
//use flag to show when digit is found
begin
if sTempSentence[k] in ['0'..'9'] //test for digit
then bValid:= true; //raise the flag – which will end the loop
inc(k); //move to next character
end; //while
//output if valid code
if bValid then
pnlApp1.Caption:= 'Valid code:)'
else begin
//if not valid - change
for k:= 1 to length(sTempSentence) do
if Pos(UpCase(sTempSentence[k]),Vowels) > 0 then
begin
sTempSentence[k]:= Digits[Pos(UpCase(sTempSentence[k]),Vowels)];
bValid:= true;
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 41
//test if it's just consonants....
if (not bValid) then
begin
sTempSentence:= sTempSentence + IntToStr(Randomrange(10,100));
end;//if not
//Display new code
pnlAfvoer.Caption:= sTempSentence;
end;//else
end;
Button [Application 2]
procedure TfrmCodeWords.btnApplication2Click(Sender: TObject);
var
Position: byte;
begin
//complete words
if length(ledSearch.Text) > 1 then
begin
sTempSentence:= ' '+sInput+ ' ' ;//to get complete words
//looking for first position
Position:= pos(uppercase(' '+ledSearch.Text+' '),uppercase(sTempSentence));
while Position >0 do //to replace all
begin
insert(ledReplace.Text,sTempSentence,Position+1); //insert new word
//get the position again
Position:= pos(uppercase( ledSearch.Text+' '),uppercase(sTempSentence));
delete(sTempSentence,Position,length(ledSearch.Text)); //delete the word
//get next position
Position:= pos(uppercase(' '+ledSearch.Text+' '),uppercase(sTempSentence));
end;
sTempSentence:= trim(sTempSentence);
//throw spaces away at beginning and end of string
sTempSentence[1]:= upcase(sTempSentence[1]); //just in case....:)
end
else begin
//single characters
sTempSentence:= sInput;
Position:= pos(uppercase(ledSearch.Text),uppercase(sTempSentence));
//get first presence
INFORMATION TECHNOLOGY | Delphi Study Guide | 42
while Position >0 do //to replace all
begin
insert(ledReplace.Text,sTempSentence,Position); //insert new character
//get the position again
Position:= pos(uppercase( ledSearch.Text),uppercase(sTempSentence));
delete(sTempSentence,Position,1); //delete character
//get next position
Position:= pos(uppercase(ledSearch.Text),uppercase(sTempSentence));
end;
end;
pnlApp2.Caption:= sTempSentence;
end;
Button [Change input string]
procedure TfrmCodeWords.btnChangeInputClick(Sender: TObject);
begin
sInput:= InputBox('Enter a new string','','What ever you want.....');
pnlInputString.Caption:= 'Input string: ' + sInput;
end;
The following global (form class) variables are declared for the date functions
form:
private
sInput: string;
sDate: string;
dBirthDate: TDate;
[onActivate]:
procedure TfrmDateFunctions.FormActivate(Sender: TObject);
begin
ShortDateFormat:= 'dd/mm/yyyy';
sInput:= 'Success is a lousy teacher. It seduces smart people into thinking they can`t
lose. (Bill Gates - 28/10/1955)';
end;
Button [Age]
procedure TfrmDateFunctions.btnAgeClick(Sender: TObject);
var
rAge: Real;
begin
dBirthDate:= StrToDate(sDate);
rAge:= (date - dBirthDate)/365 ;
//DaysBetween(date,dbirthDate)/365 or YearsBetween(date,dbirthDate) can also be
used
INFORMATION TECHNOLOGY | Delphi Study Guide | 43
pnlAge.Caption:= FloatToStr(rAge) +' = ' + FloatToStr(Ceil(rAge)) + ' (in year ' +
IntToStr(YearOf(date)) +')';
end;
Button [Birth date]
procedure TfrmDateFunctions.btnBirthDateClick(Sender: TObject);
begin
sDate:= Copy(sInput,Pos('-',sInput)+2,10);
// a way of extracting only the birthdate
pnlBirthDate.Caption:= sDate;
end;
Button [Past_Previous]
procedure TfrmDateFunctions.btnPastPrevClick(Sender: TObject);
begin
pnlPastPrev.Caption:= 'Yesterday`s date: ' + DateToStr(Yesterday) + ' ' +
'Today`s date: ' + DateToStr(Today) + ' ' +
'Tomorrow`s date: ' + DateToStr(Tomorrow);
end;
Button [Day of year?]
procedure TfrmDateFunctions.btnSameDayClick(Sender: TObject);
var
sBirthDay: string;
iAge: integer;
begin
sBirthDay:= '05/12/2002';
InputQuery('Enter your birthday ','',sBirthDay) ;
if DayOf(dBirthDate)<> StrToInt(sBirthDay[1] + sBirthDay[2]) then
// A way of extracting characters from a string
pnlSameDay.Caption:= 'Day is NOT the same'
else if MonthOf(dBirthDate)<> StrToInt(sBirthDay[4] + sBirthDay[5]) then
pnlSameDay.Caption:= 'Month is NOT the same'
else begin
pnlSameDay.Caption:= 'Congrat:) you and Bill are twins';
iAge:= YearOf(StrToDate(sBirthDay)) - YearOf(dBirthDate);
pnlSameDay.Caption:= pnlSameDay.Caption + ' he is '+
IntToStr(iAge) + ' years older than you';
end;
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 44
Button [Validation]
procedure TfrmDateFunctions.btnValidationClick(Sender: TObject);
var
sBirthDay: string;
iDay,iMonth,iYear: Integer;
bDay,bMonth: Boolean;
begin
//assume the date is correct
bDay:= True;
bMonth:= True;
//get birthdate, extract and convert to get day and month
sBirthDay:= InputBox('Enter your birthday ','','31/12/2000');
if ( not TryStrToInt(Copy(sBirthDay,4,2),iMonth) ) or //cannot convert to integer
( not TryStrToInt(Copy(sBirthDay,1,2),iDay) ) or
( not TryStrToInt(Copy(sBirthDay,7,4),iYear) ) then
pnlValidation.Caption:= 'There are invalid character(s) in date'
else Begin
if iMonth in [1..12] then //test month
case iMonth of
1,3,5,7,8,10,12: if not( iDay in [1..31]) then //test day
bDay:= False;
2: if IsLeapYear(iYear) and not( iDay in [1..29]) then
bDay:= False
else if not( iDay in [1..28]) then
bDay:= False;
4,6,9,11: if not( iDay in [1..30]) then
bDay:= False;
end
else bMonth:= False;
if bDay and bMonth then //display appropriate message
pnlValidation.Caption:= 'Valid date'
else if not bDay and not bMonth then
pnlValidation.Caption:= 'Invalid date'
else if not bDay then
pnlValidation.Caption:= 'Invalid day'
else if not bMonth then
pnlValidation.Caption:= 'Invalid month' ;
End;
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 45
procedure TfrmDateFunctions.btnWeekDaysClick(Sender: TObject);
var
sDay: string;
begin
//if you don't know the function
//case dayofweek(Date) of
//1: sDay:= 'Sunday';
//2: sDay:= 'Monday';
//3: sDay:= 'Tuesday';
//4: sDay:= 'Wednesday';
//5: sDay:= 'Thursday';
//6: sDay:= 'Fryday';
//7: sDay:= 'Saturday';
//end;
//pnlWeekDays.Caption:= 'Today is ' + sDay;
pnlWeekDays.Caption:= 'Today is ' + LongDayNames[dayofweek(Date)];
pnlWeekDays.Caption:= 'Bill is born on' + #13+ ' the ' +
IntToStr(DayOfTheYear(dBirthDate))
+' st/th day of the year '
+ #13 + ' which was a ' + LongDayNames[dayofweek(dBirthDate)] + #13 +
' in ' + LongMonthNames[MonthOfTheYear(dBirthDate)] ;
end;
Text files
Basic text file instructions
Assignfile() connect user file name (internal) to file name on disc (external)
Assignfile(tfile,’filenameOnDisc.txt’);
Reset() Open file to read content – place content of file in RAM
Reset(tfile);
Rewrite() Create the file / wipe content of a file and the file curser is placed on the
first line of the file – information can be written to the file
Rewrite(tfile);
Append() Open the file to add content at the bottom of the file
Append(tfile);
Readln() Read a single line from a text file and store the information in a variable
Readln(tfile,sVariable)
Writeln() Write a single line to a text file
Writeln(tfile,sVariable)
Eof() end of file marker
While not EOF(tfile) do //to read ALL the lines
CloseFile() Release RAM space and update file content on the disc
Closefile(tfile);
INFORMATION TECHNOLOGY | Delphi Study Guide | 46
Try except test if file exists – must untick in Debugger options
Try
Reset(tFile)
Except
Showmessage(‘File doesn`t exist’);
FileExists test if file exists
If not FileExists(‘filename.extention’)
Then Showmessage(‘File doesn`t exist’);
Assignment
Some South African artists’ work is stored in a text file Artists.txt. The content of the file
is in the following format: name of artist#Surname of artist#name of work#price of work
The artist names are stored in a text file ArtistNames.txt.
First number of lines in the text file:
The following GUI is provided:
Write code to do the following:
[OnActive] event handler
INFORMATION TECHNOLOGY | Delphi Study Guide | 47
Display the artist names in the combo box cmbArtist when the program executes.
Button [Display text file's content]
Display the content of the Artists.txt text file in the redDisplay component.
Button [Display text file's content in columns]
Display the content of the Artists.txt text file in columns in the redDisplay component.
Add the following headings to the columns: Name Surname Artworik’s name Price
NOTE: you can use the following tab stops: 100, 180, 380
INFORMATION TECHNOLOGY | Delphi Study Guide | 48
Button [Add an artist's work]
Add an artist’s new work to the Artists.txt text file in the following format.
E.g. Hercules#Human#Untitled 8 (2011)#@
NOTE: it can be any piece.....
Add the artist’s name to the ArtistNames.txt file ONLY if the artist’s name is not already
in the file.
Button [Display a certain artist's work]
Select an artist name in the combo box and display all the work for the selected artist in
the provided output component.
Button [Write a certain artist's work to a text file]
Select an artist name in the combo box and write all the work for the selected artist to a
text file with the artist’s name and surname as file name.
INFORMATION TECHNOLOGY | Delphi Study Guide | 49
Button [Display all works with no price]
Display all the art in the text file Artists.txt which has no price written to the file.
Solution
[OnActive]
procedure TfrmArtists.FormActivate(Sender: TObject);
var
tFile: textfile; //declare internal / RAM file name
sOneName: string; //to store one line's content
begin
assignfile(tFile,'ArtistNames.txt'); //assign internal file name to external file name
if FileExists(‘ArtistNames.txt’) //test if file exists
then begin
Reset(tFile); //open file to read
while not eof(tFile) do //loop through all lines in file
begin
readln(tFile,sOneName); //read one line in the file
cmbArtist.Items.Add(sOneName); //add the content of the line to the combo box
end;
CloseFile(tFile); //close the file
end;
end;
Button [Display text file's content]
procedure TfrmArtists.btnDisplayClick(Sender: TObject);
var
tFile: TextFile;
sLine: string;
begin
if not FileExists('Artists.txt') then //test that file exist
MessageDlg('The file does not exist',mtError,[mbOK],0) //message if not
INFORMATION TECHNOLOGY | Delphi Study Guide | 50
else begin
AssignFile(tFile,'Artists.txt'); //"Say" with which file you work on the hard drive
Reset(tFile); //open file for reading
redDisplay.Clear;
while not Eof(tFile) do //loop to read whole file
begin
Readln(tFile,sLine); //read a single line
redDisplay.Lines.Add(sLine) ; //display the single line
end;
CloseFile(tFile); //close the file
end;
end;
Button [Display text file's content in columns]
procedure TfrmArtists.btnDisplayColumnsClick(Sender: TObject);
var
tFile: TextFile;
sLine,Name,Surname,Artwork: string;
Price: real;
begin
redDisplay.Clear;
redDisplay.Lines.Add('Name'+#9 + 'Surname'+ #9 + 'Artwork' + #9 + 'Price');
//tabs are not set!!!!
if not FileExists('Artists.txt') then //test that file exist
MessageDlg('Die lêer bestaan nie',mtError,[mbOK],0) //message if not
else begin
AssignFile(tFile,'Artists.txt'); //"Say" with which file you work
INFORMATION TECHNOLOGY | Delphi Study Guide | 51
Reset(tFile); //open file for reading
while not Eof(tFile) do //loop to read whole file
begin
Readln(tFile,sLine); //read a single line
//copy from sLine, start at one to one character in front of #
Name:= Copy(sLine,1,Pos('#',sLine)-1);
Delete(sLine,1,Pos('#',sLine)); //delete from sLine from first character to #
Surname:= Copy(sLine,1,Pos('#',sLine)-1);
Delete(sLine,1,Pos('#',sLine));
Artwork:= Copy(sLine,1,Pos('#',sLine)-1);
Delete(sLine,1,Pos('@',sLine));
while Pos(' ',sLine) > 0 do //Look for a space(s) in the line
Delete(sLine,Pos(' ',sLine),1); //delete space
if Length(sLine) > 0 then //test if there is a value - may also use TryStrToFloat...
Price:= StrToFloat(sLine) //"convert"
else Price:= 0; //else there is no price
redDisplay.Lines.Add(Name+#9 + Surname+ #9 + Artwork +
#9 + FloatToStrF(Price,ffcurrency,10,2)); //display
end;
CloseFile(tFile); //Close the file
end;
end;
Button [Add an artist's work]
procedure TfrmArtists.btnAddArtistWorkClick(Sender: TObject);
var
tFile: TextFile;
sLine: string;
begin
AssignFile(tFile,'Artists.txt'); //"Say" with which file you work
if not FileExists('Artists.txt') then //test that file exist
begin
Rewrite(tFile); //create the file
CloseFile(tFile);
End
else begin //loop through file to “see” if the art work is already written to the file
Reset(tfile);
while not Eof(tFile) do
begin
Readln(tFile,sArt);
if Pos(sLine,sArt) > 0 then //test if art work appears in line
bFound:= True;
end;
CloseFile(tFile);
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 52
if not bFound then
begin
Append(tFile); //open file for writing
sLine:= sLine + InputBox('Enter price of work','','');
Writeln(tFile,sLine); //write to the file
CloseFile(tFile); //Close the file
end
else MessageDlg('Art work already in file',mtInformation,[mbOK],0);
end;
Button [Display a certain artist's work]
procedure TfrmArtists.btnArtistWorkClick(Sender: TObject);
var
tFile: TextFile;
sLine, sArtist , sName, sSurname,sArtwork: string;
no: integer;
begin
no:= cmbArtist.ItemIndex; //get index number for artist
sArtist:= cmbArtist.Items[no]; //get selected artist name
if not FileExists('Artists.txt') then //test that file exist
MessageDlg('The file does not exist',mtError,[mbOK],0) //message if not
else begin
AssignFile(tFile,'Artists.txt'); //"Say" with which file you work
Reset(tFile); //open file for reading
redDisplay.Clear;
redDisplay.Lines.Add('Artwork: ' + sArtist);
redDisplay.Lines.Add(' ');
while not Eof(tFile) do //loop to read whole file
begin
Readln(tFile,sLine); //read a single line
//copy from sLine, start at one to one character in front of #
sName:= Copy(sLine,1,Pos('#',sLine)-1);
if sName = sArtist then
begin
Delete(sLine,1,Pos('#',sLine)); //remove name
sSurname:= Copy(sLine,1,Pos('#',sLine)-1); //retrieve surname
Delete(sLine,1,Pos('#',sLine)); //remove surname
sArtwork:= Copy(sLine,1,Pos('#',sLine)-1);
redDisplay.Lines.Add(sArtwork) ; //display artwork
end;
end;
CloseFile(tFile); //close the file
end;
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 53
Button [Write a certain artist's work to a text file]
procedure TfrmArtists.btnArtistToFileClick(Sender: TObject);
var
tFile, tFile2: TextFile;
sLine, sArtist , sName, sSurname, sArtwork, sNewFile: string;
no: integer;
begin
no:= cmbArtist.ItemIndex; //get index number for artist
sArtist:= cmbArtist.Items[no]; //get selected artist name
if not FileExists('Artists.txt') then //test that file exist
MessageDlg('The file does not exist',mtError,[mbOK],0) //message if not
else begin
AssignFile(tFile,'Artists.txt'); //"Say" with which file you work
Reset(tFile); //open file for reading
while not Eof(tFile) and (sArtist <> sName) do //loop to read whole file
begin
Readln(tFile,sLine); //read a single line
//copy from sLine, start at one to one character before the #
sName:= Copy(sLine,1,Pos('#',sLine)-1);
Delete(sLine,1,Pos('#',sLine)); //delete from sLine from first character to #
sSurname:= Copy(sLine,1,Pos('#',sLine)-1);
end;
end;
sNewFile:= sName+sSurname+'.txt'; //build the new file's name
Reset(tFile); //start from the beginning
AssignFile(tFile2,sNewFile); //"Say" with which file you work
Rewrite(tFile2); //create the new file, open for writing
while not Eof(tFile) do //loop to read whole file
begin
Readln(tFile,sLine); //read a single line
//copy from sLine, start at one to one character before the #
sName:= Copy(sLine,1,Pos('#',sLine)-1);
if sName = sArtist then
begin
delete(sLine,1,Pos('#',sLine)); //delete name
Delete(sLine,1,Pos('#',sLine)); //delete surname
sArtwork:= Copy(sLine,1,Pos('#',sLine)-1); //get artwork
Writeln(tFile2,sArtwork); //write artwork tot new file
end;
end;
ShowMessage(sNewFile+' successfully created');
CloseFile(tFile); //Close the files
CloseFile(tFile2);
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 54
Button [Display all works with no price]
procedure TfrmArtists.btnDisplayNoPriceWorksClick(Sender: TObject);
var
tFile: textfile; //declare internal / RAM file name
sLine: string; //to store one line's content
begin
AssignFile(tFile,'Artists.txt');
Reset(tFile);
while not eof(tFile) do
begin
Readln(tFile,sLine);
// copy 10 characters - it can be any number
if Copy(sLine,Pos('@',sLine),10) = '@' then
redDisplay.Lines.Add(sLine);
end;
CloseFile(tFile);
end;
Arrays (1D)
A string is an example of an array that consists of characters = a list of characters
ordered in a specific way.
An index is used to refer to a specific character in a string: sVariable[7] refers to the
seventh character in the string.
A radio group is an example of an array.
When the.ItemIndex property is used it refers to the option / element selected in the list
(array) of options (elements) that is displayed in the radio group.
An index is used to refer to a specific item in the radio group: rgpExample[4] refers to the
third option / element in the group. (Third option / element because the options /
elements are numbered from 0 in a radio group)
INFORMATION TECHNOLOGY | Delphi Study Guide | 55
A rich edit is an example of an array.
When the.Lines.Add property is used – an element/value is added to the list (array) that
is displayed in the rich edit.
An index is used to refer to a specific line in the rich edit: redOutput.Lines[4] refers to the
fourth line.
Learner example to illustrate basic 1D array handling algorithms
Assignment
The following GUI is provided:
Global (form class unit) variables are declared:
public
procedure GetValuesFromKeyboard; //a method to populate an array from the keyboard
procedure AssignValues; //a method to populate an array with assign statements
procedure ReadFromTextFile; //a method to populate an array from the content of a text
file
Const
Max = 50; // the maximum value in the range for an array
// = maximum number of elements/values stored in the array
Var
arrAssign,arrKeyboard,arrTextFile: array[1..Max] of string;
//populate array with methods
arrName,arrNumber,arrNickName: array[1..Max] of string;
//different arrays for the information of a learner stored in the text file
arrClass: array[1..Max] of Char;
//array to store the class of a learner
iCounter: Integer; //counts the number of elements in an array
INFORMATION TECHNOLOGY | Delphi Study Guide | 56
arrConstant: array[1..10] of string =
('2178018, B, DALING, MARINUS HENDRIK, Henk',
'2178036, D, HOLDER, CULLEN DAMON, Cullen',
'2178066, H, STEYN, MARCO CLEMENT, Marco',
'2178081, A, BARNARD, CHRISTIAN JOHAN, Kian',
'2178085, A, BEUKES, JAN PETRUS JOHANNES, Johan',
'2178087, A, BODE, JACQUES, Jacques',
'2178091, A, BOOYSEN, JAMISON, Jamison',
'2178107, B, CONRADIE, WILLEM MARK, Mark',
'2178123, B, DU TOIT, KRUGER, Kruger',
'2178143, C, GOUS, ZANDER MEYER, Zander');
// population of an array with values = a constant array
Write code to do the following in the different event handlers:
[ReadFromTextFile]
Learner information is stored in the text file Learners.txt.
Test whether a text file exists and store the contents of the text file in the arrTextFile
array.
Store the number of elements / values in the array in the iCounter variable.
[AssignValuesFrom Keyboard]
Store 10 values entered by the user in the arrKeyboard array.
[AssignValues]
Assign 10 values to the arrAssign array.
[lstMethodsClick]
Populate the appropriate array with the method selected in the lstMethods list box.
[btnDisplayText]
Display the content of the arrTextFile array in the rich edit.
[btnSortAll]
Sort the information in the arrTextFile array.
[btnExtract]
The following screen shot shows the first few lines in the text file Learners.txt:
INFORMATION TECHNOLOGY | Delphi Study Guide | 57
A line consists of the following information for each learner, separated by a comma
(and a space):
number
class
surname
name(s)
nickname
Write code to
• Extract each part of the learner information and stored it in the appropriate
declared parallel arrays.
• Set the itemindex of the radio group rgpSort to -1 (no option must be selected).
• Enables the rgpSort, btnDisplay and grpProcessing components.
[rgpSort]
Sort the information in the parallel arrays according to the selection in the rgpSort
radio group.
[btnDisplay]
Display the information in the parallel arrays in the rich edit.
Button [Display new learner information]
Call the btnDisplayText event handler.
[btnSeek]
Display all the learners’ surnames and names from the parallel arrays in the rich edit
with the surname entered in a dialogue box.
[btnNew]
Insert a new learner’s information in the correct place in the sorted arrTextFile array.
[btnRemove]
Remove the learner information with the number entered in a dialogue box from the
parallel arrays.
[btnDuplicate]
Remove any duplicate learner’s information from the arrTextFile array.
INFORMATION TECHNOLOGY | Delphi Study Guide | 58
Solution
[ReadFromTextFile]
procedure TfrmArrays.ReadFromTextFile;
var
tFile: TextFile;
sLine: string;
iIndex: Byte;
begin
AssignFile(tFile,'Learners.txt'); //tell pc which file on hard drive to use
Try
Reset(tFile); //open file for reading
except
if MessageDlg('Can not find file' + #13 +
'Do you want to close the application? ',mtConfirmation,mbYesNo,0) = mrYes
then
Application.Terminate //close the program
else exit; //exit the event
end;
iIndex:= 0; //haven't read any learner information yet
while not Eof(tFile) and (iIndex <= max) do //max is maximum elements in array
begin
Inc(iIndex);//to read first learner's info
Readln(tFile,arrTextFile[iIndex]); //populate array
end;
iCounter:= iIndex; //remember the number of elements/values in array
End;
[AssignValuesFrom Keyboard]
procedure TfrmArrays.GetValuesFromKeyboard;
var
iIndex: Byte;
begin
for iIndex:= 1 to 10 do
arrKeyboard[iIndex]:= InputBox('Enter learner number ' + IntToStr(iIndex),'','');
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 59
[AssignValues]
procedure TfrmArrays.AssignValues;
begin
arrAssign[1]:= '2178018, B, DALING, MARINUS HENDRIK, Henk';
arrAssign[2]:= '2178036, D, HOLDER, CULLEN DAMON, Cullen';
arrAssign[3]:= '2178066, H, STEYN, MARCO CLEMENT, Marco';
……
arrAssign[9]:= '2178123, B, DU TOIT, KRUGER, Kruger';
arrAssign[10]:= '2178143, C, GOUS, ZANDER MEYER, Zander';
end;
[lstMethodsClick]
procedure TfrmArrays.lstMethodsClick(Sender: TObject);
begin
case lstMethods.ItemIndex of
0: GetValuesFromKeyboard;
2: AssignValues;
4: ReadFromTextFile;
end;
end;
[btnDisplayText]
procedure TfrmArrays.btnDisplayTextClick(Sender: TObject);
var
iIndex: Byte;
begin
redOutput.Clear;
for iIndex:= 1 to iCounter do
redOutput.Lines.Add(arrTextFile[iIndex]);
end;
[btnSortAll]
procedure TfrmArrays.btnSortAllClick(Sender: TObject);
var
I,J: Byte;
sSwap: string;
begin
for I:= 1 to iCounter - 1 do
for J:= I+1 to iCounter do
//need to work with arrTextfile because of iCounter
if arrTextFile[I] > arrTextFile[J] then
begin
sSwap:= arrTextFile[I];
arrTextFile[I]:= arrTextFile[J];
arrTextFile[J]:= sSwap;
end;
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 60
[btnExtract]
procedure TfrmArrays.btnExtractClick(Sender: TObject);
var
iIndex: Byte;
begin
for iIndex:= 1 to iCounter do
begin
arrNumber[iIndex]:= Copy(arrTextFile[iIndex],1,Pos(',',arrTextFile[iIndex])-1);
Delete(arrTextFile[iIndex],1,Pos(' ',arrTextFile[iIndex]));
arrClass[iIndex]:= arrTextFile[iIndex][1];
Delete(arrTextFile[iIndex],1,Pos(' ',arrTextFile[iIndex]));
arrName[iIndex]:= Copy(arrTextFile[iIndex],1,Pos(',',arrTextFile[iIndex])-1);
Delete(arrTextFile[iIndex],1,Pos(',',arrTextFile[iIndex])+1 );
arrNickName[iIndex]:= arrTextFile[iIndex];
end;
rgpSort.ItemIndex:= -1;
rgpSort.Enabled:= True;
btnDisplay.Enabled:= True;
grpProcessing.Enabled:= True;
end;
[rgpSort]
procedure TfrmArrays.rgpSortClick(Sender: TObject);
var
I,J: Byte;
sSwap: string;
begin
Try
if rgpSort.ItemIndex = 0 //sort according to numbers
then begin
for I:= 1 to iCounter - 1 do
for J:= I+1 to iCounter do
if arrNumber[I] > arrNumber[J] then
begin
sSwap:= arrNumber[I];
arrNumber[I]:= arrNumber[J];
arrNumber[J]:= sSwap;
sSwap[1]:= arrClass[I];
arrClass[I]:= arrClass[J];
arrClass[J]:= sSwap[1];
sSwap:= arrName[I];
arrName[I]:= arrName[J];
arrName[J]:= sSwap;
INFORMATION TECHNOLOGY | Delphi Study Guide | 61
sSwap:= arrNickName[I];
arrNickName[I]:= arrNickName[J];
arrNickName[J]:= sSwap;
end;
end;
if rgpSort.ItemIndex = 1 //sort according to class
then begin
for I:= 1 to iCounter - 1 do
for J:= I+1 to iCounter do
if arrClass[I] > arrClass[J] then
begin
sSwap:= arrNumber[I];
arrNumber[I]:= arrNumber[J];
arrNumber[J]:= sSwap;
sSwap[1]:= arrClass[I];
arrClass[I]:= arrClass[J];
arrClass[J]:= sSwap[1];
sSwap:= arrName[I];
arrName[I]:= arrName[J];
arrName[J]:= sSwap;
sSwap:= arrNickName[I];
arrNickName[I]:= arrNickName[J];
arrNickName[J]:= sSwap;
end;
end;
if rgpSort.ItemIndex = 2 //sort according to names
then begin
for I:= 1 to iCounter - 1 do
for J:= I+1 to iCounter do
if arrName[I] > arrName[J] then
begin
sSwap:= arrNumber[I];
arrNumber[I]:= arrNumber[J];
arrNumber[J]:= sSwap;
sSwap[1]:= arrClass[I];
arrClass[I]:= arrClass[J];
arrClass[J]:= sSwap[1];
sSwap:= arrName[I];
arrName[I]:= arrName[J];
arrName[J]:= sSwap;
INFORMATION TECHNOLOGY | Delphi Study Guide | 62
sSwap:= arrNickName[I];
arrNickName[I]:= arrNickName[J];
arrNickName[J]:= sSwap;
end;
end;
except
ShowMessage('Select sort option in radio group');
End;
end;
[btnDisplay]
procedure TfrmArrays.btnDisplayClick(Sender: TObject);
var
iIndex: Byte;
begin
redOutput.Clear;
for iIndex:= 1 to iCounter do
redOutput.Lines.Add(arrnumber[iIndex] + #9 + arrClass[iIndex]
+ #9 + arrName[iIndex] + #9 + arrNickName[iIndex]);
end;
Button [Display new learner information]
procedure TfrmArrays.btnDisplayNewClick(Sender: TObject);
begin
btnDisplayText.Click;
end;
[btnSeek]
procedure TfrmArrays.btnSeekClick(Sender: TObject);
var
sSeek: string;
bFound: Boolean;
iIndex: Byte;
begin
//ensure that list is sorted
rgpSort.ItemIndex:= 0;
rgpSortClick(sender);
sSeek:= UpperCase(InputBox('Enter surname','','Nel')); //get seek information
//need to find place in the sorted list to insert in correct place in list
bFound:= False; //haven't find place yet
iIndex:= 0; //haven't started yet
while not bFound and (iIndex <= iCounter) do
//while place not found and not at the end of the list
begin
Inc(iIndex); //start in first place
if Pos(sSeek,arrName[iIndex])> 0 then //if surname is found
bFound:= true; //raise the flag
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 63
//Display
redOutput.Clear;
while Pos(sSeek,arrName[iIndex])> 0 do
begin
redOutput.Lines.Add(arrName[iIndex]+ #9 + arrNickName[iIndex]);
Inc(iIndex);
end;
end;
[btnNew]
procedure TfrmArrays.btnNewClick(Sender: TObject);
var
sSeek: string;
bFound: Boolean;
iIndex,I: Byte;
begin
//The new information can be added at the end of the list and sorted BUT the
question is to add to a sorted list: marks will be lost
//Inc(iCounter);
//arrInligting[iCounter]:= InputBox('Enter new information','','2178091, A, BOOYSEN,
JAMISON, Jamison');
//add in sorted list
ReadFromTextFile; //get original information
btnSortAll.Click; //sort list
sSeek:= InputBox('Enter new information','','2178091, A, BOOYSEN, JAMISON,
Jamison');
//need to find place in the sorted list to insert in correct place in list
bFound:= False; //haven't find place yet
iIndex:= 0; //haven't started yet
while not bFound and (iIndex <= iCounter) do
//while place not found and not at the end of the list
begin
Inc(iIndex); //start in first place
if sSeek < arrTextFile[iIndex] then //compare new value to value in array
bFound:= true; //if new value is smaller than array value = place is found
end;
for I:= iCounter downto iIndex do
//need to "open" a space to insert the new value
//start at the end of the list till the place where the new value must be inserted
arrTextFile[I+1]:= arrTextFile[I]; //move each element "down"
arrTextFile[iIndex]:= sSeek; //insert the new value
Inc(iCounter); //increase the number of elements in the array
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 64
[btnRemove]
procedure TfrmArrays.btnRemoveClick(Sender: TObject);
var
sSeek: string;
bFound: Boolean;
iIndex,I: Byte;
begin
sSeek:= UpperCase(InputBox('Enter a number,'','2178123'));
//find place of the learner who needs to be removed
bFound:= False;
iIndex:= 0;
while not bFound and (iIndex <= iCounter) do
begin
Inc(iIndex);
if Pos(sSeek,arrNumber[iIndex])> 0 then
bFound:= true;
end;
for I:= iIndex to iCounter do //must move all elements "up"
begin
arrNumber[I]:= arrNumber[I+1];
arrName[I]:= arrName[I+1];
arrClass[I]:= arrClass[I+1];
arrNickName[I]:= arrNickName[I+1];
end;
Dec(iCounter); //one less learner in the class
end;
[btnDuplicate]
procedure TfrmArrays.btnDuplicateClick(Sender: TObject);
var
I,J: Byte;
begin
//compare adjacent elements in a sorted list and remove duplicate...
I:= 1;
while i < iCounter do
begin
while arrTextFile[I] = arrTextFile[I+1] do
begin
for J:= I + 1 to iCounter do
arrTextFile[J]:= arrTextFile[J+1] ;
Dec(iCounter);
end;
Inc(I);
end;
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 65
Arrays (2D)
A two dimensional array is a list of a list (you can think of it as a matrix).
E.g. arrNames in the previous program.
The names are a list and each name consists of a list of characters
List of names:
[1] D A L I N G , M A R I N U S H E N D R I K
[2] H O L D E R , C U L L E N D A M O N
[3] S T E Y N , M A R C O C L E M E N T
[4] B A R N A R D , C H R I S T I A N J O H A N
BEUKES, JAN PETRUS
[5] J O H A N N E S
[6] B O D E , J A C Q U E S
List of characters:
NOTE: a two dimensional array consists of rows (1 – 6 in example) and columns (1 –
27 in example).
Declaration of 2D array: arr2D: array[1..6,1..27] of string; // if example ranges are
used
NOTE: all basic 1D array processing algorithms can be applied to a 2D array.
Crossword example to illustrate basic 2D array handling algorithms
Words in a one dimensional array must be fitted in a cross word 2D array in the open
spaces provided. A word can only be placed in the cross word if the number of
characters in the word is exactly the same as the number of open spaces in a line in
the cross word array. The assumption can be made that only one word can be fitted
in a single line. This is an example of problem solving.
An array with words to fill in a cross word array is provided:
arrWords: array[1..10] of string =
('ANTMAN','BATMAN','BLACK WIDOW','CAPTAIN AMERICA',
'FLASH','GREEN LANTERN','IRONMAN','SUPERMAN','THOR','WONDER
WOMAN');
An 2D array to represent the cross word is provided with spaces where the words
must be inserted:
arrCrossWord: array[1..20,1..15] of ('*','*',' ',' ',' ',' ',' ',' ','*','*','*','*','*','*','*'),
char = ('*','*','*','*','*','*','*','*','*','*','*','*','*','*','*'),
(('*','*','*','*','*','*','*','*','*','*','*','*','*','*','*'), (' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','*','*'),
INFORMATION TECHNOLOGY | Delphi Study Guide | 66
('*','*','*','*','*','*','*','*','*','*','*','*','*','*','*'), ('*','*',' ',' ',' ',' ',' ',' ',' ','*','*','*','*','*','*'),
('*','*','*','*','*','*','*','*','*','*','*','*','*','*','*'), ('*','*','*','*','*','*','*','*','*','*','*','*','*','*','*'),
('*',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','*','*'), ('*','*','*','*','*','*','*','*','*','*','*','*','*','*','*'),
('*','*','*','*','*',' ',' ',' ',' ',' ',' ',' ',' ','*','*'), ('*','*',' ',' ',' ',' ','*','*','*','*','*','*','*','*','*'),
('*','*','*','*','*','*','*','*','*','*','*','*','*','*','*'), ('*','*','*','*','*','*','*','*','*','*','*','*','*','*','*'),
(' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '), ('*','*',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','*','*'),
('*','*','*','*','*','*','*','*','*','*','*','*','*','*','*'), ('*','*','*','*','*','*','*','*','*','*','*','*','*','*','*'),
('*','*','*',' ',' ',' ',' ',' ',' ','*','*','*','*','*','*'), ('*','*','*','*','*','*','*','*','*','*',' ',' ',' ',' ',' '));
The following GUI is provided:
Assignment
Write code to do the following:
Button [Display]
Display the two dimensional array in the rich edit.
Button [Fill with words]
Fill the words in the open spaces and display the two dimensional array in the rich
edit.
Solution
Button [Display]
procedure TfrmCrossWord.btnDisplayClick(Sender: TObject);
var
iCol,iRow: byte;
soutput: string;
begin
redOutput.clear;
redOutput.Lines.Add('');
for iRow:= 1 to 20 do //loop through rows
INFORMATION TECHNOLOGY | Delphi Study Guide | 67
begin
sOutput:= ''; //initialize an output string
for iCol:= 1 to 15 do //loop through coloumns
sOutput:= sOutput +#9+ arrCrossWord[iRow,iCol]; //build output
redOutput.Lines.Add(sOutput)
end;
end;
Button [Fill with words]
An example of a solution is to:
• find the first space in a line,
• count the number of spaces and
• compare the number of spaces with the word lengths to find the word to fill the
spaces.
NOTE: arrays will be used for the first two steps to “check” for all the lines in the
cross word.
procedure TfrmCrossWord.btnFillClick(Sender: TObject);
var
iRow,iCol: byte;
//declare two additional arrays to check start of spaces and number of spaces
arrBlanks,arrStart: array[1..20] of byte; //max 20 because 20 rows in cross word
iCheckCol,iCheckRow: byte;
sOut: string;
begin
//fill additional arrays with zero's to initialize
for iRow:= 1 to 20 do
begin
arrBlanks[iRow]:= 0;
arrStart[iRow]:= 0;
end;
for iRow:= 1 to 20 do //loop through rows in cross word
for iCol:= 1 to 15 do // loop through columns in cross word
if arrCrossWord[iRow,iCol] = ' ' then //find a space
begin
inc(arrBlanks[iRow]); //increase the number of spaces for the row
if arrStart[iRow] = 0 then //check if it is the first space in the row
arrStart[iRow]:= iCol; //store the place for the first space
end;
for iCheckRow:= 1 to 10 do //loop through words to fill in cross word
begin
iRow:= 1; //start at first row of array that stores number of spaces
while length(arrWords[iCheckRow]) <> arrBlanks[iRow] do
//compare number of spaces with word length
inc(iRow); // move to next row if length not same as number of spaces
INFORMATION TECHNOLOGY | Delphi Study Guide | 68
iCheckCol:= 1; //When correct number of spaces is found - move through columns
for iCol:= arrstart[iRow] to arrBlanks[iRow]+arrstart[iRow]-1 do
//from first space to last space
begin
arrCrossword[iRow,iCol]:= arrWords[iCheckRow][iCheckCol];
//fill the word character by character
inc(iCheckCol);//move to next character
end;
arrBlanks[iRow]:= 0;
//reset array to initial value to indicate that spaces has been filled
end;
end;
OOP (Object Orientated Programming)
Introduction
Look at the form unit of a new Delphi program:
Generic unit name: Unit1
Library units that can be used in any program with objects.
“Library” implies parts of code that can be re-used that is not bound
to a specific form.
E.g. ShowMessage dynamic object in the Dialogs library unit.
Generic class name: TForm1 which is created from/based on the TForm
“mold” / TForm class == all basic forms looks a like.
Form is the most basic component (class) for a Delphi program.
Generic form name Form1 and data (object) type TForm1 with a
number of pre-defined/inherited properties/attributes and
events/methods that can be addressed
INFORMATION TECHNOLOGY | Delphi Study Guide | 69
All the properties/attributes of the All the events/methods of the the
(type) Tform (object) class belong to (type) Tform (object) class belong to
this new form (object) and are listed in this new form (object) and are listed in
the object inspector: the object inspector:
NOTE: a form is “something” with attributes/properties and events/methods or in
other words
a form has a certain “look” or appearance and can “do” something e.g.
onCreate/onClose.
Own objects / units / classes
Why create an own unit/object? To create code for a certain environment that can be
re-used whenever that environment occurs/appears again.
E.g. the formatting for a rich edit component which must be done in a lot of
programs.
Some key factors to know when creating a new unit class:
• Identify the attributes/properties/fields of the object
• Constructor method
a class must have a constructor to set the initial values of the attributes for an
object (to “create” the object)
this method will normally receive input values called parameters
all input values must be assign to the appropriate attribute/field of the object
that is attribute:= parameter
INFORMATION TECHNOLOGY | Delphi Study Guide | 70
• Mutator method
always a PROCEDURE
a method to change an attribute’s value
this method will normally receive input values called parameters
all input values must be assign to the appropriate attribute/field of the object
that is attribute:= parameter or attribute:= attribute + parameter
• Accessor method
always a FUNCTION
returns an attribute’s value to the main form unit
NO input values/parameters
will always have a result:=
• Auxiliary method
a method that does not change any attribute’s value
a method that does not return any attribute’s value
this method can / will use the object’s attribute(s) and/or methods
can receive input values (parameters)
• All input values are received as parameters in the following format:
Procedure
methodName(parametername:datatype;parameterName2:datatype);
• To start a new unbound unit:
File, New, Unit
• To use / re-use the unit, add the unit name to the uses list in your program.
• Call the methods in the main form unit.
Assignment
1. Create an object class unit FormatRichEdit_u with the following attributes:
• fName: TRichEdit, to store the name of the rich edit in the form unit.
• fSubHeading: string, to store the subheadings to display separated by
commas.
2. Create the following methods:
2.1. A constructor method Create to receive the name of the rich edit as a
parameter and assign the value to the fName attribute.
2.2. An auxiliary method FormatHeading to:
clear the richedit
set the font style to bold and underline
set the font size to 12 pnts.
2.3. A mutator method setSubHeadings to receive the subheadings as a single
string separated by commas
assign the received value to the fSubHeading attribute
add a comma at the end of the fSubHeading attribute
2.4. An auxiliary method FormatSubHeadings to receive the number of
subheadings as an integer parameter.
Set the tabcount of the rich edit to the received value.
INFORMATION TECHNOLOGY | Delphi Study Guide | 71
Set the tab positions to the length of the subheading plus 80 pixels/spaces.
Construct a temporary heading consisting of the subheadings separated by
tabs.
Set the font color to blue.
Set the font style to bold.
Set the font size to 10 pnts.
2.5. An accessor method getSubHeadings to return the subheadings separated
by tabs.
Work in the main form unit and write the code to do the following:
3. Declare an object variable.
4. Call the object methods to:
4.1. Create the object for the rich edit placed on the form.
4.2. Assign the subheadings to the object.
4.3. Format the rich edit to add a heading.
4.4. Add the heading to the rich edit with an empty line after the heading
4.5. Format the rich edit to add a number of subheadings.
4.6. Add the subheadings separated by tabs to the rich edit with an empty line
after the subheadings.
Solution
unit FormatRichEdit_u;
interface
Uses
Graphics, ComCtrls;
type
TFormatRichEdit = class(tobject)
private
fName: TRichEdit;
fSubHeading: string;
public
constructor Create(redName:TRichEdit);
procedure FormatSubHeadings(iNumberTabs:Integer);
procedure setSubHeadings(sSubHeading: string);
procedure formatHeading;
function getSubHeadings:string;
end;
var
sTempHeading: string;
implementation
{ Tformat }
INFORMATION TECHNOLOGY | Delphi Study Guide | 72
[2.1]
constructor TFormatRichEdit.Create(redName: TRichEdit);
begin
fName:= redName;
end;
[2.2]
procedure TFormatRichEdit.FormatHeading;
begin
fName.Clear;
fName.SelAttributes.Style:= [fsBold,fsUnderline];
fName.SelAttributes.Size:= 12;
end;
[2.3]
procedure TFormatRichEdit.setSubHeadings( sSubHeading: string);
begin
fSubHeading:= sSubHeading+',';
end;
[2.4]
procedure TFormatRichEdit.FormatSubHeadings(iNumberTabs: Integer);
var
I,iTabPosition: Integer;
begin
iTabPosition:= Pos(',',fSubHeading);
sTempHeading:= Copy(fSubHeading,1,Pos(',',fSubHeading)-1);
fName.Paragraph.tabcount:= iNumberTabs;
for I:= 0 to iNumberTabs do
begin
fName.Paragraph.Tab[I]:= iTabPosition;
Delete(fSubHeading,1,Pos(',',fSubHeading));
iTabPosition:= iTabPosition + Pos(',',fSubHeading) + 80;
sTempHeading:= sTempHeading + #9 + Copy(fSubHeading,1,Pos(',',fSubHeading)-
1);
end;
fName.SelAttributes.Color:= clBlue;
fName.SelAttributes.Style:= [fsBold];
fName.SelAttributes.Size:= 10;
end;
[2.5]
function TFormatRichEdit.getSubHeadings: string;
begin
Result:= sTempHeading;
end;
end.
INFORMATION TECHNOLOGY | Delphi Study Guide | 73
unit MyProgram_U;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls,FormatRichEdit_u;
type
TfrmMyProgram = class(TForm)
btnMyFirstButton: TButton;
redOutput: TRichEdit;
procedure btnMyFirstButtonClick(Sender: TObject);
private
MyRichEdit: TFormatRichEdit; //declare an object variable [Q3]
{ Private declarations }
public
{ Public declarations }
end;
var
frmMyProgram: TfrmMyProgram;
implementation
{$R *.dfm}
procedure TfrmMyProgram.btnMyFirstButtonClick(Sender: TObject);
begin
[4.1]
MyRichEdit:= TFormatRichEdit.Create(redOutput); //create the object NB:=
//call the object’s methods using the format objectName.methodName
[4.2]
MyRichEdit.setSubHeadings('SubHeading1,SubHeading2,SubHeading3');
[4.3]
MyRichEdit.formatHeading;
[4.4]
redOutput.Lines.Add('Custom Heading');
redOutput.Lines.Add('');
[4.5]
MyRichEdit.FormatSubHeadings(3);
[4.6]
redOutput.Lines.Add(MyRichEdit.getSubHeadings);
redOutput.Lines.Add('');
end;
end.
INFORMATION TECHNOLOGY | Delphi Study Guide | 74
Database handling
SQL
Some basic structure(s): OR:
qryName.active:= false; With qryName do
qryName.sql.text:= ‘ instruction / Begin
statement ’; Close;
qryName.active:= true; Sql.text:= ‘ instruction / statement’;
Open;
Remember: End;
open can be used in place of
active:= true
close can be used in place of
active:= false;
OR:
sSQL:= ' instruction / statement ';
qryName.SQL.Clear;
qryName.SQL.Add(sSQL);
qryName.Open;
Basic structure of a SQL statement to display information
The ORDER of the key words are important = always the same order.
Select * / Field1, Field2 / CalculatedField / Aggregate funcion as [heading]
from tblname, tblname2
where tblname.LinkedField = tblname2.LinkedField and criteria and criteria
group by Field , Field2
having criteria and criteria
order by Field,Field2
NOTE:
• use the operators AND/OR/NOT when referring to criteria (where and having
key words)
• use comma (,) between field names…
• the key word SELECT is used to DISPLAY information…
• Spaces can cause problems in the execution of SQL statements… some
times they are needed and some times definitly NOT.
• when a field name in Access consists of more than one word, if it is a
reserved word or contain an operator, it must be placed in [ ] (square
brackets) in a SQL statement.
INFORMATION TECHNOLOGY | Delphi Study Guide | 75
Examples to display information on the dbgrid: SELECT
Most basic display statement:
‘SELECT * FROM tablename’; //Display ALL the fields in the table
‘SELECT Field1,Field2 FROM tablename’; //Display only Field1 and Field2
To display information WITHOUT DUPLICATES:
‘SELECT DISTINCT(FieldName ) FROM tablename’
//the duplicates are still in the database although no duplicates are displayed
Sorting of information:
‘SELECT * FROM tablename ORDER BY FieldName DESC’
//sort in descending order according to the specified fieldname
‘SELECT * FROM tablename ORDER BY FieldName1 ASC, FieldName2 DESC’
//sort first according to FieldName1 and then according to FieldName2
Display only specific records according to some criteria:
‘SELECT FieldName FROM tablename WHERE criteria’
Note the criteria is a statement using any of the following operaters:
= >= is not null
!= / <> between…and not
< in and
> like or
<= is null
Display records that contain specific text:
‘SELECT * FROM tablename WHERE FieldName LIKE “letter%”’; //begins with
‘SELECT * FROM tablename WHERE FieldName LIKE “%letter”’ ; //ends with
‘SELECT * FROM tablename WHERE FieldName LIKE “%letter%”’; //in the middle
NOTE:% is a wild character: any number of characters and/or any character
Display a group of records – look out for the words “for every /each one /for all
that / per group…”
‘SELECT FieldName, Aggregate Function AS … FROM tablename GROUP BY
FieldName ’;
NOTE: All the fields to display must occur after the group by – not necessaraly in
the same order. Do NOT use ‘*’ when grouping is must be done!
E.G.
‘SELECT FieldName , Field2,Field4, Aggregate Function AS … FROM tablename
GROUP BY FieldName , Field4,Field2 ’;
Having is used when a group must be displayed according to a specific
criteria:
‘SELECT FieldName Aggregate Function AS … FROM tablename GROUP BY
FieldName HAVING Aggregate Function with criteria;
INFORMATION TECHNOLOGY | Delphi Study Guide | 76
User input in SQL statements:
• ALL variables for user input must be declared as string.
• The SQL statement is a string hence the remark in bullet one.
• When combining the SQL statement with a field that is declared as TEXT in
Access – use “ “ because it is a string value in a string statement.
• No additional actions when combining the SQL statement with a field that is
declared as NUMBER / Currency / YesNo in Access.
• When combining the SQL statement with a field that is declared as DATE in
Access – use # #.
• Every opening ‘ must have an ending ‘, every opening “ must have an ending
“.and every opening # must have and ending “#”
'SELECT [FieldName 1],[FieldName 2],[FieldName 3],[FieldName 4] from tablename
where FieldName = ''' + STRINGvalue1 +''' and month(dateField) =
'+INTEGERvalue2;
Information from two tables:
'SELECT [FieldName 1],[FieldName 2] FROM tablename1,tablename2 '
+'WHERE tablename1.FieldName = tablename2.FieldName ’;
Fieldname is the field used to link the two tables in Access.
Built-in functions and calculated fields / aggregate functions:
ROUND: display as an integer value
'SELECT FieldName1,ROUND(FieldName1 *1.14) AS [Heading for calculated field]
from tablename’;
ROUND: display as a real value rounded off to two decimal places
'SELECT FieldName1,ROUND(FieldName 1 *1.14,2) AS [Heading for calculated
field] from tablename’;
{the ,2 specify the number of decimal places}
INT: truncation to integer value
'SELECT FieldName1,INT(FieldName 1 *1.14) AS [Heading for calculated field] from
tablename’;
Date/time functions – us a # when working with dates
YEAR: - returns the year in a date
‘SELECT FieldName , YEAR(DateField) from tablename’;
MONTH: - returns the month number in a date
‘ SELECT FieldName , MONTH(DateField) from tablename’;
DAY: - returns the day number in a date
‘SELECT FieldName , DAY(DateField) from tablename’;
DATE: - returns the system date
‘ SELECT FieldName , DATE() from tablename’;
INFORMATION TECHNOLOGY | Delphi Study Guide | 77
DATEVALUE: converts a string to date format
‘ SELECT FieldName ,FieldName2 from tablename WHERE
DateField < DATEVALUE(“5/1/1990”)’;
General calculation examples
Count the number of records which contains the searchValue
'SELECT COUNT(FieldName ) AS heading FROM tablename ' +
'WHERE FieldName LIKE "%searchValue%" ';
Calculate the total:
'SELECT SUM(FieldName ) AS heading from tablename’;
Determine the lowest/minimum/smallest:
'SELECT MIN(FieldName ) AS heading from tablename’;
Determine the highest/largest/maximum:
'SELECT MAX(FieldName ) AS heading from tablename’;
Calculate the average:
'SELECT AVG(FieldName ) AS heading from tablename’;
Display calculated field as currency
'SELECT FieldName , FORMAT(formula ,"CURRENCY") AS [NewFieldName ] ' + '
from tablename’;
String handling functions:
Concatenate two fields:
Field1 &Field2 AS heading from tablename’
Extract the first x-number of characters from a field:
Left(Field,x) AS heading from tablename’
Extract the last x-number of characters from a field:
Right(Field,x) AS heading from tablename’
Extract characters from a field starting at position x for y number of
characters:
Mid(Field,x, y) AS heading from tablename’
INFORMATION TECHNOLOGY | Delphi Study Guide | 78
SQL statements: DELETE / INSERT / UPDATE
Basic structure:
qryName.active:= false; with qryName do
qryName.sql.text:= ‘STATEMENT ‘; begin
qryXXX.ExecSQL; active:= false;
sql.text:= ‘STATEMENT’;
ExecSQL;
end;
Delete records:
All records: ‘DELETE FROM tablename’;
Specific records: ‘DELETE FROM tablename WHERE criteria’;
Insert a record:
'INSERT INTO tablename VALUES ("value",value1,"value2",#value3#)';
NOTE the use of “, # and no “ in the statement:
“ for values declared as TEXT in Access
no “ for values declared as NUMBER in Access
# for values declared as DATE in Access
the values will be inserted in the columns from left to right in the Access table
there must be exactly the same number of values as columns in the Access
table
IF only certain fields contain values to insert in the table:
'INSERT INTO tablename (Field1,Field2,Field3) VALUES ("value",value1,"value2")';
NOTE: the values will be inserted in the corresponding fieldname order in the
statement.
Change values of a field for specific records:
‘UPDATE tablename SET FieldName = “newvalue” WHERE FieldName =
"oldvalue"';
Change values of a field for ALL records:
‘UPDATE tablename SET FieldName = “newvalue”’
To insert a boolean value in the table e.g. when a check box with user input is
used:
'INSERT INTO tablename VALUES (''' + variable + ''', ''' + variable2 + ''' , ''' +
BOOLTOSTR(checkbox.checked) + ''' ,''' + variable3 + ''' )';
Most common error messages:
• “no default value”: misspelled field name / wrong table name / field
doesn’t exist in the Access table
• “…open exclusively….”: close design view in Access
INFORMATION TECHNOLOGY | Delphi Study Guide | 79
ADO- tabels / DML (data management language) / Delphi code construct and
Access
Basic table methods: TABLENAME._____
• FIRST: move the file marker to the first record in the table.
• NEXT: move the file marker one position down in the table.
• LAST: move the file marker to the last record in the table.
• INSERT: insert an empty record at the file marker position.
• EDIT: state of table to enable change in the table.
• POST: apply changes currently only in RAM to the Access table.
• CANCEL: no changes will be applied in the Access table.
• ABORT: this is the “undo” action of the post method.
• DELETE: removes the current record from the Access table directly.
• (If) BOF: Test if file marker is at the first record in the file.
• (If) EOF: Test if the file marker is at the end of the file.
• RECORDCOUNT: returns the number of records in the table
Basic structures to
NOTE: you can decide which method to use
• Extract information from a table:
• sVariable:= tblName.FieldByName(‘Fieldname’).AsString;
// use this method when the WITH DO structure is used
• sVariable:= tblName[‘Fieldname’];
// type casting is done internally and additional type casting code is not
necessary
• Insert information in a table:
With tblNames do OR
begin tblName.Insert;
Insert; tblName[‘LName’]:= ‘Piet’;
tblName[‘LSurname’]:= ‘Swart;
FieldByName(‘LName’).asstring:= tblName.Post;
‘Piet’;
FieldByName(‘LSurname’).asstring:=
‘Swart’;
Post;
end;//with
• Delete record from a table (confirm delete):
If MessageDlg(‘Are you sur to delete ‘ + tblName[‘LName’] +
‘?’,mtWarning,[mbOK,mbCancel],0) = mrOK then
tblName.Delete;
• Change information in a table:
INFORMATION TECHNOLOGY | Delphi Study Guide | 80
tblName.Edit;
tblName[‘LName’]:= ‘Pieter’;
tblName[‘LSurname’]:= ‘Swartz;
tblName.Post;
Instructor example to show use of Delphi construct and (ADO) database handling
The database Instructors.mdb contains data relating to instructors as well as the
lesson bookings that learners have made for driving lessons.
The following GUI is provided:
NOTE: a check list box is used because it is a nice way to apply array principles.
Assignment
Write code to do the following:
[OnActivate]
Clear the check list box.
Read the information stored in the LicenceCodes.txt file and add it to the check list
box.
[Display instructor record]
INFORMATION TECHNOLOGY | Delphi Study Guide | 81
Test if an instructor personal ID is entered in the edtPersID edit box.
Display a suitable message and set the focus on the edtPersID edit box if it is empty.
If an ID is entered:
• Search through the table to find the instructor with the personal ID entered in
the edtPersID edit box.
• Extract the rest of the instructor’s information from the table and display the
information in the provided edit boxes.
• Exit the procedure as soon as the instructor personal ID is found in the table.
NOTE: only use exit to end the loop execution when it is expressly asked in a
question
[New instructor record]
Because the personal instructor ID is the primary key, no duplicates are allowed.
Extract the last record’s personal ID and increase the number with one to construct a
new personal ID.
NOTE: you can assume that the table is ordered according to the instructor personal
ID field.
No data validation done here…..
[Save Record]
Write the new record to the Access table.
[Delete instructor record]
Move to the record for the instructor with personal ID entered in the edtPersId edit
box to delete from the table.
Confirm if it is the correct instructor to delete.
Delete the instructor from the table.
NOTE: remember the record with the primary key (personal ID) can not be deleted if
there is still information for that primary key in the related table (foreign key)
[Update instructor record]
INFORMATION TECHNOLOGY | Delphi Study Guide | 82
Move to the record for the instructor with personal ID entered in the edtPersId edit
box to change in the table.
Write the new (update) information entered in the edit boxes on the pnlInstructor
panel to the table.
[New year]
Change all record’s dates in the drivebookings table to the following year.
[Display number of bookings]
Search for the instructor indicated in the edtPersID edit box.
Display the instructor’s name, surname, ALL the bookings for the same month as the
system date and the total number of hours the instructor will be booked.
Solution
[OnActivate]
procedure TfrmADO.FormActivate(Sender: TObject);
var
tFile: TextFile;
sLine: string;
begin
cklstbLicenceCodes.Items.Clear; //clear the check list box
AssignFile(tFile,'LicenceCodes.txt');
Reset(tFile);
while not Eof(tFile) do
begin
Readln(tFile,sLine);
cklstbLicenceCodes.Items.Add(sLine); // Loading data into check list box
end;
CloseFile(tFile) ;
end;
[Display instructor record]
procedure TfrmADO.btnSearchClick(Sender: TObject);
var
sLicenceCodes: string;
begin
if edtPersID.Text <> '' then //test if an ID is entered
begin
tblInstructors.First; //move cursor to first record in the table
while not tblInstructors.eof do //move through the table until ID is found
begin
if tblInstructors['instructorPersID'] = UpperCase(edtPersID.Text) then
//test if the current record is the ID you are looking for
Begin
INFORMATION TECHNOLOGY | Delphi Study Guide | 83
//extract information the rest of the information from the various fields and display in
edit boxes
edtSAID.Text:= tblInstructors['instructorSAID'];
edtInstName.Text:= tblInstructors['instructorName'];
edtInstSurname.Text:= tblInstructors['instructorSurname'];
edtContactNr.Text:= tblInstructors['instructorContactNr'];
sLicenceCodes:= tblInstructors['instructorLicenceCodes']+ ',';
//add a , for extraction
//character/string handling to find which boxes must be checked in the list box
while Pos(',',sLicenceCodes) > 0 do //find all the commas, one by one
begin
if Copy(sLicenceCodes,1,Pos(',',sLicenceCodes)-1)='A' then
//test to find the check box to check
cklstbLicenceCodes.State[0]:= cbChecked; //”check” the box
//repeat for all possible values
if Copy(sLicenceCodes,1,Pos(',',sLicenceCodes)-1)='A1' then
cklstbLicenceCodes.State[1]:= cbChecked;
if Copy(sLicenceCodes,1,Pos(',',sLicenceCodes)-1)='B' then
cklstbLicenceCodes.State[2]:= cbChecked;
if Copy(sLicenceCodes,1,Pos(',',sLicenceCodes)-1)='C' then
cklstbLicenceCodes.State[3]:= cbChecked;
if Copy(sLicenceCodes,1,Pos(',',sLicenceCodes)-1)='C1' then
cklstbLicenceCodes.State[4]:= cbChecked;
if Copy(sLicenceCodes,1,Pos(',',sLicenceCodes)-1)='EB' then
cklstbLicenceCodes.State[5]:= cbChecked;
if Copy(sLicenceCodes,1,Pos(',',sLicenceCodes)-1)='EC' then
cklstbLicenceCodes.State[6]:= cbChecked;
if Copy(sLicenceCodes,1,Pos(',',sLicenceCodes)-1)='EC1' then
cklstbLicenceCodes.State[7]:= cbChecked;
Delete(sLicenceCodes,1,Pos(',',sLicenceCodes)); //Delete the option checked
end;
EXIT; //exit the procedure as soon as ID is found
end;
tblInstructors.Next;
//move to the next record if current record is not the one looking for
end;
end
else begin //if no personal ID was entered
MessageDlg('Enter a instructor`s personal ID first',mtError,[mbOK],0);
edtPersID.SetFocus;
end;
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 84
[New instructor record]
procedure TfrmADO.btnNewRecordClick(Sender: TObject);
var
sInstID: String;
LastVal: Integer;
begin
tblInstructors.Last; //move to the last record in the table
sInstID:= tblInstructors['InstructorPersID']; //extract the last personal ID
Delete(sInstID,1,3); // Removing INS
LastVal:= StrToInt(sInstID); //convert to an integer
inc(LastVal); // adding 1 to lastval
sInstID:= IntToStr(LastVal); //convert to a string
insert('INS',sInstID,1); //add INS
while Length(sInstID) < 6 do //check the length of the ID – it must be 6
insert('0',sInstID,4); //add 0 to fill the ID
edtPersID.Text:= sInstID; //display new ID in provided edit box
end;
[Save Record]
procedure TfrmADO.bttSaveRecordClick(Sender: TObject);
var
I: Integer;
sCodes: String;
begin
tblInstructors.Last; //move to last record
tblInstructors.Insert; //add an empty record
//assign all information in various fields from edit boxes
tblInstructors['InstructorPersID']:= edtPersID.Text;
tblInstructors['InstructorSAID']:= edtSAID.Text;
tblInstructors['InstructorName']:= edtInstName.Text;
tblInstructors['InstructorSurname']:= edtInstSurname.Text;
tblInstructors['InstructorContactNr']:= edtContactNr.Text;
tblInstructors['EmpBasicSalPA']:= 125000;
sCodes:= ''; //emptry string to build the licence codes field
for I:= 0 to cklstbLicenceCodes.Count - 1 do //move through check boxes
begin
if (cklstbLicenceCodes.State[I] = cbChecked) then // test if a box is checked
begin
sCodes:= sCodes + cklstbLicenceCodes.Items.Strings[I] + ',';
//add to licence code string separated by a ,
end;
end;
Delete(sCodes,Length(sCodes),1); // delete the last , appended
tblInstructors['InstructorLicenceCodes']:= sCodes; // assign to field
tblInstructors.Post; //save to the Access table
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 85
[Delete instructor record]
procedure TfrmADO.btnDeleteClick(Sender: TObject);
var
sID: string;
begin
btnSearch.Click; //move file marker / cursor to specific record in the table
sID:= UpperCase(edtPersID.Text); //extract personal ID for instructor
if MessageDlg('Sure to delete?',mtConfirmation,mbYesNo,0) = mrYes
//confirm delete
then begin
tblBookings.First; // move to first record in drivebookings table
while not tblBookings.Eof do //check all records in the drivebookings table
begin
if tblBookings['InstructorNr'] = sID //test if it is the instructor ID to delete
then tblBookings.Delete //delete the booking
else tblBookings.Next; //move to the next record
end;
tblInstructors.Delete; //delete the instructor from the instructors table
end;
end;
[Update instructor record]
procedure TfrmADO.btnUpdateClick(Sender: TObject);
var
I: Integer;
sCodes: String;
begin
btnSearch.Click; //move file marker / cursor to specific record in the table
tblInstructors.Edit; //set table in edit mode to update
//assign all information in various fields from edit boxes
tblInstructors['InstructorSAID']:= edtSAID.Text;
tblInstructors['InstructorName']:= edtInstName.Text;
tblInstructors['InstructorSurname']:= edtInstSurname.Text;
tblInstructors['InstructorContactNr']:= edtContactNr.Text;
sCodes:= ''; //emptry string to build the licence codes field
for I:= 0 to cklstbLicenceCodes.Count - 1 do //move through check boxes
if (cklstbLicenceCodes.State[I] = cbChecked) then // test if a box is checked
sCodes:= sCodes + cklstbLicenceCodes.Items.Strings[I] + ',';
//add to licence code string separated by a ,
Delete(sCodes,Length(sCodes),1); // delete the last , appended
tblInstructors['InstructorLicenceCodes']:= sCodes; // assign to field
tblInstructors.Post; //save to the Access table
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 86
[New year]
procedure TfrmADO.btnAllClick(Sender: TObject);
begin
tblBookings.First; //move to the first record
while not tblBookings.Eof do //apply to all records in the table
begin
tblBookings.Edit; //set table in edit mode
tblBookings['LessonDate']:= tblBookings['LessonDate']+365; //update the field
tblBookings.Post; //apply change in Access table
tblBookings.Next; //move to next record
end;
end;
[Display number of bookings]
procedure TfrmADO.btnCountClick(Sender: TObject);
var
iCount: Integer;
begin
btnSearch.Click; //move file marker / cursor to specific record in the table
if edtPersID.Text <> '' then
begin
iCount:= 0; //initialize total counter
redDisplay.Clear;
redDisplay.Lines.Add(tblInstructors['InstructorName'] + #9 +
tblInstructors['InstructorSurname']); //display the name and surname of the instructro
redDisplay.Lines.Add('');
tblBookings.First; //move to first record in the drivebookings table
while not tblBookings.Eof do //check ALL records against instructor number
begin
if tblBookings['InstructorNr'] = tblInstructors['InstructorPersID'] then
//test instructor number
if Monthof(tblBookings['LessonDate']) = monthof(Date) then //test month
begin
redDisplay.Lines.Add(tblBookings['LessonDate']); //display booking information
iCount:= iCount + tblBookings['LessonTime']; //add to total hours
end;
tblBookings.Next; //move to next record
end;
redDisplay.Lines.Add('');
redDisplay.Lines.Add('Total hours: ' + IntToStr(iCount)); //display total hours
end;
end;
INFORMATION TECHNOLOGY | Delphi Study Guide | 87
Basic error messages with possible solution
Missing operator or semicolon
The previous line needs a ;
Does the CASE have an OF
Are you missing an operator like +, -, /, *, div or mod
Incompatible types: “integer” and “extended”
(data types are not correct!!)
e.g.: iAmount:= iAmount / 10;
/ is floating point division, cannot be assigned to integer:= float
Use div / round / trunc / declare answer as real
Type in expression must be Boolean
A:= is used in the if statement – it must be = only
It is a comparison use = / > /< / <> / not / in
e.g if iNumber mod 6
Then …
needs something like
if iNumber mod 6 = 0
Then
Unknown identifier
Variable not declared
Declaration in wrong method/procedure
Wrong spelling / misspelled
A string without ‘’
Operator not applicable to this operand type
Mathematical operator not appropriate for expression
e.g: iNumber:= r1 div r2;
div is INTEGER division – can not use with real / floating point numbers
There is a compound if statement with and/or/not without brackets
When clicking on component and event handler framework is not available
Press F9 and correct / comment all mistakes
If the error is in the “private” section: delete the declaration of the event handler and
except the message in the dialogue window once you run the program
If property options list is not displayed
Press F9 and correct / comment all mistakes
Unknown directive “****”
VAR is left out
Then expected but identifier found
If statement without the then part
INFORMATION TECHNOLOGY | Delphi Study Guide | 88
; not allowed before else
Delete the ; in the previous line
Ordinal type required (in case statement)
The variable in the case ____ of must be an integer / char
Use trunc / round or [ ] in case of a string, e.g Word[2] or nested-if for real variables
Constant expression expected (in case)
END for case statement is missing
BEGIN and END is missing for compound statements in case statement
Declaration expected but identifier found
BEGIN and END is missing for compound statements
Or END without the BEGIN
; expected but. found
Somewhere a BEGIN without an END
Unterminated string
A string started with a ‘ but not end with one
e.g. Showmessage(‘blablabla);
Incompatible types: “string” and “tspinedit”
The property of a component is left out
Text after final end ignored by compiler
There are instructions after the final END of the program
Could not create outputfile @@@
The save / save all option was not selected yet
For control variable must be a simple local variable
The control variable for the FOR loop must be local
Class T___ not found
The “name property” is deleted
Assignment to for-loop variable ****
The control variable of the FOR loop changes automatically and you try to change /
assign a value to the control variable
Incompatible types string and procedure untype pointer or untype parameter
Unpaired brackets
Cannot focus a disabled or invisible window
When program starts to run: the setfocus must be in the onactivate and not in the
oncreate event handle
During execution: the component enabled property is set to false somewhere in the
program
INFORMATION TECHNOLOGY | Delphi Study Guide | 89