ITRW222VBC - Index of

ITRW222VBC - Index of ITRW222VBC - Index of

cdn.lnx1.nwu.ac.za
from cdn.lnx1.nwu.ac.za More from this publisher
05.05.2013 Views

Study guide compiled by: DATASTRUKTURE EN ALGORITMES: DATA STRUCTURES AND ALGORITHMS STUDY GUIDE FOR ITRW222VBC *ITRW222VBC* VAAL TRIANGLE CAMPUS Dr R Goede (School of Information Technology) Printed by The Platinum Press (018) 294 8879/(016) 981 9401 Copyright © 2011 edition. Date of revision 2012 North-West University, Vaal Triangle Campus All rights reserved. No part of this book, may be reproduced in any form or by any means without written permission from the publisher. It includes the making of photocopies of the whole or parts of this book.

Study guide compiled by:<br />

DATASTRUKTURE EN ALGORITMES:<br />

DATA STRUCTURES AND ALGORITHMS<br />

STUDY GUIDE FOR<br />

<strong>ITRW222VBC</strong><br />

*<strong>ITRW222VBC</strong>*<br />

VAAL TRIANGLE CAMPUS<br />

Dr R Goede (School <strong>of</strong> Information Technology)<br />

Printed by The Platinum Press (018) 294 8879/(016) 981 9401<br />

Copyright © 2011 edition. Date <strong>of</strong> revision 2012<br />

North-West University, Vaal Triangle Campus<br />

All rights reserved. No part <strong>of</strong> this book, may be reproduced in any form or by any means<br />

without written permission from the publisher. It includes the making <strong>of</strong> photocopies <strong>of</strong> the<br />

whole or parts <strong>of</strong> this book.


INHOUDSOPGAWE<br />

Rekenaarwetenskap en Inligtingstelsels ................................................................................ 3<br />

Tydverdeling .......................................................................................................................... 3<br />

Module-uitkomste ................................................................................................................... 3<br />

Veronderstelde leer ................................................................................................................ 4<br />

Beskikbare hulp ..................................................................................................................... 4<br />

Studiemateriaal ...................................................................................................................... 4<br />

Klasbywoning ......................................................................................................................... 4<br />

Werkswyse ............................................................................................................................ 5<br />

Hulp tydens prakties .............................................................................................................. 5<br />

Rugsteun ............................................................................................................................... 5<br />

Evaluering .............................................................................................................................. 6<br />

Studie-ikone ........................................................................................................................... 7<br />

Waarskuwing teen plagiaat .................................................................................................... 8<br />

Leereenheid 1 Die analise van algoritmes – deel 1 ................................................ 9<br />

Leereenheid 2 Die analise van algoritmes – deel 2 .............................................. 11<br />

Leereenheid 3 Skikkings en matrikse ................................................................... 13<br />

Leereenheid 4 Geskakelde lyste ........................................................................... 15<br />

Leereenheid 5 Datatipes en abstraksie – deel 1 ................................................... 17<br />

Leereenheid 6 Datatipes en abstraksie – deel 2 ................................................... 19<br />

Leereenheid 7 Stapels ........................................................................................... 21<br />

Leereenheid 8 Toue ................................................................................................ 23<br />

Leereenheid 9 Geordende lyste ............................................................................ 25<br />

Leereenheid 10 Gesorteerde lyste .......................................................................... 27<br />

Leereenheid 11 Sorteringsalgoritmes - deel 1 ....................................................... 29<br />

Leereenheid 12 Sorteringsalgoritmes - deel 2 ....................................................... 31<br />

Leereenheid 13 Bome en grafieke ........................................................................... 33<br />

Bylaag 1 - Praktiese opdragte ........................................................................................... 35<br />

Bylaag 2 – Klasbesprekings .............................................................................................. 46<br />

Bylaag 3 – Eksamenvraestel ............................................................................................. 74<br />

2


MODULE CONTENTS<br />

Welcome ................................................................................................................................ 3<br />

Computer science and information systems ........................................................................... 3<br />

Time management ................................................................................................................. 3<br />

Module outcomes................................................................................................................... 3<br />

Supposed study ..................................................................................................................... 4<br />

Available help ........................................................................................................................ 4<br />

Study material ........................................................................................................................ 4<br />

Class attendance ................................................................................................................... 4<br />

Work method ......................................................................................................................... 5<br />

Help during practical classes.................................................................................................. 5<br />

Backup ................................................................................................................................... 5<br />

Evaluation .............................................................................................................................. 6<br />

Study icons ............................................................................................................................ 7<br />

Warning against plagiarism .................................................................................................... 8<br />

Study unit 1 Analysis <strong>of</strong> algorithms – part 1 ....................................................... 9<br />

Study unit 2 Analysis <strong>of</strong> algorithms – part 2 ..................................................... 11<br />

Study unit 3 Arrays and matrixes ...................................................................... 13<br />

Study unit 4 Linked lists ..................................................................................... 15<br />

Study unit 5 Data types and abstraction – part 1 ............................................. 17<br />

Study unit 6 Data types and abstraction – part 2 ............................................. 19<br />

Study unit 7 Stacks ............................................................................................. 21<br />

Study unit 8 Queues ........................................................................................... 23<br />

Study unit 9 Ordered lists .................................................................................. 25<br />

Study unit 10 Sorted lists ..................................................................................... 27<br />

Study unit 11 Sorting algorithms - part 1 ........................................................... 29<br />

Study unit 12 Sorting algorithms – part 2 .......................................................... 31<br />

Study unit 13 Trees and graphs ........................................................................... 33<br />

Appendix 1 - Practical assignments ................................................................................. 35<br />

Appendix 2 – Class discussions ....................................................................................... 46<br />

Appendix 3– Examination paper ....................................................................................... 74<br />

2


REKENAARWETENSKAP EN INLIGTINGSTELSELS<br />

PU-vlak 2<br />

Nasionale vlak 6<br />

Krediete 16<br />

Kontakperiodes 4<br />

Praktiese periodes 3<br />

TYDVERDELING<br />

Aktiwiteit Weke Ure per week Totaal<br />

Klas (kontaktyd –> lesing + klastoetse) 12 3 36<br />

Praktika in laboratorium 12 2.5 30<br />

Praktiese opdragte 12 4 48<br />

Selfstudie 12 2 24<br />

Semestertoets 1 10 12<br />

Eksamen 1 12 12<br />

Totaal 160<br />

MODULE-UITKOMSTE<br />

Aan die einde van hierdie module het die leerder basiese kennis en insig<br />

verwerf oor:<br />

• Die tydanalise van algoritmes;<br />

• vektore;<br />

• matrikse;<br />

• geskakelde lyste;<br />

• stapels;<br />

• toue;<br />

• gesorteerde lyste;<br />

• bome;<br />

• sorteer-algoritmes; en<br />

• abstrakte datatipes en -klasse.<br />

3


WELCOME<br />

COMPUTER SCIENCE AND INFORMATION SYSTEMS<br />

PU level 2<br />

National level 6<br />

Credits 16<br />

Contact sessions 4<br />

Practical classes 3<br />

TIME MANAGEMENT<br />

Activity Weeks Hours a week Total<br />

Class (contact time –> lecture + class test)12 3 36<br />

Practical in laboratory 12 2.5 30<br />

Practical assignments 12 4 48<br />

Independent study 12 2 24<br />

Semester tests 1 10 12<br />

Exam 1 12 12<br />

Total 160<br />

MODULE OUTCOMES<br />

On completion <strong>of</strong> this module the learner will have basic knowledge and<br />

insight regarding the following:<br />

• The time analysis <strong>of</strong> algorithms;<br />

• vectors;<br />

• matrixes;<br />

• linked lists;<br />

• stacks;<br />

• queues;<br />

• sorted lists;<br />

• trees;<br />

• sorted algorithms; and<br />

• abstract data types and classes.<br />

3


Die leerder sal na voltooiing van die kursus kan bewys lewer dat hy/sy:<br />

• Die kennis en insig wat verwerf is, in probleemoplossing met behulp van die rekenaar<br />

kan toepas;<br />

• ’n goeie programmeringstyl gebruik en leesbare programme kan skryf;<br />

• gestruktureerde klasse en -programme kan skryf wat netjiese uitvoer lewer; en<br />

• programme skryf wat gebruikersvriendelik is.<br />

VERONDERSTELDE LEER<br />

Om hierdie module suksesvol te doen, word veronderstel dat ten minste 40% vir ITRW 212<br />

behaal is.<br />

BESKIKBARE HULP<br />

Dosent: Mnr Johan Prinsloo<br />

Kantoor: 102<br />

Telefoon: x 3275<br />

E-pos: Johan.Prinsloo@nwu.ac.za<br />

Groepleiers: Tydens die geskeduleerde praktiese periodes sal daar studente-assistente<br />

beskikbaar wees om met die opdragte te help. Hulle sal ook verantwoordelik<br />

wees vir die evaluering van praktiese opdragte en toetse wat tydens<br />

die geskeduleerde praktiese tye geskryf word.<br />

STUDIEMATERIAAL<br />

HANDBOEK<br />

Titel: Data Structures and Algorithms with Object Oriented Design Patterns in Java<br />

Outeur: Bruno R Preiss<br />

ISBN: 0-471-34613-6<br />

Uitgewer: Wiley<br />

KLASBYWONING<br />

Aangesien klastoetse wel sonder vooraf kennisgewing gegee kan word, is dit noodsaaklik<br />

dat alle klasse bygewoon word, tensy anders gereël.<br />

PRAKTIES<br />

Die module is baie prakties van aard en daarom vorm die praktiese opdragte die kern van<br />

die module. Alle opdragte moet betyds voltooi en ingehandig word vir evaluering.<br />

4


On completion <strong>of</strong> this course the learner must prove that he/she:<br />

• Is able to use the knowledge and insight gained and apply it in problem solving with the<br />

aid <strong>of</strong> a computer;<br />

• can use good programming style and is able to write readable programmes;<br />

• is able to write structured classes and programs that are neatly executed; and<br />

• can write programs that are user friendly.<br />

SUPPOSED STUDY<br />

To successfully complete this module, it is assumed that you achieved a mark <strong>of</strong> at least<br />

40% for ITRW 212.<br />

AVAILABLE HELP<br />

Lecturer: Mr Johan Prinsloo<br />

Office: 102<br />

Telephone: x 3275<br />

Email: Johan.Prinsloo@nwu.ac.za<br />

Group leaders: During the practical classes student assistants will be on hand to help you<br />

with your assignments. They are also responsible for the evaluation <strong>of</strong><br />

practical assignments and tests written during the scheduled practical<br />

classes.<br />

STUDY MATERIAL<br />

TEXTBOOK<br />

Title: Data Structures and Algorithms with Object Oriented Design Patterns in Java<br />

Author: Bruno R Preiss<br />

ISBN: 0-471-34613-6<br />

Publisher: Wiley<br />

CLASS ATTENDANCE<br />

Class tests may be written without prior notice. It is therefore very important that you attend<br />

all classes unless other arrangements are made.<br />

PRACTICAL<br />

The assignments are the core <strong>of</strong> this module due to the practical nature <strong>of</strong> the course. All<br />

assignments must be completed on time and be submitted for evaluation.<br />

4


WERKSWYSE<br />

• Die doel van die module is om programmeringsvaardighede uit te brei en daarom is dit<br />

noodsaaklik dat jy baie oefening kry om programme te skryf.<br />

• Java word as programmeringstaal gebruik.<br />

• Die praktiese opdrag wat elke week gegee word, is 'n samevatting van sommige van<br />

die tegnieke wat in die klas aangeleer is en dit moet ingeoefen word.<br />

• Al die werk van die week kan egter nie in die praktiese opdrag weergegee word nie en<br />

daarom is dit noodsaaklik om die voorbeelde en werk wat in die klas gedoen is, na<br />

afloop van die klasse (tydens eie tyd) op die rekenaar te oefen. Die praktiese opdragte<br />

dek slegs 'n deel van die werk wat gedoen word.<br />

• Tydens elke praktikum word 'n opdrag gegee, en dit word voltooi en ingehandig en<br />

deur die groepleier geëvalueer.<br />

• Onthou: ’n program wat nie werk nie is niks werd nie!<br />

• As die opdragte nie tydens die geskeduleerde tyd klaar is nie, moet dit in jou eie tyd<br />

gedurende die week voltooi word en vóór die volgende prakties per e-pos aan die<br />

groepleier vir evaluering gestuur word.<br />

• Rugsteun moet van al die programme en opdragte op ’n stiffie gehou word en dit moet<br />

by elke praktiese klas beskikbaar wees.<br />

• As 'n program laat ingehandig word, word punte afgetrek.<br />

• Aan die begin van ’n praktiese sessie word dadelik met die nuwe opdrag begin.<br />

• Afskrywery en kopiëring van ander persone se werk word as 'n baie ernstige oortreding<br />

beskou. Die persoon wat hieraan skuldig is, sowel as die persoon wat sy werk beskikbaar<br />

gestel het, sal hulle punte verbeur en loop ook gevaar om eksamentoelating<br />

geweier te word.<br />

HULP TYDENS PRAKTIES<br />

Al die praktiese sessies vind in die mikro-laboratorium plaas en almal moet teenwoordig<br />

wees.<br />

Studente-assistente sal beskikbaar wees om met die praktiese opdragte gedurende<br />

die praktiese sessies te help.<br />

Geen praktiese opdrag sal vir ’n punt in aanmerking kom as die student nie tydens die<br />

geskeduleerde praktiese periodes teenwoordig was nie.<br />

Die studente-assistente is verantwoordelik vir die evaluering van die opdragte. As ’n<br />

praktiese opdrag voltooi is, sal die studente-assistent ’n punt daarvoor gee.<br />

Die studente-assistent moet al die studente in sy groep se naam en besonderhede<br />

opskryf en die studente moet hulle studente-assistente se naam en e-posadres kry.<br />

RUGSTEUN<br />

Die praktiese werk wat gedoen word, word op die P-skyf van die netwerk gestoor. Elke<br />

student moet egter nog ’n stiffie aanskaf om die opdragte en werkstukke op te stoor sodat dit<br />

op twee plekke gestoor kan word (vir veiligheid/rugsteun).<br />

5


WORK METHOD<br />

• The aim <strong>of</strong> this module is to expand your programming skills, and practice in writing<br />

programs is therefore essential.<br />

• Java is the programming language used.<br />

• Each week’s practical assignment is a summary <strong>of</strong> some <strong>of</strong> the techniques you learned<br />

in class and must be practised.<br />

• All the work <strong>of</strong> the week cannot be included in the practical assignment. For this reason<br />

it is essential to practise at home the examples and the work done during class. The<br />

practical assignments cover only a part <strong>of</strong> the work done.<br />

• During each practical class an assignment will be given that must be completed and<br />

submitted for evaluation by the group leader.<br />

• Remember: a program that does not work is worthless!<br />

• Assignments not completed during class must be finished on your own time and sent<br />

by e-mail to the group leader for evaluation before the next practical.<br />

• Backups <strong>of</strong> all your programs and assignments must be kept and be available<br />

with each practical class.<br />

• Programs submitted late will result in a loss in marks.<br />

• At the start <strong>of</strong> each practical session a new assignment will be started on.<br />

• Copying another person’s work is a serious <strong>of</strong>fence. Both the person guilty <strong>of</strong> copying<br />

and the person making his/her work available, will forfeit marks and run the risk <strong>of</strong><br />

being denied admission to the examination.<br />

HELP DURING PRACTICAL CLASSES<br />

All practical classes will be in the micro laboratory and all must be in attendance.<br />

Student assistants will be on hand to help you with the assignments during the<br />

practical classes.<br />

A practical assignment will not be evaluated if the student was absent from the<br />

scheduled practical class.<br />

The student assistants are responsible for evaluating the assignments. On<br />

completion <strong>of</strong> a practical assignment the student assistant will award a mark.<br />

The student assistant must get his/her group’s names and details, and students must<br />

get the name and e-mail address <strong>of</strong> their student assistant.<br />

BACKUP<br />

The practical work must be saved on the P drive <strong>of</strong> the network. Each student must create<br />

an extra backup <strong>of</strong> his/her assignments on a disk to ensure it is stored at two separate<br />

places.<br />

5


EVALUERING<br />

KLASTOETSE<br />

• Praktiese opdragte sowel as teorie-klastoetse sal weekliks gegee word ten einde jou in<br />

staat te stel om jou deelnamebewys te verwerf en om jou vordering na waarde te skat.<br />

• Klastoetse sal handel oor die werk wat die vorige week behandel is, maar kennis van<br />

vorige werk is ook noodsaaklik.<br />

• Klastoetse wat handel oor die vorige periode se werk kan ook sonder vooraf waarskuwing<br />

gegee word.<br />

• Elke gedeelte van die werk veronderstel 'n grondige kennis van die voorafgaande dele.<br />

Elke gedeelte werk wat in die klas behandel word, moet dus onmiddellik bestudeer en<br />

verstaan word. Jy moet dus sorg dat jy alles verstaan en kan gebruik.<br />

• Oneerlikheid tydens klastoetse word as 'n baie ernstige oortreding beskou. Die<br />

persoon wat hieraan skuldig is, sowel as die persoon wat sy werk beskikbaar gestel<br />

het, sal hulle punte verbeur, en loop ook gevaar om eksamentoelating geweier te word.<br />

DEELNAMEPUNT<br />

Jou deelnamepunt word saamgestel uit:<br />

• 50% vir klastoetse (teorie en prakties). Die swakste klastoetspunt sal nie bygereken<br />

word nie en geen mediese sertifikate moet ingedien word indien jy ’n toets mis nie.<br />

• 50% vir semestertoets (teorie en prakties).<br />

VEREISTES VIR EKSAMENTOELATING<br />

• ’n Deelnamebewys wat verkry word deur die skryf van die klastoetse en die<br />

inhandiging van alle praktiese opdragte.<br />

• 'n Deelnamepunt van minstens 40%.<br />

• Die universiteit se regulasies rakende die tweede eksamengeleentheid geld vir hierdie<br />

module.<br />

6


EVALUATION<br />

CLASS TESTS<br />

• Both practical assignments and theory class tests will be written each week to evaluate<br />

your progress and to enable you to obtain your pro<strong>of</strong> <strong>of</strong> participation.<br />

• Class tests will be on the work done the previous week, but knowledge <strong>of</strong> previous<br />

work is also essential.<br />

• Class tests on the previous period’s work may also be written without prior warning.<br />

• Each part <strong>of</strong> the work suggests sound knowledge and understanding <strong>of</strong> the preceding<br />

parts. It is therefore important to study and understand every piece <strong>of</strong> the work done in<br />

class immediately. Make sure you understand and are able to use everything.<br />

• Dishonesty during class tests is deemed a serious <strong>of</strong>fence. A person guilty <strong>of</strong> this and<br />

the person making his/her work available, will both forfeit marks and run the risk <strong>of</strong><br />

being denied admission to the examination.<br />

PARTICIPATION MARK<br />

Your participation mark is calculate in the following manner:<br />

• 50% from class tests (theory and practical). The weakest mark is not taken into<br />

account and no medical certificates must be submitted if you missed a test.<br />

• 50% from the semester test (theory and practice).<br />

EXAMINATION ADMISSION REQUIREMENTS<br />

• Writing class tests and submitting all practical assignments give you pro<strong>of</strong> <strong>of</strong><br />

participation.<br />

• You must have a participation mark <strong>of</strong> at least 40%.<br />

• University regulation regarding the second examination opportunity applies to this<br />

module.<br />

6


STUDIE-IKONE<br />

Toets die stand van jou<br />

kennis/insig<br />

Belangrike inligting<br />

Antwoorde / oplossings<br />

Werksopdrag<br />

Skryf die klastoets volgens<br />

skedule<br />

Herskryf hierdie stelling/ konsep<br />

in jou eie woorde sodat jy<br />

verduidelik wat dit beteken<br />

Berei jouself voor vir deelname<br />

oor hierdie onderwerp tydens<br />

die kontaksessie /<br />

groepbyeenkoms Dit is 'n goeie<br />

voorbeeld van 'n eksamenvraag<br />

Uitkomste<br />

Voorbereiding vir die<br />

kontaksessie / groepbyeenkoms<br />

Geskatte studietyd<br />

7


STUDY ICONS<br />

Test your current<br />

knowledge/insight.<br />

Important information.<br />

Answers/solutions.<br />

Assignment.<br />

Write the class test according<br />

to schedule.<br />

Rewrite this statement/ concept<br />

in your own words so that its<br />

meaning is explained.<br />

Prepare yourself for participation<br />

in the group meeting/contact<br />

session on this issue. It is a<br />

good example <strong>of</strong> an examination<br />

question.<br />

Outcomes.<br />

Preparation for contact<br />

session/group meeting.<br />

Estimated study time.<br />

7


WAARSKUWING TEEN PLAGIAAT<br />

WERKSTUKKE IS INDIVIDUELE TAKE EN NIE GROEPAKTIWITEITE NIE (TENSY DIT<br />

UITDRUKLIK AANGEDUI WORD AS ‘N GROEPAKTIWITEIT)<br />

Kopiëring van teks van ander leerders <strong>of</strong> uit ander bronne (byvoorbeeld die studiegids,<br />

voorgeskrewe studiemateriaal <strong>of</strong> direk vanaf die internet) is ontoelaatbaar – net kort<br />

aanhalings is toelaatbaar en slegs indien dit as sodanig aangedui word.<br />

U moet bestaande teks herformuleer en u eie woorde gebruik om te verduidelik wat u<br />

gelees het. Dit is nie aanvaarbaar om bestaande teks/st<strong>of</strong>/inligting bloot oor te tik en die<br />

bron in 'n voetnoot te erken nie – u behoort in staat te wees om die idee <strong>of</strong> begrip/konsep<br />

weer te gee sonder om die oorspronklike skrywer woordeliks te herhaal.<br />

Die doel van die opdragte is nie die blote weergee van bestaande materiaal/st<strong>of</strong> nie, maar<br />

om vas te stel <strong>of</strong> u oor die vermoë beskik om bestaande tekste te integreer, om u eie<br />

interpretasie en/<strong>of</strong> kritiese beoordeling te formuleer en om 'n kreatiewe oplossing vir<br />

bestaande probleme te bied.<br />

Wees gewaarsku: Studente wat gekopieerde teks indien sal 'n nulpunt vir die opdrag<br />

ontvang en dissiplinêre stappe mag deur die Fakulteit en/<strong>of</strong> die Universiteit teen<br />

sodanige studente geneem word. Dit is ook onaanvaarbaar om iemand anders se werk<br />

vir hulle te doen <strong>of</strong> iemand anders in staat te stel om u werk te kopieer – moet dus nie<br />

u werk uitleen <strong>of</strong> beskikbaar stel aan ander nie!<br />

8


WARNING AGAINST PLAGIARISM<br />

ASSIGNMENTS ARE INDIVIDUAL TASKS AND NOT GROUP ACTIVITIES. (UNLESS<br />

EXPLICITLY INDICATED AS GROUP ACTIVITIES)<br />

Copying <strong>of</strong> text from other learners or from other sources (for instance the study guide,<br />

prescribed material or directly from the internet) is not allowed – only brief quotations are<br />

allowed and then only if indicated as such.<br />

You should reformulate existing text and use your own words to explain what you have read.<br />

It is not acceptable to retype existing text and just acknowledge the source in a footnote –<br />

you should be able to relate the idea or concept, without repeating the original author to the<br />

letter.<br />

The aim <strong>of</strong> the assignments is not the reproduction <strong>of</strong> existing material, but to ascertain<br />

whether you have the ability to integrate existing texts, add your own interpretation and/or<br />

critique <strong>of</strong> the texts and <strong>of</strong>fer a creative solution to existing problems.<br />

Be warned: students who submit copied text will obtain a mark <strong>of</strong> zero for the<br />

assignment and disciplinary steps may be taken by the Faculty and/or University. It is<br />

also unacceptable to do somebody else’s work, to lend your work to them or to make<br />

your work available to them to copy – be careful and do not make your work available<br />

to anyone!<br />

8


1 DIE DIE ANALISE ANALISE ANALISE VAN<br />

VAN<br />

ALGORITMES<br />

ALGORITMES ALGORITMES – DEEL DEEL 1<br />

1<br />

Jy behoort ongeveer 10 uur te neem om hierdie leereenheid suksesvol deur te werk.<br />

Hierdie leereenheid is op Ho<strong>of</strong>stuk 2 van die handboek gebaseer.<br />

Aan die einde van hierdie leereenheid behoort jy:<br />

Leereenheid 1<br />

• Die aksiomas rakende die gedetailleerde model van die rekenaar te kan weergee en<br />

toepas;<br />

• ’n program met ‘n dubbele lusstruktuur te kan ontleed;<br />

• ’n rekursiewe funksie te kan ontleed;<br />

• gemiddelde looptye te kan bepaal;<br />

• die vereenvoudigde model van die rekenaar te kan verduidelik en toepas;<br />

• ’n rekursiewe funksie met die vereenvoudigde model te kan ontleed; en<br />

• ’n hersieningsoefening oor grafiese koppelvlakke te kan doen.<br />

9


1. ANALYSIS ANALYSIS OF OF ALGORITH<br />

ALGORITHMS<br />

ALGORITH MS –<br />

PART PART 1<br />

1<br />

You will need approximately 10 hours to successfully complete the work in this study unit.<br />

This study unit is based on Chapter 2 <strong>of</strong> the textbook.<br />

On completion <strong>of</strong> this study unit you should be able to:<br />

• Recall and apply the axioms regarding the detailed model <strong>of</strong> the computer;<br />

• analyse a program with a double loop structure;<br />

• analyse a recursive function;<br />

• determine the average running time;<br />

• explain and apply the simplified model <strong>of</strong> the computer;<br />

• analyse a recursive function by using the simplified model; and<br />

• do a revision exercise on graphic interfaces.<br />

9


Berei voor in die handboek:<br />

• Paragrawe 2.1.1 tot 2.1.6 – maak seker dat jy die aksiomas verstaan.<br />

• Paragraaf 2.1.7 oor die gemiddelde looptyd van ’n funksie.<br />

• Paragrawe 2.1.8 tot 2.1.9 kan oorgeslaan word.<br />

• Paragraaf 2.1.10 oor die nuutste aksioma.<br />

• Paragrawe 2.2.1 tot 2.2.6 oor die vereenvoudigde model van die rekenaar.<br />

Doen oefeninge 2.1 (a, d, g).<br />

Leereenheid 1<br />

Kontroleer jou antwoorde met dié wat deur die dosent beskikbaar gestel word. Maak seker<br />

dat jy hierdie week al jou probleme met hierdie afdeling uitsorteer.<br />

Die voorbeeld op bladsy 23 en 24 is deurslaggewend. Sekere van die ouer handboeke het<br />

’n drukfout op bl 24. Maak seker dat jou handboek reg is – hierdie fout sal tydens die<br />

klasperiode uitgewys word.<br />

Daar sal ‘n alternatiewe bewysmetode vir die stelling in paragraaf 2.2.2 in die klas bespreek<br />

word. Maak seker dat jy dit verstaan.<br />

Praktiese opdrag<br />

Doen Opdrag 1 agter in die studiegids. Die datum van inhandiging sal aan die begin van die<br />

week aangekondig word. Bestudeer klasbespreking 1 as hersiening van ITRW212 se werk.<br />

Maak seker dat jy al die uitkomste van hierdie leereenheid bereik het.<br />

10


Prepare from the textbook:<br />

• Paragraphs 2.1.1 – 2.1.6. Make sure that you understand axioms.<br />

• Paragraph 2.1.7 on the average running time <strong>of</strong> a function.<br />

• Paragraphs 2.1.8 and 2.1.9 can be skipped.<br />

• Paragraphs 2.1.10 on the latest axioms.<br />

• Paragraphs 2.2.1 – 2.2.6 regarding the simplified model <strong>of</strong> the computer.<br />

Do exercises 2.1 (a, d, g).<br />

Check your answers by comparing them with those provided by the lecturer. Sort out any<br />

problems that you have with this section by the end <strong>of</strong> this week.<br />

The example on pages 23 and 24 is significant. Some <strong>of</strong> the older textbooks have a printing<br />

error on page 24. Make sure that your textbook is correct – the error will be pointed out to<br />

you during class.<br />

An alternative method <strong>of</strong> proving the premise in paragraph 2.2.2 will be discussed in class.<br />

Make sure that you understand it.<br />

Practical assignment<br />

Do assignment 1 at the back <strong>of</strong> this study guide. The submission date will be announced at<br />

the start <strong>of</strong> the week. Study Class Discussion 1 to review the work done in ITRW 212.<br />

Make sure that you attained the outcomes set for this study unit.<br />

10


2 DIE DIE ANALISE ANALISE ANALISE VAN<br />

VAN<br />

ALGORITMES<br />

ALGORITMES ALGORITMES – DEEL DEEL 2<br />

2<br />

Jy behoort ongeveer 10 uur te neem om hierdie leereenheid suksesvol deur te werk.<br />

Hierdie leereenheid is op Ho<strong>of</strong>stuk 3 van die handboek gebaseer.<br />

Aan die einde van hierdie leereenheid behoort jy:<br />

• Die definisies van asimtotiese ontleding met insig te kan verduidelik;<br />

• sekere van die stellings te kan bewys; en<br />

• funksies asimtoties te kan ontleed.<br />

Berei voor in die handboek:<br />

• Paragraaf 3.1. Jy kan die bewyse van stellings 3.6 en 3.7 oorslaan.<br />

• Paragraaf 3.2. Jy kan die bewys van stelling 3.8 oorslaan.<br />

• Paragraaf 3.3. Maak seker dat jy hierdie definisies ken en verstaan.<br />

• Paragraaf 3.4 oor die toepassing van asimtotiese ontleding.<br />

Leereenheid 2<br />

11


Study unit 2<br />

2. ANALYSIS ANALYSIS OF OF ALGORITH<br />

ALGORITHMS<br />

ALGORITH MS –<br />

PART PART 2<br />

2<br />

You will need approximately 10 hours to successfully complete the work in this study unit.<br />

This study unit is based on Chapter 3 in the textbook.<br />

On completion <strong>of</strong> this study unit you should be able to:<br />

• Explain with insight the definitions <strong>of</strong> asymptotic analysis;<br />

• prove some <strong>of</strong> the premises; and<br />

• analyse functions asymptotically.<br />

Prepare from the textbook:<br />

• Paragraph 3.1. You can skip the pro<strong>of</strong> <strong>of</strong> Theorems 3.6 and 3.7.<br />

• Paragraph 3.2. You can skip the pro<strong>of</strong> <strong>of</strong> Theorem 3.8.<br />

• Paragraph 3.3. Make sure you know and understand the definitions.<br />

• Paragraph 3.4 on the application <strong>of</strong> asymptotic analysis.<br />

11


Doen oefening 3.1.<br />

Leereenheid 2<br />

Kontroleer jou antwoorde met dié wat deur die dosent beskikbaar gestel word. Maak seker<br />

dat jy hierdie week al jou probleme met hierdie afdeling uitsorteer.<br />

Jy moet die stellings se bewyse nie as leerwerk beskou nie, maar eerder as toepassings van<br />

die ander stelllings.<br />

Praktiese opdrag<br />

Doen Opdrag 2 agter in die studiegids. Die datum van inhandiging sal aan die begin van die<br />

week aangekondig word.<br />

Maak seker dat jy al die uitkomste van hierdie leereenheid bereik het.<br />

12


Do exercise 3.1.<br />

Study unit 2<br />

Compare your answers with those given to you by your lecturer. Be sure to sort out any<br />

difficulties that you may have with the section by the end <strong>of</strong> this week.<br />

The pro<strong>of</strong> <strong>of</strong> the premises must not be regarded as work to be studied, but rather as<br />

applications <strong>of</strong> the other premises.<br />

Practical assignment<br />

Do Assignment 2 at the back <strong>of</strong> the study guide. The submission date will be announced at<br />

the start <strong>of</strong> the week.<br />

Make sure that you attained the outcomes <strong>of</strong> this study unit.<br />

12


3 SKIKKINGS SKIKKINGS EN EN MATRIKS<br />

MATRIKSE<br />

MATRIKS<br />

Jy behoort ongeveer 10 uur te neem om hierdie leereenheid suksesvol deur te werk.<br />

Hierdie leereenheid is op paragrawe 4.1 en 4.2 van die handboek gebaseer.<br />

Aan die einde van hierdie leereenheid behoort jy:<br />

• Skikkings as datastrukture te kan gebruik;<br />

• die “Object”-datatipe van Java te kan gebruik; en<br />

• multidimensionele skikkings te kan gebruik.<br />

Berei voor in die handboek:<br />

Leereenheid 3<br />

• Paragraaf 4.1 oor skikkings – dit is baie belangrike werk en moet verstaan word om die<br />

res van die kursus te kan bemeester.<br />

• Paragraaf 4.2 oor multidimensionele skikkings.<br />

13


3. ARRAYS ARRAYS AND AND AND MATRIXES<br />

MATRIXES<br />

You will need approximately 10 hours to successfully complete this study unit.<br />

This study unit is based on paragraphs 4.1 and 4.2 in the textbook.<br />

At the end <strong>of</strong> this study unit you should be able to:<br />

• Use arrays and data structures;<br />

• use Java’s Object data type; and<br />

• use multi-dimensional arrays.<br />

Prepare from the textbook:<br />

Study unit 3<br />

• Paragraph 4.1 on arrays – the work is very important, and to master the remainder <strong>of</strong><br />

the course, you must understand this section.<br />

• Paragraph 4.2 on multi-dimensional arrays.<br />

13


Doen oefening 4.3.<br />

Leereenheid 3<br />

Kontroleer jou antwoorde met dié wat deur die dosent beskikbaar gestel word. Maak seker<br />

dat jy hierdie week al jou probleme met hierdie afdeling uitsorteer.<br />

Dis van kardinale belang dat jy die “Object”-datatipe/-klas begryp. Jy moet hierdie week se<br />

prakties as die belangrikste van die hele semester beskou, omdat jy die volgende praktiese<br />

opdragte op hierdie een bou.<br />

Praktiese opdrag<br />

Doen Opdrag 3 agter in die studiegids. Die datum van inhandiging sal aan die begin van die<br />

week aangekondig word.<br />

Maak seker dat jy al die uitkomste van hierdie leereenheid bereik het.<br />

14


Do exercise 4.3.<br />

Study unit 3<br />

Check your answers by comparing them with those provided by your lecturer. Be sure to sort<br />

out any problems that you have with this section by the end <strong>of</strong> the week.<br />

It is <strong>of</strong> absolute importance that you understand the Object data type/class. Consider the<br />

practical work that you do this week as the most important <strong>of</strong> the semester. This assignment<br />

will be the basis for the assignments that will follow.<br />

Practical assignment<br />

Do Assignment 3 at the back <strong>of</strong> the study guide. The submission date will be announced in<br />

class at the start <strong>of</strong> the week.<br />

Make sure you achieved all the outcomes set for this study unit.<br />

14


4 GESKAKELDE GESKAKELDE LYSTE<br />

LYSTE<br />

Jy behoort ongeveer 10 uur te neem om hierdie leereenheid suksesvol deur te werk.<br />

Hierdie leereenheid is op paragraaf 4.3 van die handboek gebaseer.<br />

Aan die einde van hierdie leereenheid behoort jy:<br />

• Geskakelde lyste as datastrukture te kan gebruik; en<br />

• die “Object”-datatipe van Java in geskakelde lyste te kan gebruik.<br />

Berei voor in die handboek:<br />

Leereenheid 4<br />

Paragraaf 4.3 oor skikkings – dit is baie belangrike werk en moet verstaan word om die res<br />

van die kursus te kan bemeester.<br />

15


4. LINKED LINKED LISTS<br />

LISTS<br />

Study unit 4<br />

You will need approximately 10 hours to successfully complete the work in this study unit.<br />

This study unit is based on paragraph 4.3 <strong>of</strong> the textbook.<br />

At the end <strong>of</strong> this study unit you should be able to:<br />

• Use linked lists as data structures; and<br />

• use the Java’s Object data type in linked lists.<br />

Prepare from the textbook:<br />

Paragraph 4.3 on arrays. This is very important work and must be understood in order to<br />

master the rest <strong>of</strong> the course.<br />

15


Doen programmeringsoefening 4.3.<br />

Leereenheid 4<br />

Kontroleer jou antwoorde met dié wat deur die dosent beskikbaar gestel word. Maak seker<br />

dat jy hierdie week al jou probleme met hierdie afdeling uitsorteer.<br />

Dis van kardinale belang dat jy die “Object”-datatipe/-klas begryp. Hierdie week se prakties<br />

gebruik nie die “Object”-klas nie – weet jy waarom nie?<br />

Praktiese opdrag<br />

Doen Opdrag 4 agter in die studiegids. Die datum van inhandiging sal aan die begin van die<br />

week aangekondig word.<br />

Maak seker dat jy al die uitkomste van hierdie leereenheid bereik het.<br />

16


Do programming exercise 4.3.<br />

Study unit 4<br />

Check your answers against those provided by your lecturer. Sort out any problems that you<br />

have with this section by the end <strong>of</strong> the week.<br />

It is <strong>of</strong> absolute importance that you understand the Object data type/class. The Object class<br />

is not used in this week’s practical work – do you know why?<br />

Practical assignment<br />

Do Assignment 4 at the back <strong>of</strong> the study guide. The submission date will be announced in<br />

class at the start <strong>of</strong> the week.<br />

Make sure that you attained all outcomes set for this study unit.<br />

16


Leereenheid 5<br />

5 DATATIPES DATATIPES EN EN ABSTRAK<br />

ABSTRAKSIE<br />

ABSTRAK SIE –<br />

DEEL DEEL 1<br />

1<br />

Jy behoort ongeveer 10 uur te neem om hierdie leereenheid suksesvol deur te werk.<br />

Hierdie leereenheid is op paragrawe 5.1 tot 5.2.4 van die handboek gebaseer.<br />

Aan die einde van hierdie leereenheid behoort jy:<br />

• Met insig te kan verduidelik wat abstrakte datatipes is;<br />

• die klashiërargie van die handboek met insig te kan verduidelik;<br />

• ’n koppelvlak te kan ontwerp;<br />

• met insig te kan verduidelik wat “wrapper”-klasse is, en waarom dit nodig is om hulle te<br />

gebruik;<br />

• te weet wat houer-klasse is; en<br />

• die “Object”-datatipe van Java te kan gebruik.<br />

17


5. DATA DATA TYPES TYPES AND<br />

AND<br />

ABSTRACTION ABSTRACTION – PART PART 1<br />

1<br />

You will need approximately 10 hours to successfully complete this study unit.<br />

This study unit is based on paragraphs 5.1 to 5.2.4 in the textbook.<br />

At the end <strong>of</strong> this study unit you should be able to:<br />

• Explain abstract data types with insight;<br />

• explain the class hierarchy <strong>of</strong> the textbook with insight;<br />

• design an interface;<br />

• explain wrapper classes with insight and why it is necessary to use them;<br />

• know what container classes are; and<br />

• use Java’s Object data type.<br />

Study unit 5<br />

17


Berei voor in die handboek:<br />

• Paragraaf 5.1 oor abstrakte datatipes.<br />

• Paragraaf 5.2 oor ontwerpspatrone tot en met paragraaf 5.2.4.<br />

• Klasbespreking 2 agter in die studiegids.<br />

Doen oefening 5.3.<br />

Leereenheid 5<br />

Kontroleer jou antwoorde met dié wat deur die dosent beskikbaar gestel word. Maak seker<br />

dat jy hierdie week al jou probleme met hierdie afdeling uitsorteer.<br />

Studente beskou hierdie ho<strong>of</strong>stuk as die moeilikste van die kursus. Klasbespreking 2 is ’n<br />

poging om die verduideliking van die handboek aan te vul. Werk die program deur en merk<br />

elke program met ’n regmerkie as jy dit verstaan en ’n kruisie indien jy onseker is. Werk die<br />

hele program aan die hand van die klasbespreking op hierdie manier deur. Wanneer jy klaar<br />

is, herhaal dit en kyk <strong>of</strong> jy van die lyne wat met kruisies gemerk is, nou verstaan. Jy moet<br />

besef dat jy hierdie program drie tot vier keer so op jou eie sal moet deurwerk voordat jy alles<br />

sal verstaan. ’n Addisionele lesing sal geskeduleer word om individuele probleme op te los.<br />

Jy moet egter eers jou probleme op hierdie manier identifiseer voordat jy die lesing bywoon.<br />

Praktiese opdrag<br />

Doen Opdrag 5 agter in die studiegids. Die datum van inhandiging sal aan die begin van die<br />

week aangekondig word.<br />

Maak seker dat jy al die uitkomste van hierdie leereenheid bereik het.<br />

18


Prepare from the textbook:<br />

• Paragraph 5.1 on abstract data types.<br />

• Paragraph 5.2 on design patterns up to paragraph 5.2.4.<br />

• Class discussion 2 at the back <strong>of</strong> the study guide.<br />

Do exercise 5.3.<br />

Study unit 5<br />

Compare your answers with those provided by your lecturer. Sort out all problems that you<br />

have with this section by the end <strong>of</strong> this week.<br />

This chapter is regarded by students to be the most difficult <strong>of</strong> the course. Class Discussion<br />

2 attempts to elucidate the explanation that you find in the textbook. Study the program and<br />

tick each one that you understand and make a cross next to the ones that you are unsure <strong>of</strong>.<br />

Study the whole program with the aid <strong>of</strong> the Class Discussion in this manner. When you are<br />

finished, repeat the process and check if the lines that you marked with a cross are now clear<br />

to you. You will need to go through the program three to four times in this manner before you<br />

will be able to understand it all. An extra lecture will be scheduled to answer any individual<br />

problems there may be. You must identify your problems in this manner before attending the<br />

lecture.<br />

Practical assignment<br />

Do Assignment 5 at the back <strong>of</strong> the study guide. The submission date will be announced in<br />

class at the start <strong>of</strong> the week.<br />

Make sure that you attained the outcomes <strong>of</strong> this study unit.<br />

18


Leereenheid 6<br />

6 DATATIPES DATATIPES EN EN ABSTRAK<br />

ABSTRAKSIE<br />

ABSTRAK SIE –<br />

DEEL DEEL 2<br />

2<br />

Jy behoort ongeveer 10 uur te neem om hierdie leereenheid suksesvol deur te werk.<br />

Hierdie leereenheid is op paragrawe 5.2.5 tot 5.7 van die handboek gebaseer.<br />

Aan die einde van hierdie leereenheid behoort jy:<br />

• Met insig te kan verduidelik wat ontwerpspatrone is;<br />

• die klashiërargie van die handboek met insig te kan verduidelik;<br />

• ‘visitors’ met insig te kan verduidelik;<br />

• ‘enumerations’ met insig te kan verduidelik; en<br />

• te weet wat deursoekbare houerklasse is.<br />

Berei voor in die handboek:<br />

• Paragraaf 5.2.5 wat handel oor ‘visitors’.<br />

• Paragraaf 5.2.6 wat handel oor ‘enumerations’.<br />

• Paragraaf 5.2.7 wat handel oor ‘searchable containers’.<br />

• Klasbespreking 2 agter in die studiegids.<br />

19


6. DATA DATA TYPES TYPES AND<br />

AND<br />

ABSTRACTION ABSTRACTION – PART PART 2<br />

2<br />

Study unit 6<br />

You will need approximately 10 hours to successfully complete the work in this study unit.<br />

This study unit is based on paragraphs 5.2.5 to 5.7 in the textbook.<br />

At the end <strong>of</strong> this study unit you should be able to:<br />

• Explain design patterns with insight;<br />

• explain the class hierarchy <strong>of</strong> the textbook with insight;<br />

• explain visitors with insight;<br />

• explain enumerations with insight; and<br />

• know what searchable container classes are.<br />

Prepare from the textbook:<br />

• Paragraph 5.2.5 regarding visitors.<br />

• Paragraph 5.2.6 regarding enumerations.<br />

• Paragraph 5.2.7 regarding searchable containers.<br />

• Class Discussion 2 at the back <strong>of</strong> the study guide.<br />

19


Doen oefening 5.3.<br />

Leereenheid 6<br />

Kontroleer jou antwoorde met dié wat deur die dosent beskikbaar gestel word. Maak seker<br />

dat jy hierdie week al jou probleme met hierdie afdeling uitsorteer.<br />

Praktiese opdrag<br />

Gebruik hierdie week om seker te maak dat jy Opdrag 1-5 volledig verstaan.<br />

Maak seker dat jy al die uitkomste van hierdie leereenheid bereik het.<br />

20


Do exercise 5.3.<br />

Study unit 6<br />

Compare your answers with those provided by your lecturer. Sort out any problems that you<br />

may have with this section by the end <strong>of</strong> this week.<br />

Practical assignment<br />

Go through Assignments 1 – 5 this week and make sure that you understand them all<br />

completely.<br />

Make sure that you attained the outcomes <strong>of</strong> this study unit.<br />

20


7 STAPEL STAPELS STAPEL<br />

Jy behoort ongeveer 10 uur te neem om hierdie leereenheid suksesvol deur te werk.<br />

Hierdie leereenheid is op paragraaf 6.1 van die handboek gebaseer.<br />

Aan die einde van hierdie leereenheid behoort jy:<br />

• Stapels as datastrukture met insig te kan verduidelik;<br />

• stapels met behulp van skikkings te kan implementeer; en<br />

• stapels met behulp van geskakelde lyste te kan implementeer.<br />

Berei voor in die handboek:<br />

• Paragraaf 6.1 wat handel oor stapels.<br />

• Paragraaf 6.1.1 wat handel oor stapels met behulp van skikkings.<br />

• Paragraaf 6.1.2 wat handel oor stapels met behulp van geskakelde lyste.<br />

• Paragraaf 6.1.3 wat handel oor die toepassings van stapels.<br />

• Klasbespreking 3 agter in die studiegids.<br />

Leereenheid 7<br />

21


7. STACKS<br />

STACKS<br />

Study unit 7<br />

You will need approximately 10 hours to successfully complete the work in this study unit.<br />

This study unit is based on paragraph 6.1 in the textbook.<br />

At the end <strong>of</strong> this study unit you should be able to:<br />

• Explain stacks as data structures with insight;<br />

• implement stacks with the aid <strong>of</strong> arrays; and<br />

• implement stacks with the aid <strong>of</strong> linked lists.<br />

Prepare from the textbook:<br />

• Paragraph 6.1 regarding stacks.<br />

• Paragraph 6.1.1 regarding stacks with the aid <strong>of</strong> arrays.<br />

• Paragraphs 6.1.2 on stack with the aid <strong>of</strong> linked lists.<br />

• Paragraph 6.1.3 regarding the applications <strong>of</strong> stacks.<br />

• Class Discussion 3 at the back <strong>of</strong> the study guide.<br />

21


Doen oefening 6.1.<br />

Leereenheid 7<br />

Kontroleer jou antwoorde met dié wat deur die dosent beskikbaar gestel word. Maak seker<br />

dat jy hierdie week al jou probleme met hierdie afdeling uitsorteer.<br />

Dit is baie belangrik om nie kode te memoriseer nie. Jy sal soortgelyke kode in die eksamen<br />

moet skryf oor vreemde probleme. Jy moet dus die kode verstaan! Jy moet Klasbespreking<br />

3 op dieselfde manier as Klasbespreking 2 deurwerk.<br />

Praktiese opdrag<br />

Doen die stapelgedeelte en die skermuitleg van Opdrag 6.<br />

Maak seker dat jy al die uitkomste van hierdie leereenheid bereik het.<br />

22


Do exercise 6.1.<br />

Study unit 7<br />

Check your answers by comparing them with those provided by you lecturer. Make sure that<br />

you sort out any problems that you have with this section by the end <strong>of</strong> this week.<br />

Please do not memorise code. In the examination you will have to write similar code for<br />

unfamiliar problems. This implies that you have to understand the code! Work through Class<br />

Discussion 3 in the same manner as you did Class discussion 2.<br />

Practical assignment<br />

Do the sections on stacks and screen layout <strong>of</strong> Assignment 6.<br />

Make sure that you attained the outcomes <strong>of</strong> this study unit.<br />

22


8 TOUE<br />

TOUE<br />

Jy behoort ongeveer 10 uur te neem om hierdie leereenheid suksesvol deur te werk.<br />

Hierdie leereenheid is op paragraaf 6.2 - 6.3 van die handboek gebaseer.<br />

Aan die einde van hierdie leereenheid behoort jy:<br />

• Toue as datastrukture met insig te kan verduidelik;<br />

• toue met behulp van skikkings te kan implementeer;<br />

• toue met behulp van geskakelde lyste te kan implementeer; en<br />

• “dequeues” met insig te kan verduidelik.<br />

Leereenheid 8<br />

23


8. QUEUES<br />

QUEUES<br />

Study unit 8<br />

You will need approximately 10 hours to successfully complete the work in this study unit.<br />

This study unit is base on paragraph 6.2 and 6.3 <strong>of</strong> the textbook.<br />

At the end <strong>of</strong> this study unit you should be able to:<br />

• Explain queues as data structures with insight;<br />

• implement queues with the aid <strong>of</strong> arrays;<br />

• implement queues with the aid <strong>of</strong> linked lists; and<br />

• explain dequeues with insight.<br />

23


Berei voor in die handboek:<br />

• Paragraaf 6.2 wat handel oor toue.<br />

• Paragraaf 6.2.1 wat handel oor toue met behulp van skikkings.<br />

• Paragraaf 6.2.2 wat handel oor toue met behulp van geskakelde lyste.<br />

• Paragraaf 6.2.3 wat handel oor die toepassings van toue.<br />

• Paragraaf 6.3 wat handel oor "dequeues".<br />

• Klasbespreking 3 agter in die studiegids.<br />

Doen oefening 6.7.<br />

Leereenheid 8<br />

Kontroleer jou antwoorde met dié wat deur die dosent beskikbaar gestel word. Maak seker<br />

dat jy hierdie week al jou probleme met hierdie afdeling uitsorteer.<br />

Dit is baie belangrik om nie kode te memoriseer nie. Jy sal soortgelyke kode in die eksamen<br />

moet skryf oor vreemde probleme. Jy moet dus die kode verstaan!<br />

Praktiese opdrag<br />

Doen Opdrag 6 volledig.<br />

Maak seker dat jy al die uitkomste van hierdie leereenheid bereik het.<br />

24


Prepare from the textbook:<br />

• Paragraph 6.2 regarding queues.<br />

• Paragraph 6.2.1 regarding queues with the aid <strong>of</strong> arrays.<br />

• Paragraph 6.2.2 regarding queues with the aid <strong>of</strong> linked lists.<br />

• Paragraph 6.2.3 regarding the applications <strong>of</strong> queues.<br />

• Paragraph 6.3 on dequeues.<br />

• Class Discussion 3 at the back <strong>of</strong> the study guide.<br />

Do exercise 6.7.<br />

Study unit 8<br />

Check your answers by comparing them with those provided by you lecturer. Make sure that<br />

you sort out any problems that you have with this section by the end <strong>of</strong> this week.<br />

Please do not memorise code. You will have to write similar code for unfamiliar problems<br />

during the examination. This implies that you have to understand the code!<br />

Practical assignment<br />

Complete Assignment 6.<br />

Make sure that you attained all the outcomes set for this study unit.<br />

24


9 GEORDENDE GEORDENDE LYSTE<br />

LYSTE<br />

Jy behoort ongeveer 10 uur te neem om hierdie leereenheid suksesvol deur te werk.<br />

Hierdie leereenheid is op paragraaf 7.1 van die handboek gebaseer.<br />

Aan die einde van hierdie leereenheid behoort jy:<br />

• Geordende lyste as datastrukture met insig te kan verduidelik;<br />

• geordende lyste met behulp van skikkings te kan implementeer; en<br />

• geordende lyste met behulp van geskakelde lyste te kan implementeer.<br />

Berei voor in die handboek:<br />

• Paragraaf 7.1 wat handel oor geordende lyste.<br />

• Paragraaf 7.1.1 wat handel oor geordende lyste met behulp van skikkings.<br />

Leereenheid 9<br />

• Paragraaf 7.1.2 wat handel oor geordende lyste met behulp van geskakelde lyste.<br />

• Paragraaf 7.1.3 wat handel oor die vergelyking tussen skikkings en geskakelde lyste.<br />

• Paragraaf 7.1.4 wat handel oor die toepassing van geordende lyste.<br />

25


9. ORDERED ORDERED LISTS<br />

LISTS<br />

Study unit 9<br />

You will need approximately 10 hours to successfully complete the work in this study unit.<br />

This study unit is based on paragraph 7.1 in the textbook.<br />

At the end <strong>of</strong> this study unit you should be able to:<br />

• Explain ordered lists as data structures with insight;<br />

• implement ordered lists with the aid <strong>of</strong> arrays; and<br />

• implement ordered lists with the aid <strong>of</strong> linked lists.<br />

Prepare from the textbook:<br />

• Paragraph 7.1 regarding ordered lists.<br />

• Paragraph 7.1.1 on ordered lists with the aid <strong>of</strong> arrays.<br />

• Paragraph 7.1.2 on ordered lists with the aid <strong>of</strong> linked lists.<br />

• Paragraph 7.1.3 on the comparison between arrays and linked lists.<br />

• Paragraph 7.1.4 on the application <strong>of</strong> ordered lists.<br />

25


Doen oefening 7.2.<br />

Leereenheid 9<br />

Kontroleer jou antwoorde met dié wat deur die dosent beskikbaar gestel word. Maak seker<br />

dat jy hierdie week al jou probleme met hierdie afdeling uitsorteer.<br />

Dit is baie belangrik om nie kode te memoriseer nie. Jy sal soorgelyke kode in die eksamen<br />

moet skryf oor vreemde probleme. Jy moet dus die kode verstaan!<br />

Praktiese opdrag<br />

Doen Opdrag 7.<br />

Maak seker dat jy al die uitkomste van hierdie leereenheid bereik het.<br />

26


Do exercise 7.2.<br />

Study unit 9<br />

Check your answers by comparing them with those provided by your lecturer. Sort out any<br />

difficulties that you have with this section by the end <strong>of</strong> this week.<br />

Please do not memorise code. You will have to write similar code for unfamiliar problems in<br />

the examination. This implies that you have to understand the code!<br />

Practical assignment<br />

Do Assignment 7.<br />

Make sure that you attained all the outcomes <strong>of</strong> this study unit.<br />

26


10 10 GESORTEERDE GESORTEERDE LYSTE<br />

LYSTE<br />

Jy behoort ongeveer 10 uur te neem om hierdie leereenheid suksesvol deur te werk.<br />

Hierdie leereenheid is op paragraaf 7.2 van die handboek gebaseer.<br />

Aan die einde van hierdie leereenheid behoort jy:<br />

• Gesorteerde lyste as datastrukture met insig te kan verduidelik;<br />

• gesorteerde lyste met behulp van skikkings te kan implementeer; en<br />

• gesorteerde lyste met behulp van geskakelde lyste te kan implementeer.<br />

Berei voor in die handboek:<br />

• Paragraaf 7.1 wat handel oor gesorteerde lyste.<br />

• Paragraaf 7.2.1 wat handel oor gesorteerde lyste met behulp van skikkings.<br />

Leereenheid 10<br />

• Paragraaf 7.2.2 wat handel oor gesorteerde lyste met behulp van geskakelde lyste.<br />

• Paragraaf 7.2.3 wat handel oor die vergelyking tussen skikkings en geskakelde lyste.<br />

• Paragraaf 7.2.4 wat handel oor die toepassing van gesorteerde lyste.<br />

27


10. 10. SORTED SORTED SORTED LISTS<br />

LISTS<br />

Study unit 10<br />

You will need approximately 10 hours to successfully complete the work in this study unit.<br />

This study unit is based on paragraph 7.2 <strong>of</strong> the textbook.<br />

At the end <strong>of</strong> this study unit you should be able to:<br />

• Explain sorted lists as data structures with insight;<br />

• implement sorted lists with the aid <strong>of</strong> arrays; and<br />

• implement sorted lists with the aid <strong>of</strong> linked lists.<br />

Prepare from the textbook:<br />

• Paragraph 7.1 regarding sorted lists.<br />

• Paragraph 7.2.1 on sorted lists with the aid <strong>of</strong> arrays.<br />

• Paragraph 7.2.2 on sorted lists with the aid <strong>of</strong> linked lists.<br />

• Paragraph 7.2.3 on the comparison between arrays and linked lists.<br />

• Paragraphs 7.2.4 on the application <strong>of</strong> sorted lists.<br />

27


Doen oefening 7.2.<br />

Leereenheid 10<br />

Kontroleer jou antwoorde met dié wat deur die dosent beskikbaar gestel word. Maak seker<br />

dat jy hierdie week al jou probleme met hierdie afdeling uitsorteer.<br />

Dit is baie belangrik om nie kode te memoriseer nie. Jy sal soortgelyke kode in die eksamen<br />

moet skryf oor vreemde probleme. Jy moet dus die kode verstaan!<br />

Praktiese opdrag<br />

Jy moet hierdie week vir jou praktiese toets voorberei.<br />

Maak seker dat jy al die uitkomste van hierdie leereenheid bereik het.<br />

28


Do exercise 7.2.<br />

Study unit 10<br />

Check your answers by comparing them with those provided by the lecturer. Sort out any<br />

problems that you have with this section by the end <strong>of</strong> this week.<br />

Please do not memorise code. You must write similar code for unfamiliar problems during the<br />

examination. This implies that you have to understand the code!<br />

Practical assignment<br />

Prepare for the practical test.<br />

Make sure that you attained the outcomes set for this study unit.<br />

28


Leereenheid 11<br />

11 11 SORTERINGSALGORITMES SORTERINGSALGORITMES -<br />

DEEL DEEL 1<br />

1<br />

Jy behoort ongeveer 10 uur te neem om hierdie leereenheid suksesvol deur te werk.<br />

Hierdie leereenheid is op paragrawe 15.1 tot 15.5 van die handboek gebaseer.<br />

Aan die einde van hierdie leereenheid behoort jy:<br />

• ’n Verskeidenheid sorteer-algoritmes te kan implementeer en analiseer; en<br />

• verskillende sorteer-algoritmes met mekaar te kan vergelyk.<br />

29


11. 11. SORTING SORTING ALGORITHMS ALGORITHMS -<br />

PART PART 1<br />

1<br />

Study unit 11<br />

You will need approximately 10 hours to successfully complete the work in this study unit.<br />

This study unit is based on paragraphs 15.1 to 15.5 in the textbook.<br />

At the end <strong>of</strong> this study unit you should be able to:<br />

• Implement and analyse a variety <strong>of</strong> sorting algorithms; and<br />

• compare various sorting algorithms.<br />

29


Berei voor in die handboek:<br />

• Paragrawe 15.1 en 15.2 wat handel oor sortering in die algemeen.<br />

• Paragraaf 15.3 wat handel oor invoeging.<br />

• Paragraaf 15.4 wat handel oor omruiling.<br />

• Paragraaf 15.5 wat handel oor seleksie.<br />

• Paragraaf 15.6 wat handel oor samevoeging.<br />

• Paragraaf 15.7 wat handel oor ’n ondergrens vir sortering.<br />

• Paragraaf 15.8 wat handel oor verspreiding.<br />

Doen oefening 15.5.<br />

Leereenheid 11<br />

Kontroleer jou antwoorde met dié wat deur die dosent beskikbaar gestel word. Maak seker<br />

dat jy hierdie week al jou probleme met hierdie afdeling uitsorteer.<br />

Dit is baie belangrik om nie kode te memoriseer nie. Jy sal soortgelyke kode in die eksamen<br />

moet skryf oor vreemde probleme. Jy moet dus die kode verstaan!<br />

Praktiese opdrag<br />

Jy moet hierdie week vir jou praktiese toets voorberei.<br />

Maak seker dat jy al die uitkomste van hierdie leereenheid bereik het.<br />

30


Prepare from the textbook:<br />

• Paragraphs 15.1 and 15.2 on sorting in general.<br />

• Paragraph 15.3 on insertion.<br />

• Paragraph 15.4 on exchange.<br />

• Paragraph 15.5 on selection.<br />

• Paragraph 15.6 on merging.<br />

• Paragraph on a lower bound on sorting.<br />

• Paragraph 15.8 on distribution.<br />

Do exercise 15.5.<br />

Study unit 11<br />

Check your answers by comparing them with those provided by your lecturer. Sort out any<br />

problems that you have with this section by the end <strong>of</strong> this week.<br />

Please do not memorise code. In the examination you will have to write similar code for<br />

unfamiliar problems. This implies that you have to understand the code!<br />

Practical assignment<br />

Prepare for the practical test.<br />

Make sure that you attained all the outcomes set for this study unit.<br />

30


Leereenheid 12<br />

12 12 SORTERINGSALGORITMES SORTERINGSALGORITMES -<br />

DEEL DEEL 2<br />

2<br />

Jy behoort ongeveer 10 uur te neem om hierdie leereenheid suksesvol deur te werk.<br />

Hierdie leereenheid is op paragrawe 15.6 tot 15.9 van die handboek gebaseer.<br />

Aan die einde van hierdie leereenheid behoort jy:<br />

• ’n Verskeidenheid sorteer-algorimes te kan implementeer en analiseer; en<br />

• verskillende sorteer-algoritmes met mekaar te kan vergelyk.<br />

Berei voor in die handboek:<br />

• Paragraaf 15.6 wat handel oor samevoeging.<br />

• Paragraaf 15.7 wat handel oor ’n ondergrens vir sortering.<br />

• Paragraaf 15.8 wat handel oor verspreiding.<br />

• Paragraaf 15.9 wat handel oor “performance data.”<br />

31


12. 12. SORTING SORTING ALGORITHMS ALGORITHMS –<br />

PART PART 2<br />

2<br />

Study unit 12<br />

You will need approximately 10 hours to successfully complete the work in this study unit.<br />

This study unit is based on paragraphs 15.6 to 15.9 in the textbook.<br />

At the end <strong>of</strong> the study unit you must be able to:<br />

• Analyse and implement a variety <strong>of</strong> sorting algorithms; and<br />

• compare various sorting algorithms.<br />

Prepare from the textbook:<br />

• Paragraph 15.6 regarding merging.<br />

• Paragraph 15.7 on the lower bound on sorting.<br />

• Paragraph 15.8 on distribution.<br />

• Paragraph 15.9 on performance data.<br />

31


Doen oefening 15.11.<br />

Leereenheid 12<br />

Kontroleer jou antwoorde met dié wat deur die dosent beskikbaar gestel word. Maak seker<br />

dat jy hierdie week al jou probleme met hierdie afdeling uitsorteer.<br />

Dit is baie belangrik om nie kode te memoriseer nie. Jy sal soortgelyke kode in die eksamen<br />

moet skryf oor vreemde probleme. Jy moet dus die kode verstaan! Aan die einde van die<br />

studiegids is ’n voorbeeld van ’n eksamenvraestel vir hierdie module. Gebruik dit om jou<br />

vordering te meet.<br />

Maak seker dat jy al die uitkomste van hierdie leereenheid bereik het.<br />

32


Do exercise 15.11.<br />

Study unit 12<br />

Compare your answers with those provided by your lecturer. Sort out any difficulties that you<br />

have with this section by the end <strong>of</strong> this week.<br />

Please do not memorise code. You will have to write similar code for unfamiliar problems in<br />

the examination. This implies that you have to understand the code! At the end <strong>of</strong> the study<br />

guide you will find an example <strong>of</strong> an examination paper for this module. Evaluate your<br />

progress by completing it.<br />

Make sure that you attained the outcomes set for this study unit.<br />

32


13 13 BOME BOME EN EN GRAFIEKE<br />

GRAFIEKE<br />

Jy behoort ongeveer 10 uur te neem om hierdie leereenheid suksesvol deur te werk.<br />

Leereenheid 13<br />

Hierdie leereenheid is op paragrawe 9.1 tot 9.3 en 16.1 tot 16.3 van die handboek gebaseer.<br />

Aan die einde van hierdie leereenheid behoort jy:<br />

• Die basiese teorie oor bome te kan weergee;<br />

• die basiese teorie oor grafieke te ken; en<br />

• die verskillende maniere om deur bome en grafieke te beweeg te ken.<br />

Berei voor in die handboek:<br />

• Paragraaf 9.1 – 9.3 wat handel oor basiese bome en binêre bome.<br />

• Paragraaf 16.1 – 16.3 wat handel oor die basiese teorie oor grafieke.<br />

33


13. 13. TREES TREES AND AND GRAPHS<br />

GRAPHS<br />

Study unit 13<br />

You will need approximately 10 hours to successfully complete the work in this study unit.<br />

This study unit is based on paragraphs 9.1 to 9.3 and 16.1 to 16.3 in the textbook.<br />

At the end <strong>of</strong> this study unit you should be able to:<br />

• Explain the basic theory regarding trees;<br />

• know the basic theory regarding graphs; and<br />

• know the different ways to move through trees and graphs.<br />

Prepare from the textbook:<br />

• Paragraph 9.1 to 9.3 on basic trees and binary trees.<br />

• Paragraph 16.1 to 16.3 on the basic theory <strong>of</strong> graphs.<br />

33


Doen oefening 9.1 en 16.4.<br />

Leereenheid 13<br />

Kontroleer jou antwoorde met dié wat deur die dosent beskikbaar gestel word. Maak seker<br />

dat jy hierdie week al jou probleme met hierdie afdeling uitsorteer.<br />

Dit is baie belangrik om die teorie te ken rakende bome en grafieke.<br />

Maak seker dat jy al die uitkomste van hierdie leereenheid bereik het.<br />

34


Do exercise 9.1 and 16.4.<br />

Study unit 13<br />

Check your answers by comparing them with those provided by your lecturer. Sort out any<br />

difficulties that you have with this section by the end <strong>of</strong> this week.<br />

It is very important to know the theory regarding trees and graphs.<br />

Make sure you have reached the outcomes set for this study unit.<br />

34


BYLAAG 1 - PRAKTIESE Opdragte<br />

Bylaag 2 - Klasbesprekings<br />

35


Appendix 2<br />

APPENDIX 1 - PRACTICAL ASSIGNMENTS<br />

35


OPDRAG 1: INGEEDATUM: ______________________<br />

Bylaag 2 - Klasbesprekings<br />

Skryf ’n Java-applet wat ’n onbekende aantal heelgetalle een na die ander in ’n TextField sal<br />

inlees (die gebruiker druk Enter tussen die getalle). Die applet moet deur middel van ’n<br />

Label die gesorteede lys van getalle vertoon. Let op die volgende:<br />

• Gebruik ’n vektor (array) om die getalle in te stoor. (Onthou om die string van die<br />

TextField na ’n Integer oor te skakel.)<br />

• Sorteer die vektor na elke nuwe getal ingelees is.<br />

• Onthou om die Label vir die vektor vol leë karakters te verklaar.<br />

• Bou die Label van vooraf elke keer vanaf die vektor op.<br />

36


Appendix 2<br />

ASSIGNMENT 1: SUBMISSION DATE: ______________________<br />

Write a Java applet that will read an unknown number <strong>of</strong> integers one after the other in a<br />

TextField. (The user press Enter in between the numbers). The applet must display the<br />

sorted list <strong>of</strong> numbers by using a Label. Take note <strong>of</strong> the following:<br />

• Use a vector (array) to store the numbers in. (Remember to switch the string <strong>of</strong> the<br />

TextField to an Integer)<br />

• Sort the vector after reading each new number.<br />

• Remember the Label for the vector must be declared full <strong>of</strong> empty characters.<br />

• Each time rebuild the Label from the vector.<br />

36


Bylaag 2 - Klasbesprekings<br />

OPDRAG 2: INGEEDATUM: ___________________________<br />

Verander Opdrag 1 sodat die gebruiker die keuse het om óf die oorspronklike óf die<br />

gesorteerde vektor te sien. Plaas twee Button-objekte op die applet. Let op die volgende:<br />

• Daar is nou drie objekte wat Events kan genereer, naamlik die TextField en die twee<br />

Buttons.<br />

• Die vektor moet gesorteer word wanneer die TextField die Event genereer.<br />

• Onthou om nou ook ’n tweede vektor te maak om die oorspronklike getalle in te stoor.<br />

• Ek het ’n vlaggie (wat verander word as ’n Button gedruk word) gebruik om vas te stel<br />

watter vektor vertoon moet word.<br />

• Wanneer ‘n Button gedruk word, moet die Label dadelik na die regte vektor verander<br />

word en so bly totdat die ander Button weer gedruk word.<br />

BEGIN BETYDS - Dis meer werk as wat jy dink!!!<br />

37


Appendix 2<br />

ASSIGNMENT 2: SUBMISSION DATE: _________________________<br />

Change Assignment 1 to allow the user to see either the original or sorted vector. Place two<br />

Button objects on the applet. Note the following:<br />

• There are three objects able to generate Events: the TextField and two Buttons.<br />

• The vector must be sorted when the TextfField generates the Event.<br />

• Remember to generate a second vector to store the original numbers in.<br />

• I used a flag (that changes and prints as a Button) to determine which vector must be<br />

displayed.<br />

• When the Button is pressed, the Label must immediately change to the correct vector<br />

and remain so until the Button is pressed again.<br />

START NOW - This is much more work than you think!!<br />

37


Bylaag 2 - Klasbesprekings<br />

OPDRAG 3: INGEEDATUM: _____________________________<br />

HERHAAL OPDRAG 1 deur gebruik te maak van die handboek se Array-klas.<br />

Let op:<br />

• Gestel jy het:<br />

Array arr;<br />

arr = new Array(20);<br />

• Wanneer put geroep word vir ’n drywer wat met heelgetalle werk, doen dit soos volg:<br />

arr.put(i, new Integer (num));<br />

waar i die posisie van die element in ’n vektor is, en<br />

num ’n heelgetal is wat met Integer.parseInt() van die teksveld afgelees is.<br />

• Wanneer get geroep word, doen dit soos volg:<br />

num2 = (Integer)arr.get(k)<br />

Arrstring += num2.toString();<br />

JY MOET ALLES IN HIERDIE OPDRAG VERSTAAN OM HIERDIE VAK TE SLAAG!!!!!<br />

38


Appendix 2<br />

ASSIGNMENT 3: SUBMISSION DATE: _________________________<br />

REPEAT ASSIGNMENT 1 by using the textbook’s Array class.<br />

Take note:<br />

• Suppose you have:<br />

Array arr;<br />

arr = new Array(20);<br />

• When put is called for a drive that operates with integers, you do it like this:<br />

arr.put(i , new Integer (num));<br />

when i is the position <strong>of</strong> an element in a vector, and<br />

num is an integer read with Integer.parselnet() from the text field.<br />

• When calling get, do it this way:<br />

num2 = (Integer)arr.get(k)<br />

Arrstring += num2.toString();<br />

YOU MUST UNDERSTAND EVERY ASPECT OF THIS<br />

ASSIGNMENT TO PASS THIS SUBJECT!!<br />

38


Bylaag 2 - Klasbesprekings<br />

OPDRAG 4: INGEEDATUM: _____________________________<br />

HERHAAL OPDRAG 1 DEUR GEBRUIK TE MAAK VAN 'N GESKAKELDE LYS<br />

Skryf ’n Java-applet wat ’n onbekende aantal heelgetalle een na die ander in ’n TextField sal<br />

inlees (die gebruiker druk Enter tussen die getalle). Die applet moet deur middel van ’n<br />

Label die gesorteede lys van getalle vertoon. Let op die volgende:<br />

• Gebruik ’n gesorteerde geskakelde lys om die getalle in te stoor. Ontwerp ’n klas<br />

LinkedList wat ‘n gesorteerde geskakelde lys van heelgetalle bestuur. Die klas moet<br />

die volgende bevat:<br />

Ε Datalede vir head en tail die begin en die einde van die lys.<br />

Ε Metodes:<br />

- Purge (maak lys skoon) wat in die constructor geroep word;<br />

- isEmpty wat toets <strong>of</strong> die lys leeg is;<br />

- insertSorted wat ’n getal op die regte plek in die sorteerde geskakelde lys sal<br />

invoeg;<br />

- toString wat ’n string opbou wat uit die lys se elemente bestaan en ’n string<br />

genereer; en<br />

- Toegangsfunksies vir die datalede.<br />

Ε Volg die gebruik van die handboek om van ’n inner-klas vir die elemente gebruik<br />

te maak. Jou elemente moet int wees en nie Object nie.<br />

• Skryf ’n aandrywer Applet as gebruikerskoppelvlak vir die geskakelde lys.<br />

Ε Die drywer mag nie deur die lys soek nie.<br />

Ε Die drywer mag nie die lys element vir element vertoon nie.<br />

Ε Die drywer bevat ‘n object van die LinkedList klas en roep slegs die metodes van<br />

die klas.<br />

39


Appendix 2<br />

ASSIGNMENT 4: SUBMISSION DATE: _________________________<br />

REPEAT ASSIGNMENT 1 BY MAKING USE OF A LINKED LIST<br />

Write a Java applet that will read an unknown number <strong>of</strong> integers one after the other in a<br />

Textfield (The user presses Enter in between the numbers). The applet must display the<br />

sorted list <strong>of</strong> numbers by making use <strong>of</strong> a Label. Note the following:<br />

• Use a sorted linked list to store the numbers in. Design a class LinkedList that<br />

manages a sorted linked list <strong>of</strong> integers. The class must have the following:<br />

• Data members for head and tail, the start and end <strong>of</strong> the list.<br />

• Methods:<br />

- urge (clean the list) that is called in the constructor;<br />

- sEmpty tests if the list is empty;<br />

- nsertSorted will place a number in the correct place in a sorted linked list.<br />

- oString builds up a string consisting list’s elements and generates a string;<br />

- access functions for data members.<br />

• Follow the way in the textbook to make use <strong>of</strong> an inner class for elements. You<br />

elements must be int, not Object.<br />

• Write an actuator/drive Applet as a user interface for the linked list.<br />

The drive may not search through the list.<br />

The drive may not display the list the elements consecutively.<br />

The drive contains an object from the LinkedList class and calls only the methods <strong>of</strong><br />

this class.<br />

39


Bylaag 2 - Klasbesprekings<br />

OPDRAG 5: INGEEDATUM: ____________________________<br />

Hierdie is ‘n generiese opdrag om polymorfisme en oorerwing in Java te toets. Jy moet:<br />

• ’n Interface met die naam Basis skep wat uit vier metodes bestaan, naamlik:<br />

Ε double met01()<br />

Ε double met02()<br />

Ε double met03()<br />

Ε String wie()<br />

• Skep ’n klas met die naam KlasA wat die basis implementeer deur:<br />

Ε Twee double veranderlikes te verklaar (v1 en v2)<br />

Ε met01() hoef slegs v1 terug te stuur en met02() v2<br />

Ε met03() stuur die som van v1 en v2 terug<br />

Ε wie() stuur die string “KlasA” terug<br />

• Skep ’n klas met die naam KlasA1 wat ‘n subklas van KlasA is:<br />

Ε Daar moet nog twee veranderlikes bygevoeg word, naamlik v3,v4<br />

Ε met04() en met05() moet v3 en v4 onderskeidelik terugstuur<br />

Ε wie() stuur die string “KlasA1” terug<br />

Ε met03() stuur die antwoord van die formule v1*v2+v3 terug<br />

• Skep ’n klas met die naam KlasA2 wat ‘n subklas van KlasA is:<br />

Ε Daar moet nog twee veranderlikes bygevoeg word, naamlik v3,v4<br />

Ε met08() en met07() moet v3 en v4 onderskeidelik terugstuur<br />

Ε wie() stuur die string “KlasA2” terug<br />

Ε met03() stuur die antwoord van die formule v1*v2+v4 terug<br />

• Skryf ’n aandrywerprogram wat:<br />

Ε ’n verwysing na basis, naamlik b verklaar<br />

Ε ’n objek van KlasA, naamlik a maak (met waardes: 3,4)<br />

Ε ’n objek van KlasA1, naamlik a1 maak (met waardes: 3,4,2,5)<br />

Ε ’n objek van KlasA2, naamlik a2 maak (met waardes: 2,1,3,2)<br />

40


Appendix 2<br />

ASSIGNMENT 5: SUBMISSION DATE: _________________________<br />

This is a generic assignment to test polymorphism and inheriting in Java. You must:<br />

• Create an Interface with the name Base that consists <strong>of</strong> 4 methods:<br />

double met01()<br />

double met02()<br />

double met03()<br />

String wie()<br />

• Create a class with the name ClassA the implements the base by:<br />

Declaring two double variables (v1 en v2)<br />

met01() need only send v1 back and met02() v2<br />

met03() sends the sum <strong>of</strong> v1 and v2 back<br />

wie() sends the string “ClassA” back<br />

• Create a class with the name ClassA1, a sub-class <strong>of</strong> ClassA:<br />

Two other variables must be added, they are v3, v4<br />

met04() and met05() must respectively send v3 and v4 back<br />

wie() sends the string “ClassA1” back<br />

met03() sends the answer <strong>of</strong> the formula v1*v2 +v3 back<br />

• Create a class with the name ClassA2, a sub-class <strong>of</strong> ClassA:<br />

Two other variables must be added, they are v3, v4<br />

met08() and met07() must respectively send v3 and v4 back<br />

wie() sends the string “ClassA2” back<br />

met03() sends the answer <strong>of</strong> the formula v1*v2+v4 back<br />

• Write a driver program that:<br />

declares a reference to base, namely b<br />

make an object <strong>of</strong> ClassA, namely a (with values 3,4)<br />

make an object <strong>of</strong> ClassA1, namely a1 (with values 3,4,2,5)<br />

make an object <strong>of</strong> ClassA2, namely a2 (with values 2,1,3,2)<br />

40


• Daar moet vir elkeen van die klasse die volgende gedoen word:<br />

Bylaag 2 - Klasbesprekings<br />

Ε Die wie() metode deur static-binding roep en met drawstring vertoon word<br />

Ε Die objek aan b toeken<br />

Ε Roep weer die wie() metode, maar die keer deur die objek b (dynamic binding)<br />

en vertoon die resultaat<br />

Ε Roep die met03() metode ook deur die objek b en vertoon die resultaat.<br />

41


• The following must be done for each <strong>of</strong> the classes:<br />

Call the wie() method through static binding and be displayed with drawstring.<br />

Award the object to b.<br />

Appendix 2<br />

Call the wie() method again, but this time through object b (dynamic binding) and<br />

display the result.<br />

Also call the met03() method through object b and display the result.<br />

41


Bylaag 2 - Klasbesprekings<br />

OPDRAG 6: INGEEDATUM: _____________________________<br />

Hierdie opdrag behels die volgende:<br />

• Oorerwing<br />

• Polimorfisme<br />

• “BorderLayout”<br />

• “Panels”<br />

• “Radio Buttons”<br />

Bestudeer die volgende twee skermuitdrukke:<br />

42


Appendix 2<br />

ASSIGNMENT 6: SUBMISSION DATE: _________________________<br />

This assignment comprises <strong>of</strong> the following:<br />

• Inheriting;<br />

• Polymorphism;<br />

• BorderLayout;<br />

• Panels; and<br />

• Radio Buttons.<br />

Study the following screen prints:<br />

42


Hoe werk die Applet?<br />

• Daar is net twee Buttons op die applet: ’n byvoeg en ’n weglaat Button.<br />

Bylaag 2 - Klasbesprekings<br />

• Die Buttons se teks verander na aanleiding van die keuse van die Radio Buttons.<br />

• Buttons se teks word met setLabel() verander bv addButton.setLabel(“Pop”).<br />

• Wanneer Dequeue <strong>of</strong> Pop gedruk word, verskyn die getal wat uit die lys gehaal word in<br />

die TextBox. Indien die lys leeg is verskyn daar ’n –1.<br />

• Die korrekte lys moet vertoon word na aanleiding van die Radio Button.<br />

• Gebruik BorderLayout vir die Applet-ontwerp.<br />

• Omdat jy meer as een item in die middel wil plaas, moet jy hulle eers op ’n panel sit en<br />

dan die panel in die middel plaas.<br />

• ’n Panel kan sy eie Layout Manager hê. Ek het ‘n (3,1) rooster gebruik.<br />

• Jy moet net drie dinge doen na aanleiding van die Radio Button:<br />

Ε ‘n Indeks veranderlike van die vektor stel;<br />

Ε Die addButton se teks verander;<br />

Ε Die RemoveButton se teks verander.<br />

BELANGRIK - Ons gebruik polimorfisme om die add, remove en die vertoonlys te doen.<br />

• Maak ’n vektor met twee posisies van wysers na die basisklas.<br />

• Stel een van die posisies gelyk aan die een subklas en die ander een gelyk aan die<br />

ander subklas.<br />

• Roep die add-, remove- <strong>of</strong> list-funksie deur die vektor bv lys[index].add()<br />

Ε As jy totaal verward is, kyk na die Shapes-voorbeeld in die notas op bl 393 wat<br />

voor die vakansie uitgedeel is.<br />

KLASSTRUKTUUR<br />

Basisklas – abstrakte klas LinkedList met innerclas Element<br />

Datalede: head, tail en count<br />

Abstrakte metodes: add() en remove()<br />

Metodes: purge(), getCount(), isEmpty(), toString() en dan die standaard Element-klas<br />

Subklas 1: Stack wat van LinkedList oorerf<br />

Datalede: niks ekstra<br />

Metodes: add() en remove() en die submetodes wat hulle gebruik soos prepend()<br />

Kyk in die handboek vir die kode, herskryf extract()<br />

43


How does the Applet work?<br />

• There are only two Buttons on the applet: an add and an omit Button.<br />

Appendix 2<br />

• The text <strong>of</strong> the Buttons changes in accordance with the choice made on the Radio<br />

Buttons.<br />

• The text <strong>of</strong> the Buttons is changed with setLabel(), for example, addButton.setLabel<br />

(“Pop”).<br />

• When Dequeue or Pop is pressed, the number taken from the list is displayed in the<br />

TextBox. If the list is empty, only a 1 will be displayed.<br />

• The correct list must display as a result <strong>of</strong> the Radio Button.<br />

• Use BorderLayout for the design <strong>of</strong> the Applet.<br />

• Because you want to place more than on item in the centre, you first need to place the<br />

items in a panel. After this you can place the panel in the centre.<br />

• A Panel can have its own Layout Manager. I used a (3,1) grid.<br />

• There are three things you must do in connection with the Radio Button:<br />

Set an index variable <strong>of</strong> the vector;<br />

Change the text <strong>of</strong> the addButton;<br />

Change the text <strong>of</strong> the RemoveButton.<br />

IMPORTANT - We use polymorphism to do the add, remove and display list.<br />

• Make a vector with two positions <strong>of</strong> pointers towards the base class.<br />

• Set one <strong>of</strong> the positions equal to the one subclass and other equal to the other<br />

subclass.<br />

• Use the vector to call the add, remove or list functions, for example, lys[index].add()<br />

If you are completely confused, take a look at the Shapes example in the notes on<br />

page 393 that I handed to you before the holiday.<br />

CLASS STRUCTURE<br />

Base class – abstract class LinkedList with innerclass Element<br />

Data members: head, tail and count<br />

Abstract methods: add() en remove()<br />

Methods: purge(), getCount(), isEmpty(), toString() and the standard Element class.<br />

Subclass 1: Stack inheriting from LinkedList<br />

Data members: nothing extra<br />

Methods: add() and remove() and the sub methods they use, such as prepend()<br />

Look in the textbook for the code, rewrite extract()<br />

43


Subklas 2: Queue wat van LinkedList oorerf<br />

Datalede: niks ekstra<br />

Bylaag 2 - Klasbesprekings<br />

Metodes: add() en remove() en die submetodes wat hulle gebruik soos append()<br />

Kyk in die handboek vir die kode, herskryf extract()<br />

• Die add() en remove() metodes moet natuurlik met Integer-parameters werk en jy moet<br />

self uitwerk hoe dit moet wees!<br />

INDIEN JY HIERDIE OPDRAG SELF REGKRY, BEHOORT JY IN DIE<br />

PRAKTIESE EKSAMEN SUKSESVOL TE WEES!!<br />

ONTHOU JY IS VERONDERSTEL OM TE GENIET WAT JY DOEN!<br />

44


Subclass 2: Queue inherited from LinkedList<br />

Data members: nothing extra<br />

Methods: add() and remove() and the sub methods they use such as append()<br />

Look in your textbook for the code and rewrite extract()<br />

Appendix 2<br />

• Obviously the add() and remove() methods must function with Integer parameters and<br />

you must calculate how it must be!<br />

YOU SHOULD BE SUCCESSFUL IN THE EXAMINATION IF YOU ARE ABLE TO<br />

COMPLETE THIS ASSIGNMENT BY YOURSELF.<br />

REMEMBER, YOU ARE SUPPOSED TO ENJOY WHAT YOU ARE DOING!<br />

44


Bylaag 2 - Klasbesprekings<br />

OPDRAG 7: INGEEDATUM: ____________________________<br />

Hierdie program behels slegs klein veranderings aan Opdrag 6:<br />

• Jy moet exception handling doen in plaas daarvan om ’n –1 terug te stuur wanneer die<br />

stapel <strong>of</strong> die tou leeg is.<br />

• Jy moet jou eie exception skep.<br />

• Die removeItem() metode moet die uitsondering throw.<br />

• Die try en catch moet in jou drywerprogram gedoen word.<br />

• Jy moet ’n foutboodskap in die vorm van ’n window op die skerm vertoon.<br />

• Onthou die throws in die funksies se opskrifte.<br />

45


Appendix 2<br />

ASSIGNMENT 7: SUBMISSION DATE: _________________________<br />

This program comprises small changes to Assignment 6.<br />

• You must do exception handling instead <strong>of</strong> sending back a 1 when a stack or queue is<br />

empty.<br />

• You must create your own exception.<br />

• The removeItem() method must throw the exception.<br />

• The try and catch must be done in you drive program.<br />

• You must display an error message in a window on the screen.<br />

• Remember the throws in the headings <strong>of</strong> the functions.<br />

45


BYLAAG 2 – KLASBESPREKINGS<br />

Bylaag 2 - Klasbesprekings<br />

46


APPENDIX 2 – CLASS DISCUSSIONS<br />

Appendix 2<br />

46


KLASBESPREKING 1<br />

Bylaag 2 - Klasbesprekings<br />

Ontwikkel ’n klas en toepassing om studente se punte te hanteer. Jou program moet uit<br />

twee lêers bestaan:<br />

1. ’n Volledige klas vir studente met:<br />

• Datalede (attributes) vir naam, punt1, punt2 en gemiddeld.<br />

• Daar moet twee “constructors” wees. Een moet waardes van die gebruiker aan die<br />

datalede toeken. Die ander “constructor” ontvang geen parameters nie en roep die<br />

eerste “constructor” met nul datavelde.<br />

• Die “constructor” moet die stelfunksies gebruik om die waardes van die datalede te<br />

inisieer.<br />

• Daar moet toegangsfunksies (methods) vir elke datalid wees.<br />

• Die stelfunksies vir die punte moet die punte toets om seker te maak dat dit tussen<br />

0 en 100 is (validate).<br />

• Daar moet ’n funksie wees om die gemiddeld te bereken.<br />

• Compile die klas met javac, maar aangesien dit nie ’n program <strong>of</strong> applet is nie, kan<br />

jy dit nie uitvoer nie.<br />

2. ’n Applet wat:<br />

• Die gebruikerskoppelvlak van die studenteklas is om die datalede van die klas te<br />

stel.<br />

• Jy moet ’n vektor van 5 studente-objekte skep. Dit is baie belangrik om die objekte<br />

een vir een in ’n for-lus te skep, sodoende word daar geheue vir elkeen toegewys.<br />

• Gebruik drie Buttons om onderskeidelik die datalede te stel, die volgende vektorposisie<br />

te vertoon en die vorige vektorposisie te vertoon.<br />

• Die posisie in vektor moet ook op die skerm vertoon word.<br />

• Dit is baie belangrik om seker te maak dat die Buttons nie toegang buite die grense<br />

van die vektor veroorsaak nie.<br />

47


CLASS DISCUSSION 1<br />

Appendix 2<br />

Develop a class and application to handle student marks. Your program must consist <strong>of</strong> two<br />

files:<br />

1. A complete class for students with:<br />

• Data members (attributes) for name, mark1, mark2 and average.<br />

• There must be two constructors. One must allocate values <strong>of</strong> the user to the data<br />

members. The other constructor receives no parameters and calls the first constructor<br />

with zero data fields.<br />

• The constructor must use the set functions to initiate the values <strong>of</strong> the data members.<br />

• There must be access functions (methods) for each data member.<br />

• The set functions for the marks must test them to ensure that they are between 0 and<br />

100 (validate).<br />

• There must be a function that calculates the average.<br />

• Compile the class with java, you cannot carry this out though, because it is neither a<br />

program nor an applet.<br />

2. An Applet that:<br />

• Is the user interface <strong>of</strong> the student class to set the data members <strong>of</strong> the class.<br />

• You must create a vector <strong>of</strong> five student objects. It is very important to create the<br />

objects one by one in a for loop. By doing this, memory is allocated to each.<br />

• Use three Buttons to set the data members severally, display the next vector position<br />

and display the previous vector position.<br />

• The position <strong>of</strong> the vector must also be displayed on the screen.<br />

• It is very important to ensure that the Buttons do not create access outside the borders<br />

<strong>of</strong> the vector.<br />

47


public class Student<br />

{<br />

private String name;<br />

private double mark1, mark2, average;<br />

Student(String n, double m1, double m2)<br />

{<br />

}<br />

setName(n);<br />

setMark1(m1);<br />

setMark2(m2);<br />

computeAverage();<br />

Student()<br />

{<br />

}<br />

this(" ",0,0);<br />

public void setName(String studentName)<br />

{<br />

}<br />

name = studentName;<br />

public void setMark1(double studentMark1)<br />

{<br />

}<br />

if (studentMark1>=0 && studentMark1 =0 && studentMark2


public class Student<br />

{<br />

private String name;<br />

private double mark1, mark2, average;<br />

Student(String n, double m1, double m2)<br />

{<br />

}<br />

setName(n);<br />

setMark1(m1);<br />

setMark2(m2);<br />

computeAverage();<br />

Student()<br />

{<br />

}<br />

this(" ",0,0);<br />

public void setName(String studentName)<br />

{<br />

}<br />

name = studentName;<br />

public void setMark1(double studentMark1)<br />

{<br />

}<br />

if (studentMark1>=0 && studentMark1 =0 && studentMark2


}<br />

public double computeAverage()<br />

{<br />

}<br />

average = (mark1+mark2)/ (double) 2;<br />

return average;<br />

public String getName()<br />

{<br />

}<br />

return name;<br />

public double getMark1()<br />

{<br />

}<br />

return mark1;<br />

public double getMark2()<br />

{<br />

}<br />

return mark2;<br />

public double getAvg()<br />

{<br />

}<br />

return average;<br />

Bylaag 2 - Klasbesprekings<br />

49


}<br />

public double computeAverage()<br />

{<br />

}<br />

average = (mark1+mark2)/ (double) 2;<br />

return average;<br />

public String getName()<br />

{<br />

}<br />

return name;<br />

public double getMark1()<br />

{<br />

}<br />

return mark1;<br />

public double getMark2()<br />

{<br />

}<br />

return mark2;<br />

public double getAvg()<br />

{<br />

}<br />

return average;<br />

Appendix 2<br />

49


import java.applet.Applet;<br />

import java.awt.*;<br />

import java.awt.event.*;<br />

//NB Import Class Definition and implementation <strong>of</strong> class Student<br />

import Student;<br />

Bylaag 2 - Klasbesprekings<br />

// This program keep track <strong>of</strong> count students. count Empty positions are created<br />

// and can be filled by entering data in the TextFields and pressing the<br />

// the Save Student button.<br />

public class StudentsDriver extends Applet<br />

{<br />

Label promptName, promptMark1, promptMark2, promptAvg, labelAvg;<br />

Label showAvg, counter, promptCounter, blank;<br />

TextField inputName,inputMark1,inputMark2;<br />

Button nextStudent,previousStudent,saveStudent;<br />

int position = 0;<br />

double stuAvg;<br />

Student stuArr[];<br />

int count = 5;<br />

public void init()<br />

{<br />

stuArr = new Student[count]; //Constructor Not called<br />

//The elements in this array are reference types, that is, each element contains a<br />

//reference to a Student object. At this point, enough memory has been allocated to<br />

//contain the Student references, but no memory has been allocated for the Students<br />

//themselves. If you attempted to access one <strong>of</strong> stuArrs elements at this point,<br />

//you would get a NullPointerException because the array is empty and contains no<br />

//Students and no Student objects. This is <strong>of</strong>ten a source <strong>of</strong> some confusion for<br />

50


import java.applet.Applet;<br />

import java.awt.*;<br />

import java.awt.event.*;<br />

//NB Import Class Definition and implementation <strong>of</strong> class Student<br />

import Student;<br />

// This program keep track <strong>of</strong> count students. count Empty positions are created<br />

// and can be filled by entering data in the TextFields and pressing the<br />

// the Save Student button.<br />

public class StudentsDriver extends Applet<br />

{<br />

Label promptName, promptMark1, promptMark2, promptAvg, labelAvg;<br />

Label showAvg, counter, promptCounter, blank;<br />

TextField inputName,inputMark1,inputMark2;<br />

Button nextStudent,previousStudent,saveStudent;<br />

int position = 0;<br />

double stuAvg;<br />

Student stuArr[];<br />

int count = 5;<br />

public void init()<br />

{<br />

stuArr = new Student[count]; //Constructor Not called<br />

//The elements in this array are reference types, that is, each element contains a<br />

//reference to a Student object. At this point, enough memory has been allocated to<br />

//contain the Student references, but no memory has been allocated for the Students<br />

//themselves. If you attempted to access one <strong>of</strong> stuArrs elements at this point,<br />

//you would get a NullPointerException because the array is empty and contains no<br />

//Students and no Student objects. This is <strong>of</strong>ten a source <strong>of</strong> some confusion for<br />

Appendix 2<br />

50


programmers new to the Java lang<br />

for (int i = 0; i


programmers new to the Java lang<br />

for (int i = 0; i


}<br />

add(showAvg); //Not a TextField, computed field<br />

add(saveStudent);<br />

add (blank);<br />

add(nextStudent);<br />

add(previousStudent);<br />

add(promptCounter);<br />

add(counter);<br />

counter.setText(Integer.toString(position+1));<br />

public boolean action(Event e, Object arg)<br />

{<br />

Button pressed;<br />

double m1,m2; //temp variables to compute avg<br />

if (e.target instance<strong>of</strong> TextField)<br />

{<br />

}<br />

m1 = Double.parseDouble(inputMark1.getText());<br />

m2 = Double.parseDouble(inputMark2.getText());<br />

stuAvg = ((m1+m2)/2 = 0) ? (m1+m2)/2 : 0;<br />

showAvg.setText(Double.toString(stuAvg));<br />

if (e.target instance<strong>of</strong> Button)<br />

{<br />

pressed = (Button)e.target;<br />

if (pressed == saveStudent)<br />

{<br />

}<br />

stuArr[position].setName(inputName.getText());<br />

stuArr[position].setMark1(Double.parseDouble(inputMark1.getText()));<br />

stuArr[position].setMark2(Double.parseDouble(inputMark2.getText()));<br />

stuAvg = stuArr[position].computeAverage();<br />

showAvg.setText(Double.toString(stuAvg));<br />

pressed = nextStudent;<br />

Bylaag 2 - Klasbesprekings<br />

52


}<br />

add(showAvg); //Not a TextField, computed field<br />

add(saveStudent);<br />

add (blank);<br />

add(nextStudent);<br />

add(previousStudent);<br />

add(promptCounter);<br />

add(counter);<br />

counter.setText(Integer.toString(position+1));<br />

public boolean action(Event e, Object arg)<br />

{<br />

Button pressed;<br />

double m1,m2; //temp variables to compute avg<br />

if (e.target instance<strong>of</strong> TextField)<br />

{<br />

}<br />

m1 = Double.parseDouble(inputMark1.getText());<br />

m2 = Double.parseDouble(inputMark2.getText());<br />

stuAvg = ((m1+m2)/2 = 0) ? (m1+m2)/2 : 0;<br />

showAvg.setText(Double.toString(stuAvg));<br />

if (e.target instance<strong>of</strong> Button)<br />

{<br />

pressed = (Button)e.target;<br />

if (pressed == saveStudent)<br />

{<br />

}<br />

stuArr[position].setName(inputName.getText());<br />

stuArr[position].setMark1(Double.parseDouble(inputMark1.getText()));<br />

stuArr[position].setMark2(Double.parseDouble(inputMark2.getText()));<br />

stuAvg = stuArr[position].computeAverage();<br />

showAvg.setText(Double.toString(stuAvg));<br />

pressed = nextStudent;<br />

Appendix 2<br />

52


}<br />

}<br />

}<br />

if (pressed ==previousStudent)<br />

{<br />

}<br />

if (position > 0)<br />

{<br />

}<br />

position--;<br />

else<br />

position = count-1;<br />

counter.setText(Integer.toString(position+1));<br />

inputName.setText(stuArr[position].getName());<br />

inputMark1.setText(Double.toString(stuArr[position].getMark1()));<br />

inputMark2.setText(Double.toString(stuArr[position].getMark2()));<br />

showAvg.setText(Double.toString(stuArr[position].getAvg()));<br />

if (pressed == nextStudent)<br />

{<br />

}<br />

if (position < count-1 )<br />

{<br />

}<br />

position++;<br />

else<br />

position = 0;<br />

counter.setText(Integer.toString(position+1));<br />

inputName.setText(stuArr[position].getName());<br />

inputMark1.setText(Double.toString(stuArr[position].getMark1()));<br />

inputMark2.setText(Double.toString(stuArr[position].getMark2()));<br />

showAvg.setText(Double.toString(stuArr[position].getAvg()));<br />

return true;<br />

Bylaag 2 - Klasbesprekings<br />

53


}<br />

}<br />

}<br />

if (pressed ==previousStudent)<br />

{<br />

}<br />

if (position > 0)<br />

{<br />

}<br />

position--;<br />

else<br />

position = count-1;<br />

counter.setText(Integer.toString(position+1));<br />

inputName.setText(stuArr[position].getName());<br />

inputMark1.setText(Double.toString(stuArr[position].getMark1()));<br />

inputMark2.setText(Double.toString(stuArr[position].getMark2()));<br />

showAvg.setText(Double.toString(stuArr[position].getAvg()));<br />

if (pressed == nextStudent)<br />

{<br />

}<br />

if (position < count-1 )<br />

{<br />

}<br />

position++;<br />

else<br />

position = 0;<br />

counter.setText(Integer.toString(position+1));<br />

inputName.setText(stuArr[position].getName());<br />

inputMark1.setText(Double.toString(stuArr[position].getMark1()));<br />

inputMark2.setText(Double.toString(stuArr[position].getMark2()));<br />

showAvg.setText(Double.toString(stuArr[position].getAvg()));<br />

return true;<br />

Appendix 2<br />

53


Bylaag 2 - Klasbesprekings<br />

KLASBESPREKING 2: HOE OM HOOFSTUK 5 AAN TE PAK<br />

DIE SKRYF VAN ’N KLAS: ARRAY WAT ’N SKIKKING VAN ENIGE DATATIPE OF OBJEK<br />

VAN ENIGE KLAS KAN BEVAT EN WAAR DIE SKIKKING IN DIE KLAS: ARRAY<br />

GESORTEER KAN WORD.<br />

• Hierdie klasbespreking volg op Opdrag 3: die Array-klas met Object-datatipe. Maak<br />

seker dat jy dit verstaan voordat jy dit aanpak.<br />

• Hierdie werk is moeilik; moenie verwag om alles dadelik te verstaan nie.<br />

• Verstaan eers die oorho<strong>of</strong>se doel:<br />

Ε Om ’n klas Array te maak sodat daar ’n ingeboude datatipe Array is wat ’n<br />

skikking van enige data bevat. Wanneer mens die skikking wil gebruik, dui mens<br />

net die grootte aan en as jy wil, die basis-indeksposisie.<br />

Ε KYK NA DIE AANDRYWERPROGRAM – Lyn 159 – 214<br />

Ε Lyn 175 – maak ‘n objek van die klas Array.<br />

Ε Lyn 199 – wanneer elemente in die skikking geplaas word, moet die datatipe<br />

aangedui word – ons het in Opdrag 3 die Integer-klas gebruik, nou gebruik ons<br />

die Int (ons eie) klas. Waarom? (Lees eers verder, jy sal later verstaan)<br />

Ε Lyn 205 – Hierdie nuwe datatipe wat skikkings stoor het ’n ingeboude sorteerfunksie<br />

– oulik nê, kom ons gebruik dit!<br />

Ε Lyn 206 – Soos elke goeie klas in Java, het die Array-klas ook ’n toString() om<br />

die inhoud van die skikking in ‘n string te plaas, sodat dit maklik is om dit te<br />

vertoon.<br />

• Die vrae wat jy behoort te vra indien iemand jou net die aandrywer wys is:<br />

Ε Hoe kry mens dit reg om enige datatipe in ’n skikking te stoor?<br />

- Soos jy nou al moet verstaan is die antwoord die “Object”-datatipe.<br />

Ε Soos ek tot nou toe geleer het, kan ek nie veranderlikes van die Object- datatipe<br />

met mekaar vergelyk nie. Hoe kry mens dit dan reg om die skikking vol Objectveranderlikes<br />

te sorteer?<br />

- Indien jy ook by hierdie vraag uitkom, verstaan jy nou al baie!<br />

- Die antwoord is om van die Comparable() interface (koppelvlak) gebruik te<br />

maak.<br />

• Hoe gebruik ons die Comparable interface om Object-veranderlikes met mekaar te<br />

vergelyk? Die antwoord in een woord is polimorfisme, maar hoe werk dit?<br />

Ε Kyk na die Comparable interface – Lyne 1 tot 10.<br />

Ε Daar is geen implementering van die funksies nie, want dit is net ’n interface – al<br />

die funksies is ABSTRACT.<br />

Ε Kan ek ’n objek van ’n interface maak? NEE.<br />

Ε Kan ek ’n wyser na ’n interface maak? JA – hoekom? Jy sal later verstaan.<br />

Ε Kom ons kyk na ’n klas wat hierde interface implementeer: AbstractObject.<br />

54


Appendix 2<br />

CLASS DISCUSSION 2: HOW TO GET TO GRIPS WITH CHAPTER 5<br />

WRITING A CLASS: AN ARRAY THAT CAN CONTAIN AN ARRAY OF ANY DATA TYPE<br />

OR OBJECT OF ANY CLASS AND WHERE THE ARRAY IN THE CLASS: ARRAY CAN<br />

BE SORTED.<br />

• This class discussion follows on Assignment 3 – the Array class with Object data type.<br />

Make sure that you understand it before starting with it.<br />

• This is difficult work; do not expect to understand everything immediately.<br />

Ε First understand the general purpose:<br />

Ε To make a class Array in such a way that there is a built-in data type Array that<br />

can contain an array with any data. When you want to use the array, you indicate<br />

the size and if you like, the base index position.<br />

Ε LOOK AT THE DRIVE PROGRAM – Line 159 – 214<br />

Ε Line 175 – make an object <strong>of</strong> the class Array.<br />

Ε Line 199 – when elements are placed in the array, the data type must be<br />

indicated – in Assignment 3 we used the Integer class, now we use the Int (our<br />

own) class. Do you know why? (Keep reading, it will become clear to you later<br />

on.)<br />

Ε Line 205 – The new data type storing the arrays has a built-in sorting function – is<br />

that not that smart? Let us use it!<br />

Ε Line 206 – As with every good class in Java, the Array class also has a toString()<br />

that allows the contents <strong>of</strong> the array to be placed in a string. This makes it easier<br />

to display.<br />

• The questions you should be asking if someone only shows you the drive:<br />

Ε How do you go about storing any data type in an array?<br />

- by now you should understand the answer is the Object data type.<br />

Ε Like I told you in class, the variables <strong>of</strong> the Object data type cannot be compared<br />

with one another. How do you go about sorting and array <strong>of</strong> Object variables?<br />

- if you asked yourself this question, you already understand a lot!<br />

- the answer is to use a Comparable() interface.<br />

• How do we use the Comparable interface to compare Object variables with one<br />

another? The answer is polymorphism. But how does this work?<br />

Ε Take a look at the Comparable interface. Lines 1 to 10.<br />

Ε There is no implementation <strong>of</strong> the functions because it is only an interface – all<br />

the functions are ABSTRACT.<br />

Ε Can I make an object from an interface? NO.<br />

Ε Can I make a pointer from an interface? YES – why? You will understand this<br />

later.<br />

Ε Let us take a look at the class that will implement this interface: AbstractObject.<br />

54


• Kyk na die klas AbstractObject lyne 11-51.<br />

Ε Verstaan lyn 12<br />

Ε Lyn 14 dui die ABSTRAKTE funksie ComparTo() aan<br />

- Hierdie klas is dus abstrak.<br />

- Kan ek ’n objek van hom maak? NEE.<br />

Bylaag 2 - Klasbesprekings<br />

- Alle klasse wat van hom erf (inherit) sal ook abstrak wees TENSY HULLE DIE<br />

compareTo() metode implementeer (kode verskaf).<br />

Ε Meeste van die funksies van die klas gebruik die compare()-metode.<br />

Ε Die compare()-metode kontroleer <strong>of</strong> die objekte wat sorteer moet word van<br />

dieselfde datatipe is, indien wel, roep hy die abstrakte funksie CompareTo()<br />

(sien lyn 46).<br />

Ε Om te verstaan hoedat twee getalle met mekaar vergelyk word in hierdie<br />

hiërargie, kyk gou eers na die compareTo() funksie van die Int klas lyn 68.<br />

- Lyn 68 is die parameter ’n Comparable – hoekom nie ’n Int nie? Die funksie<br />

moet dieselfde opskrif hê as in die ouerklas (parent) waar dit gedefinieer word<br />

- sien lyn 14. Jy kan ook daar sien dat dit ’n gewone primitiewe Int terugstuur.<br />

- Lyn 70 verander die Comparable parameter ook na ’n Int.<br />

- Kyk na die Int-klas – dit het value-veranderlike wat ’n primitiewe Int is – lyn 55.<br />

- Onthou die CompareTo()-metode sou in die algemeen so in ‘n program<br />

gebruik word:<br />

• Int a = new Int(5);<br />

• Int b = new Int(4);<br />

• int c = a.compareTo(b);<br />

- b is dan die argument.<br />

- In lyn 72 word b se value van a s’n afgetrek. Onthou a is die veranderlike wat<br />

die funksie roep (die this-veranderlike).<br />

- Afhangende van die verskil tussen die twee getalle, word daar nou in lyne 72-<br />

77 ’n Int teruggestuur.<br />

- Kom ons kyk terug deur die hiërargie vir die geval wat ons hierbo het, naamlik<br />

5 en 4. Lyn 75 sal ’n 1 terugstuur. Waarheen? Watter metode roep<br />

compareTo()? Dis natuurlik compare() lyn 46.<br />

- compare() stuur nou ’n 1 terug vir wie?<br />

- Dit hang af watter van die funksies van die klas dit geroep het. Kyk nou na lyn<br />

149 (dis ’n sorteerfunksie – moenie nou oor die res van die kode bekommer<br />

nie). Ons gebruik die isLT() funksie uit die AbstractObject-klas. Kyk daarna in<br />

lyn 17. Dit return ’n Boolean (True <strong>of</strong> False). In hierdie geval false want<br />

compare het ’n 1 teruggestuur. Dit is heeltemal reg dat ’n is “less than”funksie<br />

false is as ek 5 met 4 vergelyk.<br />

- Kom ons kyk hoekom ons die isLT() geroep het.<br />

55


• Look at the class AbstractObject lines 11-51.<br />

Ε Understand line 12.<br />

Ε Line 14 indicates the ABSTRACT function ComparTo().<br />

- this class is abstract.<br />

- can I make an object from it? NO.<br />

Appendix 2<br />

- all classes inheriting from it will also be abstract, UNLESS they implement<br />

the compareTo() method (code given).<br />

• Most <strong>of</strong> the functions in this class use the compare() method.<br />

• The compare() method checks if the objects that must be sorted are the same. If<br />

they are, it calls the abstract function CompareTo() (see line 46).<br />

• In order to understand how two numbers can be compared in this hierarchy, you must<br />

first take a look at the compareTo() function <strong>of</strong> the Int class in line 68.<br />

- In line 68 is the parameter a Comparable – why not an Int? The function<br />

must have the same heading as the parent class where it is defined - see<br />

line 14. Take note that it sends back a simple, primitive Int.<br />

- in line 70 the Comparable parameter changes to an Int.<br />

- look at the Int class – it has a value variable that is a primitive Int – line 55.<br />

- remember the CompareTo() method will in general be used like this in a<br />

program:<br />

Ε Int a = new Int(5);<br />

Ε Int b = new Int(4);<br />

Ε int c = a.compareTo(b);<br />

- b is the argument.<br />

- in line 72, b’s value is subtracted from the value <strong>of</strong> a. Remember a is the<br />

variable calling the function (the this variable)<br />

- depending on the difference between the two numbers, an Int is now sent<br />

back in lines 72-77.<br />

- let us have a look at the hierarchy for the situation we have above, namely<br />

5 and 4. Line 75 will send back a 1. Where to will it be sent? What<br />

method calls compareTo()? It is compare() in line 46.<br />

- compare() sends a 1 back - to whom?<br />

- it depends on which functions <strong>of</strong> class it called. Look at line 149 (it is a<br />

sorting function – do not worry about the rest <strong>of</strong> the code right now). We<br />

use the isLT() function <strong>of</strong> the AbstractObject class. Then look at line 17. It<br />

returns a Boolean (True or False). In this case false because compare sent<br />

back a 1. It is correct that a less than function is false when you compare 5<br />

with 4.<br />

- let us look at why we called the isLT().<br />

55


Bylaag 2 - Klasbesprekings<br />

Ε Wat jy nou moet verstaan is: Om twee Object-verandelikes met mekaar te vergelyk<br />

moet daar iewers in die heel onderste klas in die hiërargie ’n implementering<br />

van die funksie compareTo() wees. Dit beteken die volgende vir ons aanvanklike<br />

probleem:<br />

- Wat is ons probleem? Om ’n skikking van Object-veranderlikes te sorteer.<br />

- Ons het reeds in Opdrag 3 en lyn 199 gesien dat wanneer ons iets in die<br />

skikking sit (met put()), ons die datatipe moet aandui. Nou voeg ons nóg ’n<br />

vereiste by.<br />

- Om die sort()-funksie van die skikking te mag gebruik moet die datatipe wat<br />

ons in die skikking sit, ’n implementering van die compareTo() abstrakte<br />

funksie bevat. Hoekom? Sodat die sort()-funksie weet hoe om objekte in die<br />

skikking met mekaar te vergelyk.<br />

- Het die primitiewe Int <strong>of</strong> die ingeboude Java Integer-klasse ’n implementering<br />

van die compareTo()-funksie? NEE. Kan ons objekte van hierdie klasse in die<br />

skikking insit? NEE. Wat moet ons dan doen?<br />

- Ons moet ons eie Integer-klas maak. Kom ons noem hom Int wat slegs<br />

bestaan uit ’n int veranderlike en ’n implementering van die compareTo()funksie.<br />

(Natuurlik sit ons altyd ‘n toString() in). Kan ons dan objekte van<br />

hierdie klas in die skikking sorteer? JA!<br />

- So ’n klas word ’n wrapper-klas genoem. Dit is ’n klas wat ‘n primitiewe dataelement<br />

bevat en enkele funksies byvoeg om in polimorfisme te gebruik.<br />

• Hoekom sê ons hierdie klas gebruik polimorfisme?<br />

• Kyk nou na die Array-klaslyn 80:<br />

Ε Ek neem aan julle verstaan alles behalwe die sorteer()-funksie.<br />

Ε Kyk na lyn 139 – ek kan nie objekte van ’n abstrakte klas maak nie, maar wel<br />

verwysings (references <strong>of</strong> addresses) daarna.<br />

Ε My skikking is vol Objects - nou verander ek spesifieke elemente na<br />

Comparables lyne 147 en 148. Hoekom? Ek wil hulle met mekaar vergelyk.<br />

Ε Nou kan ek die isLT()-metode uitvoer?<br />

Ε Hoe weet die Java watter funksies om te roep?<br />

Ε In die aandrywer in lyn 199 het ek gewys dat dit Int.-objekte is wat ek in die Array<br />

sit. Put-lyn 108 het daardie Int na ’n Object verander (deur die parameter se tipe),<br />

maar Java onthou nog dat dit eintlik ’n Int was. Nou wanneer ek die Object (wat<br />

‘n Int was) na ’n Comparable verander in lyn 147, weet Java dat hierdie<br />

Comparable eintlik ’n Int is.<br />

Ε Die funksie wat in lyn 149 geroep word is die funksie van lyn 3. Daar is nie ’n<br />

implementering nie, daarom soek Java een en kry een in lyn 17. Dan word die<br />

funksie Compare() van lyn 43 geroep. In lyn 46 word CompareTo() geroep. Nou<br />

is dit ’n dinamiese binding, want dit is ’n verwysing van die basisklas<br />

(Comparable) wat ’n abstrakte funksie van die subklas Int roep. Java weet dat<br />

die Comparable wat die funksie roep, eintlik ’n Int is en voer Int se compareTo()<br />

uit!!<br />

Ε As dit nie vir jou “cool” is nie, swot jy dalk die verkeerde rigting!<br />

56


Appendix 2<br />

Ε What you must understand at this point: In order to compare two Object variables<br />

with one another, somewhere in the bottom class <strong>of</strong> the hierarchy the<br />

compareTo() function must be implemented. This implies the following for our<br />

initial problem:<br />

- what is our problem? To sort an array <strong>of</strong> Object variables.<br />

- during Assignment 3 and line 199 it became clear that when we put<br />

something in the array (with put() ) we must indicate the data type. Now we<br />

add another requirement.<br />

- in order to use the sort() function <strong>of</strong> the array, the data type we put in the<br />

array must contain an implementation <strong>of</strong> the compareTo() abstract function.<br />

Why? It lets the sort() function know how to compare the objects in the<br />

array with one another.<br />

- does the primitive Int or built-in Java Integer classes have an<br />

implementation <strong>of</strong> the compareTo() function? NO. Can we place objects <strong>of</strong><br />

these classes in the array? NO. What must we do?<br />

- we must make our own Integer class. Let us call it Int and it consists only <strong>of</strong><br />

the int variable and the implementation <strong>of</strong> the compareTo() function.<br />

(Obviously we add a toString()). Can we now sort objects <strong>of</strong> this class in<br />

the array? YES!<br />

- this kind <strong>of</strong> class is called a wrapper class. It is a class containing a<br />

primitive data element and adds several functions to be used in<br />

polymorphism.<br />

• Why does this class use polymorphism?<br />

• Take a look at Array class in line 80:<br />

Ε I assume you understand everything except the sort() function.<br />

Ε Look at line 139 – I cannot make objects from an abstract class, but I can make<br />

references or addresses.<br />

Ε My array filled with Objects – now I change specific elements to Comparables<br />

(lines 147 and 148). Why? I want to compare them with one another.<br />

Ε Am I now able to perform the isLT() method?<br />

Ε How does Java know which functions to call?<br />

Ε In the drive in line 199 I showed that I put Int objects in the Array. Put line 108<br />

changed that Int to an Object (through the type <strong>of</strong> the parameter), but Java still<br />

remembers that it is actually an Int. When at this point I change the Object<br />

(which was an Int) into a Comparable in line 147, Java knows that the<br />

Comparable is in fact an Int.<br />

Ε The function called in line 149 is the function in line 3. There is no<br />

implementation and Java seeks one and finds one in line 17. Then the<br />

Compare() function <strong>of</strong> line 43 is called. In line 46 CompareTo() is called. Now it<br />

is a dynamic link, because it is a reference <strong>of</strong> the base class (Comparable) calling<br />

an abstract function <strong>of</strong> the subclass Int. Java knows that the Comparable calling<br />

the function is in fact an Int and performs Int’s compareTo()!<br />

Ε If you do not think this is cool, you may be studying the wrong course!<br />

56


Bylaag 2 - Klasbesprekings<br />

• Daar is egter drie ander dinge van die Array-klas wat anders is as in die handboek.<br />

Mens kom dit op die harde manier (meer as 10 uur se gesukkel) agter:<br />

Ε Die Array-klas extend ook van AbstractObject, so om ’n konkrete klas te wees<br />

moet dit ’n implementering van compareTo() bevat. Logies sal hierdie funksie<br />

verduidelik hoe ’n mens een objek van die Array-klas (’n hele skikking) met ‘n<br />

ander een vergelyk. Dit is nie eintlik ’n logiese ding om te doen nie, daarom word<br />

net ’n o teruggestuur. Kyk lyne 115 –117.<br />

Ε Ek het vir die Array-klas ’n cont bygesit wat die aantal vol posisies in die skikking<br />

aandui, sodat ek nie nulposisies sorteer nie. Hoekom nie? In lyn 149 sou ’n<br />

mens dan die funksie vanaf ‘n nul-veranderlike roep en dan kry jy ’n Nul –pointer<br />

exception.<br />

Ε Ek het natuurlik ook ’n toString() bygesit.<br />

EK HOOP WERKLIK HIERDIE VERDUIDELIKING HELP JULLE OM HOOFSTUK 5<br />

TE VERSTAAN.<br />

57


Appendix 2<br />

• There are three things that are different to the Array class than in the textbook. You<br />

learn this the hard way – after trying for more than 10 hours!<br />

Ε The Array class also extends from AbstractObject, this means that for it to be a<br />

concrete class, it must contain the implementation <strong>of</strong> compareTo(). Logically it<br />

follows that this function explains how one object <strong>of</strong> the Array class (a complete<br />

array) is compared with another. Actually it is not a logical thing to do and<br />

therefore only a 0 is sent back. Look at lines 115 - 117.<br />

Ε I added to the Array class a cont to indicate the number <strong>of</strong> full positions in the<br />

array and prevent me from sorting zero positions. Why not? In line 149 you<br />

would call the function from a zero variable and get a Null pointer exception.<br />

Ε I naturally also added a toString().<br />

I HOPE THIS EXPLANATION HELPS YOU TO UNDERSTAND CHAPTER 5.<br />

57


Programkode<br />

//pr 5.1<br />

1 Public interface Comparable<br />

2 {<br />

3 Boolean isLT (Comparable object);<br />

4 Boolean isLE (Comparable object);<br />

5 Boolean isGT (Comparable object);<br />

6 Boolean isGE (Comparable object);<br />

7 Boolean isEQ (Comparable object);<br />

8 Boolean isNE (Comparable object);<br />

9 Int compare (Comparable object);<br />

10 }<br />

//Pr5.2+pr5.3<br />

11 Public abstract class AbstractObject<br />

12 Implements Comparable<br />

13 {<br />

14 Protected abstract int compareTo (Comparable arg);<br />

15<br />

16<br />

17 public final boolean isLT (Comparable object)<br />

18 { return compare (object) < 0; }<br />

19<br />

20 public final boolean isLE (Comparable object)<br />

21 { return compare (object) 0; }<br />

25<br />

26 public final boolean isGE (Comparable object)<br />

27 { return compare (object) >= 0; }<br />

28<br />

29 public final boolean isEQ (Comparable object)<br />

30 { return compare (object) == 0; }<br />

Bylaag 2 - Klasbesprekings<br />

58


Program code<br />

//pr 5.1<br />

1 Public interface Comparable<br />

2 {<br />

3 Boolean isLT (Comparable object);<br />

4 Boolean isLE (Comparable object);<br />

5 Boolean isGT (Comparable object);<br />

6 Boolean isGE (Comparable object);<br />

7 Boolean isEQ (Comparable object);<br />

8 Boolean isNE (Comparable object);<br />

9 Int compare (Comparable object);<br />

10 }<br />

//Pr5.2+pr5.3<br />

11 Public abstract class AbstractObject<br />

12 Implements Comparable<br />

13 {<br />

14 Protected abstract int compareTo (Comparable arg);<br />

15<br />

16<br />

17 public final boolean isLT (Comparable object)<br />

18 { return compare (object) < 0; }<br />

19<br />

20 public final boolean isLE (Comparable object)<br />

21 { return compare (object) 0; }<br />

25<br />

26 public final boolean isGE (Comparable object)<br />

27 { return compare (object) >= 0; }<br />

28<br />

29 public final boolean isEQ (Comparable object)<br />

30 { return compare (object) == 0; }<br />

Appendix 2<br />

58


31<br />

32 public final boolean isNE (Comparable object)<br />

33 { return compare (object) != 0; }<br />

34<br />

35 public final boolean equals (Object object)<br />

36 {<br />

37 if (object instance<strong>of</strong> Comparable)<br />

38 return isEQ ((Comparable) object);<br />

39 Else<br />

40 return false;<br />

41 }<br />

42<br />

43 public final int compare (Comparable arg)<br />

44 {<br />

45 if (getClass () == arg.getClass ())<br />

46 return compareTo (arg);<br />

47 Else<br />

48 return getClass ().getName ().compareTo (<br />

49 arg.getClass ().getName ());<br />

50 }<br />

51 }<br />

//pr 5.5<br />

52 public class Int<br />

53 extends AbstractObject<br />

54 {<br />

55 Protected int value;<br />

56<br />

57 public Int (int value)<br />

58 { this.value = value; }<br />

59<br />

60 public int intValue ()<br />

61 { return value; }<br />

62<br />

Bylaag 2 - Klasbesprekings<br />

59


31<br />

32 public final boolean isNE (Comparable object)<br />

33 { return compare (object) != 0; }<br />

34<br />

35 public final boolean equals (Object object)<br />

36 {<br />

37 if (object instance<strong>of</strong> Comparable)<br />

38 return isEQ ((Comparable) object);<br />

39 Else<br />

40 return false;<br />

41 }<br />

42<br />

43 public final int compare (Comparable arg)<br />

44 {<br />

45 if (getClass () == arg.getClass ())<br />

46 return compareTo (arg);<br />

47 Else<br />

48 return getClass ().getName ().compareTo (<br />

49 arg.getClass ().getName ());<br />

50 }<br />

51 }<br />

//pr 5.5<br />

52 public class Int<br />

53 extends AbstractObject<br />

54 {<br />

55 Protected int value;<br />

56<br />

57 public Int (int value)<br />

58 { this.value = value; }<br />

59<br />

60 public int intValue ()<br />

61 { return value; }<br />

62<br />

Appendix 2<br />

59


63 public String toString()<br />

64 {<br />

65 Return Integer.toString(value);<br />

66 }<br />

67<br />

68 Protected int compareTo (Comparable object)<br />

69 {<br />

70 Int arg = (Int) object;<br />

71 Long diff = (long) value - (long) arg.value;<br />

72 if (diff < 0)<br />

73 return -1;<br />

74 Else if (diff > 0)<br />

75 return +1;<br />

76 Else<br />

77 return 0;<br />

78 }<br />

79 }<br />

80 public class Array extends AbstractObject<br />

81 {<br />

82 protected Object[] data;<br />

83 protected int base, count;<br />

84<br />

85<br />

86 public Array (int n, int m)<br />

87 {<br />

88 data = new Object[n];<br />

89 base = m;<br />

90 count = 0;<br />

91 }<br />

92<br />

Bylaag 2 - Klasbesprekings<br />

60


63 public String toString()<br />

64 {<br />

65 Return Integer.toString(value);<br />

66 }<br />

67<br />

68 Protected int compareTo (Comparable object)<br />

69 {<br />

70 Int arg = (Int) object;<br />

71 Long diff = (long) value - (long) arg.value;<br />

72 if (diff < 0)<br />

73 return -1;<br />

74 Else if (diff > 0)<br />

75 return +1;<br />

76 Else<br />

77 return 0;<br />

78 }<br />

79 }<br />

80 public class Array extends AbstractObject<br />

81 {<br />

82 protected Object[] data;<br />

83 protected int base, count;<br />

84<br />

85<br />

86 public Array (int n, int m)<br />

87 {<br />

88 data = new Object[n];<br />

89 base = m;<br />

90 count = 0;<br />

91 }<br />

92<br />

Appendix 2<br />

60


93 public Array()<br />

94 {<br />

95 this(0,0);<br />

96 }<br />

97<br />

98 public Array(int n)<br />

99 {<br />

100 this(n,0);<br />

101 }<br />

102<br />

103<br />

104 public Object get (int position)<br />

105 { return data[position-base];}<br />

106<br />

107<br />

108 public void put(int position, Object object)<br />

109 {<br />

110 data[position-base]= object;<br />

111 count++;<br />

112 }<br />

113<br />

114<br />

115 protected int compareTo (Comparable object)<br />

116 {<br />

117 return 0;<br />

118 }<br />

119<br />

120 public String toString()<br />

121 {<br />

122 String returnString;<br />

123 int k;<br />

124<br />

125 ReturnString = "";<br />

126 for (k = 0; k


93 public Array()<br />

94 {<br />

95 this(0,0);<br />

96 }<br />

97<br />

98 public Array(int n)<br />

99 {<br />

100 this(n,0);<br />

101 }<br />

102<br />

103<br />

104 public Object get (int position)<br />

105 { return data[position-base];}<br />

106<br />

107<br />

108 public void put(int position, Object object)<br />

109 {<br />

110 data[position-base]= object;<br />

111 count++;<br />

112 }<br />

113<br />

114<br />

115 protected int compareTo (Comparable object)<br />

116 {<br />

117 return 0;<br />

118 }<br />

119<br />

120 public String toString()<br />

121 {<br />

122 String returnString;<br />

123 int k;<br />

124<br />

125 ReturnString = "";<br />

126 for (k = 0; k


132 }<br />

133<br />

134<br />

135 public void sort()<br />

136 {<br />

137 int j,k,smallpos,n;<br />

138 Object smallest,temp;<br />

139 Comparable g1,g2;<br />

140<br />

141<br />

142 for (j=0;j


132 }<br />

133<br />

134<br />

135 public void sort()<br />

136 {<br />

137 int j,k,smallpos,n;<br />

138 Object smallest,temp;<br />

139 Comparable g1,g2;<br />

140<br />

141<br />

142 for (j=0;j


163 public class Sorteerints extends Applet<br />

164 {<br />

165 Label prompt,iValue,resultString;<br />

166 TextField input;<br />

167 Array arr;<br />

168 int i,j, flag;<br />

169<br />

170<br />

171<br />

172<br />

173 public void init()<br />

174 {<br />

175 arr = new Array(20);<br />

176 prompt = new Label("Enter an Integer and press return");<br />

177 input = new TextField(10);<br />

178 iValue = new Label(" ") ;<br />

179 ResultString = new Label(" ");<br />

180 i = 0;<br />

181 flag = 0;<br />

182 add(prompt);<br />

183 add(input);<br />

184 add(iValue);<br />

185 add(resultString);<br />

186 }<br />

187<br />

188<br />

189 public boolean action(Event e, Object arg)<br />

190<br />

191 {<br />

192 int k,num;<br />

193 String arrString = new String(" ");<br />

194<br />

195<br />

196 if (e.target instance<strong>of</strong> TextField)<br />

197 {<br />

198 num = Integer.parseInt(input.getText());<br />

199 arr.put(i, new Int(num));<br />

200<br />

201 i++;<br />

Bylaag 2 - Klasbesprekings<br />

63


163 public class Sorteerints extends Applet<br />

164 {<br />

165 Label prompt,iValue,resultString;<br />

166 TextField input;<br />

167 Array arr;<br />

168 int i,j, flag;<br />

169<br />

170<br />

171<br />

172<br />

173 public void init()<br />

174 {<br />

175 arr = new Array(20);<br />

176 prompt = new Label("Enter an Integer and press return");<br />

177 input = new TextField(10);<br />

178 iValue = new Label(" ") ;<br />

179 ResultString = new Label(" ");<br />

180 i = 0;<br />

181 flag = 0;<br />

182 add(prompt);<br />

183 add(input);<br />

184 add(iValue);<br />

185 add(resultString);<br />

186 }<br />

187<br />

188<br />

189 public boolean action(Event e, Object arg)<br />

190<br />

191 {<br />

192 int k,num;<br />

193 String arrString = new String(" ");<br />

194<br />

195<br />

196 if (e.target instance<strong>of</strong> TextField)<br />

197 {<br />

198 num = Integer.parseInt(input.getText());<br />

199 arr.put(i, new Int(num));<br />

200<br />

201 i++;<br />

Appendix 2<br />

63


202 input.setText("");<br />

203 iValue.setText(Integer.toString(i));<br />

204<br />

205 arr.sort();<br />

206 ArrString = arr.toString();<br />

207 ResultString.setText(arrString);<br />

208<br />

209 return true;<br />

210 }<br />

211 return false;<br />

212 }<br />

213<br />

214 }<br />

Bylaag 2 - Klasbesprekings<br />

JY MOET ALLES IN HIERDIE BESPREKING VERSTAAN OM HIERDIE VAK TE<br />

KAN SLAAG!<br />

64


202 input.setText("");<br />

203 iValue.setText(Integer.toString(i));<br />

204<br />

205 arr.sort();<br />

206 ArrString = arr.toString();<br />

207 ResultString.setText(arrString);<br />

208<br />

209 return true;<br />

210 }<br />

211 return false;<br />

212 }<br />

213<br />

214 }<br />

Appendix 2<br />

YOU MUST UNDERSTAND EVERYTHING IN THIS DISCUSSION IN ORDER TO<br />

PASS THIS SUBJECT!<br />

64


KLASBESPREKING 3:<br />

’n DRYWERPROGRAM VIR HOOFSTUK 5 EN 6<br />

Wat doen hierdie program?<br />

• Dit is ’n poging om die klasse van ho<strong>of</strong>stukke 5 en 6 te gebruik.<br />

Bylaag 2 - Klasbesprekings<br />

• Op die boek se tuisblad (kyk op bl xi voor die inhoudsopgawe vir die adres) is daar ’n<br />

demoprogram (demo2) wat die klasse gebruik.<br />

• Die demo gebruik Containers en ander goed wat ons nie gedoen het nie, gevolglik het<br />

ek dit aangepas.<br />

Wat is die metode wat gevolg is?<br />

• Ek het eers al die klasse afgelaai en die lêername na die klasname toe verander.<br />

• Van die klasse is in meer as een lêer en ek het hulle toe bymekaar gestoor in een lêer.<br />

• Ek het toe al die klasse ge-“compile.”<br />

• Die exception handling het probleme geskep en ek het toe al die exceptions na<br />

Array<strong>Index</strong>OutOf Bounds verander wat ’n ingeboude Java-fout is.<br />

Die Drywerprogram<br />

• Dis r<strong>of</strong>weg gegrond op Demo2 van die tuisblad.<br />

• Indien jy dit probeer aflaai: Dit kan nie in Notepad gelees word nie, maar DOS se EDIT<br />

maak dit oop.<br />

• Ek probeer om met Int-datatipe ’n stapel as ’n vektor (array) te implementeer.<br />

• Die klasse werk almal met Object en mens moet, wanneer jy iets in die stapel<br />

voeg, die datatipe aandui.<br />

• Wanneer ek dit uit die stapel haal, verander ek dit weer na Int en vertoon dit met die<br />

toString()-funksie wat ek by Int bygesit het.<br />

Die probleem<br />

• My program het heeltemal reg gewerk behalwe dat die data wat op die skerm verskyn<br />

het die adresse van die veranderlikes was en nie die waardes nie!<br />

• Die probleem is dus dat Object se toString() nie die waardes wil druk nie. Die fout kom<br />

in AbstractContainer se toString() voor.<br />

• Kyk na die tweede uitvoerskerm. Ek sien toe die woord Int, en na vele ander pogings<br />

sit ek toe net vir die klas Int ’n toString() by. Dit werk!!!!<br />

• Die rede is dat Object se toString() nie weet wat die data is en hoe om dit te<br />

vertoon nie. Dit is eintlik maar net ’n wyser na die objek – in ons geval Int.<br />

Wanneer Object se toString() geroep word soos wat dit indirek in lyn 100 gedoen<br />

word, word daar in die hiërargie afgesoek na die heel onderste klas in die boom –<br />

in hierdie geval die Int-klas. Die Int-klas se toString() word dan gebruik.<br />

• Ek gee al my lêers vir julle – dan kan julle sien wat is bymekaar gesit ens.<br />

65


CLASS DISCUSSION 3:<br />

A DRIVER PROGRAM FOR CHAPTER 5 AND 6<br />

What does the program do?<br />

• It is an attempt to use the classes <strong>of</strong> chapters 5 and 6.<br />

Appendix 2<br />

• On the webpage <strong>of</strong> the book (take a look on p xi <strong>of</strong> the table <strong>of</strong> contents for the<br />

address) there is a demo program (demo2) that uses the classes.<br />

• The demo uses Containers and other things we do not focus on, therefore I adapted it.<br />

What is the method being followed?<br />

• I first downloaded all the classes and changed the file names to class names.<br />

• Some <strong>of</strong> the classes are in more than one file and I stored them together in one file.<br />

• Then I compiled all the classes.<br />

• The exception handling created problems and I changed all the exceptions to<br />

Array<strong>Index</strong>OutOf Bounds – this is a built-in error in Java.<br />

The Driver program<br />

• It is broadly based on Demo2 <strong>of</strong> the homepage.<br />

• If you try to download it: It cannot be read in Notepad, but DOS’s EDIT opens it.<br />

• I attempted to implement a stack as a vector (array) with an Int data type.<br />

• All the classes work with Object and you must indicate the data type when you<br />

add something to the stack.<br />

• When I remove it from the stack, I change it back to an Int and display it with the<br />

toString() function I added to the Int.<br />

The problem<br />

• My program functioned correctly except that the data displayed on the screen was the<br />

addresses <strong>of</strong> the variables instead <strong>of</strong> the values!<br />

• This means that the Object’s toString() would not print the values. The error originates<br />

from the toString() in the AbstractContainer.<br />

• Look at the second output screen. I then saw the word Int and after several attempts<br />

only added to the Int class a toString(). It works!!!!<br />

• The reason is the toString() <strong>of</strong> the Object does not know what the data is or how<br />

to display it. In fact, it is just a pointer to the object – in this case Int. When the<br />

toString() <strong>of</strong> the Object is called as it is indirectly done in line 100, a search is<br />

done all the way down the hierarchy to the class at the very bottom <strong>of</strong> the tree –<br />

in this case the Int class. The toString() <strong>of</strong> the Int class is then used.<br />

• I am giving all my files to you so can you see what is grouped together, etc.<br />

65


Die een wat werk:<br />

Die een wat die adresse wys:<br />

Bylaag 2 - Klasbesprekings<br />

66


The one that works:<br />

The one showing the addresses:<br />

Appendix 2<br />

66


pr 5.1<br />

public interface Comparable<br />

{<br />

}<br />

boolean isLT (Comparable object);<br />

boolean isLE (Comparable object);<br />

boolean isGT (Comparable object);<br />

boolean isGE (Comparable object);<br />

boolean isEQ (Comparable object);<br />

boolean isNE (Comparable object);<br />

int compare (Comparable object);<br />

//Pr5.2+pr5.3<br />

public abstract class AbstractObject<br />

{<br />

implements Comparable<br />

protected abstract int compareTo (Comparable arg);<br />

public final boolean isLT (Comparable object)<br />

{ return compare (object) < 0; }<br />

public final boolean isLE (Comparable object)<br />

{ return compare (object) 0; }<br />

public final boolean isGE (Comparable object)<br />

{ return compare (object) >= 0; }<br />

public final boolean isEQ (Comparable object)<br />

{ return compare (object) == 0; }<br />

public final boolean isNE (Comparable object)<br />

{ return compare (object) != 0; }<br />

public final boolean equals (Object object)<br />

Bylaag 2 - Klasbesprekings<br />

67


pr 5.1<br />

public interface Comparable<br />

{<br />

}<br />

boolean isLT (Comparable object);<br />

boolean isLE (Comparable object);<br />

boolean isGT (Comparable object);<br />

boolean isGE (Comparable object);<br />

boolean isEQ (Comparable object);<br />

boolean isNE (Comparable object);<br />

int compare (Comparable object);<br />

//Pr5.2+pr5.3<br />

public abstract class AbstractObject<br />

{<br />

implements Comparable<br />

protected abstract int compareTo (Comparable arg);<br />

public final boolean isLT (Comparable object)<br />

{ return compare (object) < 0; }<br />

public final boolean isLE (Comparable object)<br />

{ return compare (object) 0; }<br />

public final boolean isGE (Comparable object)<br />

{ return compare (object) >= 0; }<br />

public final boolean isEQ (Comparable object)<br />

{ return compare (object) == 0; }<br />

public final boolean isNE (Comparable object)<br />

{ return compare (object) != 0; }<br />

public final boolean equals (Object object)<br />

Appendix 2<br />

67


}<br />

{<br />

}<br />

if (object instance<strong>of</strong> Comparable)<br />

else<br />

return isEQ ((Comparable) object);<br />

return false;<br />

public final int compare (Comparable arg)<br />

{<br />

}<br />

if (getClass () == arg.getClass ())<br />

else<br />

// Prog 5.8<br />

return compareTo (arg);<br />

return getClass ().getName ().compareTo (<br />

public interface Container<br />

{<br />

}<br />

extends Comparable<br />

int getCount ();<br />

boolean isEmpty ();<br />

boolean isFull ();<br />

void purge ();<br />

void accept (Visitor visitor);<br />

arg.getClass ().getName ());<br />

// Enumeration getEnumeration ();<br />

// pr5.9 + 5.12<br />

public abstract class AbstractContainer<br />

{<br />

extends AbstractObject<br />

implements Container<br />

protected int count;<br />

public int getCount ()<br />

{ return count; }<br />

Bylaag 2 - Klasbesprekings<br />

68


}<br />

{<br />

}<br />

if (object instance<strong>of</strong> Comparable)<br />

else<br />

return isEQ ((Comparable) object);<br />

return false;<br />

public final int compare (Comparable arg)<br />

{<br />

}<br />

if (getClass () == arg.getClass ())<br />

else<br />

// Prog 5.8<br />

return compareTo (arg);<br />

return getClass ().getName ().compareTo (<br />

public interface Container<br />

{<br />

}<br />

extends Comparable<br />

int getCount ();<br />

boolean isEmpty ();<br />

boolean isFull ();<br />

void purge ();<br />

void accept (Visitor visitor);<br />

arg.getClass ().getName ());<br />

// Enumeration getEnumeration ();<br />

// pr5.9 + 5.12<br />

public abstract class AbstractContainer<br />

{<br />

extends AbstractObject<br />

implements Container<br />

protected int count;<br />

public int getCount ()<br />

{ return count; }<br />

Appendix 2<br />

68


}<br />

public boolean isEmpty ()<br />

{ return getCount () == 0; }<br />

public boolean isFull ()<br />

{ return false; }<br />

public String toString ()<br />

{<br />

}<br />

final StringBuffer buffer = new StringBuffer ();<br />

Visitor visitor = new AbstractVisitor ()<br />

{<br />

};<br />

// Pr 5.10<br />

private boolean comma;<br />

public void visit (Object object)<br />

{<br />

if (comma)<br />

buffer.append (", ");<br />

buffer.append(object);<br />

comma = true;<br />

}<br />

accept (visitor);<br />

return "{" + buffer + "}";<br />

public interface Visitor<br />

{<br />

}<br />

void visit (Object object);<br />

boolean isDone ();<br />

//pr 5.11<br />

public abstract class AbstractVisitor<br />

implements Visitor<br />

Bylaag 2 - Klasbesprekings<br />

69


}<br />

public boolean isEmpty ()<br />

{ return getCount () == 0; }<br />

public boolean isFull ()<br />

{ return false; }<br />

public String toString ()<br />

{<br />

}<br />

final StringBuffer buffer = new StringBuffer ();<br />

Visitor visitor = new AbstractVisitor ()<br />

{<br />

};<br />

// Pr 5.10<br />

private boolean comma;<br />

public void visit (Object object)<br />

{<br />

if (comma)<br />

buffer.append (", ");<br />

buffer.append(object);<br />

comma = true;<br />

}<br />

accept (visitor);<br />

return "{" + buffer + "}";<br />

public interface Visitor<br />

{<br />

}<br />

void visit (Object object);<br />

boolean isDone ();<br />

//pr 5.11<br />

public abstract class AbstractVisitor<br />

implements Visitor<br />

Appendix 2<br />

69


{<br />

}<br />

public void visit (Object object)<br />

{}<br />

public boolean isDone ()<br />

//pr 6.1<br />

{ return false; }<br />

public interface Stack<br />

{<br />

}<br />

extends Container<br />

Object getTop ();<br />

void push (Object object);<br />

Object pop ();<br />

// Pr 6.2+6.3 +6.4 +6.5<br />

public class StackAsArray<br />

{<br />

extends AbstractContainer<br />

implements Stack<br />

protected Object[] array;<br />

public StackAsArray (int size)<br />

{ array = new Object [size]; }<br />

public void purge ()<br />

{<br />

}<br />

while (count > 0)<br />

array [--count] = null;<br />

public void push (Object object)<br />

{<br />

}<br />

if (count == array.length)<br />

throw new Array<strong>Index</strong>OutOfBoundsException ();<br />

array [count++] = object;<br />

Bylaag 2 - Klasbesprekings<br />

70


{<br />

}<br />

public void visit (Object object)<br />

{}<br />

public boolean isDone ()<br />

//pr 6.1<br />

{ return false; }<br />

public interface Stack<br />

{<br />

}<br />

extends Container<br />

Object getTop ();<br />

void push (Object object);<br />

Object pop ();<br />

// Pr 6.2+6.3 +6.4 +6.5<br />

public class StackAsArray<br />

{<br />

extends AbstractContainer<br />

implements Stack<br />

protected Object[] array;<br />

public StackAsArray (int size)<br />

{ array = new Object [size]; }<br />

public void purge ()<br />

{<br />

}<br />

while (count > 0)<br />

array [--count] = null;<br />

public void push (Object object)<br />

{<br />

}<br />

if (count == array.length)<br />

throw new Array<strong>Index</strong>OutOfBoundsException ();<br />

array [count++] = object;<br />

Appendix 2<br />

70


pr 5.5<br />

public class Int<br />

{<br />

}<br />

extends AbstractObject<br />

protected int value;<br />

public Int (int value)<br />

{ this.value = value; }<br />

public int intValue ()<br />

{ return value; }<br />

public String toString()<br />

{<br />

}<br />

return Integer.toString(value);<br />

protected int compareTo (Comparable object)<br />

{<br />

}<br />

Int arg = (Int) object;<br />

long diff = (long) value - (long) arg.value;<br />

if (diff < 0)<br />

return -1;<br />

else if (diff > 0)<br />

else<br />

return +1;<br />

return 0;<br />

//Drywer Program<br />

import java.applet.Applet;<br />

import java.awt.*;<br />

import java.awt.event.*;<br />

public class StackDriver extends Applet<br />

{<br />

Label prompt,resultString;<br />

TextField input;<br />

Bylaag 2 - Klasbesprekings<br />

71


pr 5.5<br />

public class Int<br />

{<br />

}<br />

extends AbstractObject<br />

protected int value;<br />

public Int (int value)<br />

{ this.value = value; }<br />

public int intValue ()<br />

{ return value; }<br />

public String toString()<br />

{<br />

}<br />

return Integer.toString(value);<br />

protected int compareTo (Comparable object)<br />

{<br />

}<br />

Int arg = (Int) object;<br />

long diff = (long) value - (long) arg.value;<br />

if (diff < 0)<br />

return -1;<br />

else if (diff > 0)<br />

else<br />

return +1;<br />

return 0;<br />

//Drywer Program<br />

import java.applet.Applet;<br />

import java.awt.*;<br />

import java.awt.event.*;<br />

public class StackDriver extends Applet<br />

{<br />

Label prompt,resultString;<br />

TextField input;<br />

Appendix 2<br />

71


Button pushButton, popButton;<br />

StackAsArray myStack;<br />

//Stack is a abstractContainer p 6.2 p122<br />

//AbstracContainer extends abstractObject p 5.2 p 101<br />

//and is a Container p5.9 p107<br />

//AbstarctObject p102 implements comparable pr 5.1p100<br />

public void init()<br />

{<br />

}<br />

prompt = new Label("Enter an Integer and press return");<br />

pushButton = new Button("Push");<br />

popButton = new Button("Pop");<br />

input = new TextField(10);<br />

resultString = new Label(" ");<br />

myStack = new StackAsArray(10);<br />

add(prompt);<br />

add(input);<br />

add(pushButton);<br />

add(popButton);<br />

add(resultString);<br />

public boolean action(Event e, Object arg)<br />

{<br />

int num;<br />

Int number;<br />

String listString;<br />

Button b;<br />

if (e.target instance<strong>of</strong> Button)<br />

{<br />

b = (Button) e.target;<br />

if (b==pushButton)<br />

{<br />

}<br />

num = Integer.parseInt(input.getText());<br />

myStack.push(new Int(num));<br />

if (b==popButton)<br />

Bylaag 2 - Klasbesprekings<br />

72


Button pushButton, popButton;<br />

StackAsArray myStack;<br />

//Stack is a abstractContainer p 6.2 p122<br />

//AbstracContainer extends abstractObject p 5.2 p 101<br />

//and is a Container p5.9 p107<br />

//AbstarctObject p102 implements comparable pr 5.1p100<br />

public void init()<br />

{<br />

}<br />

prompt = new Label("Enter an Integer and press return");<br />

pushButton = new Button("Push");<br />

popButton = new Button("Pop");<br />

input = new TextField(10);<br />

resultString = new Label(" ");<br />

myStack = new StackAsArray(10);<br />

add(prompt);<br />

add(input);<br />

add(pushButton);<br />

add(popButton);<br />

add(resultString);<br />

public boolean action(Event e, Object arg)<br />

{<br />

int num;<br />

Int number;<br />

String listString;<br />

Button b;<br />

if (e.target instance<strong>of</strong> Button)<br />

{<br />

b = (Button) e.target;<br />

if (b==pushButton)<br />

{<br />

}<br />

num = Integer.parseInt(input.getText());<br />

myStack.push(new Int(num));<br />

if (b==popButton)<br />

Appendix 2<br />

72


}<br />

}<br />

}<br />

{<br />

}<br />

number = (Int) myStack.pop();<br />

input.setText(number.toString());<br />

//ons het mos ‘n toString bygesit vir Int<br />

//pr5.12 p111, pr5.11 p110, use p5.10 p107<br />

listString = myStack.toString(); //pr5.12 p111<br />

resultString.setText(listString);<br />

return true;<br />

Bylaag 2 - Klasbesprekings<br />

73


}<br />

}<br />

}<br />

{<br />

}<br />

number = (Int) myStack.pop();<br />

input.setText(number.toString());<br />

//ons het mos ‘n toString bygesit vir Int<br />

//pr5.12 p111, pr5.11 p110, use p5.10 p107<br />

listString = myStack.toString(); //pr5.12 p111<br />

resultString.setText(listString);<br />

return true;<br />

Appendix 2<br />

73


BYLAAG 3 – EKSAMENVRAESTEL<br />

Bylaag 3 - Eksamenvraestel<br />

74


APPENDIX 3– EXAMINATION PAPER<br />

Appendix 3<br />

74


Requirements for this paper:<br />

Bylaag 3 - Eksamenvraestel<br />

Multiple choice cards: Non-programmable calculator: Open book examination<br />

Graphic paper: Laptop:<br />

EKSAMEN/<br />

EXAMINATION:<br />

VAKKODE/<br />

SUBJECT CODE:<br />

JANUARIE 2003<br />

JANUARY 2003<br />

GRADE/DEGREE/<br />

/ DIPLOMA:<br />

BSc BCom<br />

RKW211 / ITRW212 DUUR/<br />

DURATION:<br />

VAK / SUBJECT: MAKS / MAX: 70<br />

EKSAMINATOR(E)/<br />

EXAMINER(S):<br />

R Goede<br />

MODERATOR: Pr<strong>of</strong> GR Drevin<br />

Vraag 1 / Question 1<br />

DATUM /<br />

DATE:<br />

2 uur<br />

2 hours<br />

Bepaal die totale looptyd van hierdie programdeel deur van die vereenvoudigde model gebruik te<br />

maak.<br />

Determine the total running time <strong>of</strong> this program segment by using the simplified model.<br />

Maak gebruik van die volgende gelykheid:<br />

Use the following equation:<br />

n<br />

∑<br />

i=<br />

1<br />

n(<br />

n + 1)<br />

i =<br />

2<br />

1 public class Question 1<br />

2 {<br />

3 public static int numbers (int n)<br />

4 {<br />

5 int prod = 1;<br />

6 for (int i=0; i


Requirements for this paper:<br />

Multiple choice cards: Non-programmable calculator: Open book examination<br />

Graphic paper: Laptop:<br />

EKSAMEN/<br />

EXAMINATION:<br />

VAKKODE/<br />

SUBJECT CODE:<br />

JANUARIE 2003<br />

JANUARY 2003<br />

GRADE/DEGREE/<br />

/ DIPLOMA:<br />

BSc BCom<br />

RKW211 / ITRW212 DUUR/<br />

DURATION:<br />

VAK / SUBJECT: MAKS / MAX: 70<br />

EKSAMINATOR(E)/<br />

EXAMINER(S):<br />

R Goede<br />

MODERATOR: Pr<strong>of</strong> GR Drevin<br />

Vraag 1 / Question 1<br />

DATUM /<br />

DATE:<br />

Appendix 3<br />

2 uur<br />

2 hours<br />

Bepaal die totale looptyd van hierdie programdeel deur van die vereenvoudigde model gebruik te<br />

maak.<br />

Determine the total running time <strong>of</strong> this program segment by using the simplified model.<br />

Maak gebruik van die volgende gelykheid:<br />

Use the following equation:<br />

n<br />

∑<br />

i=<br />

1<br />

n(<br />

n + 1)<br />

i =<br />

2<br />

1 public class Question 1<br />

2 {<br />

3 public static int numbers (int n)<br />

4 {<br />

5 int prod = 1;<br />

6 for (int i=0; i


Vraag 2 / Question 2<br />

2.1 Gee die definisie van die asimtotiese bo-grens - O().<br />

Bylaag 3 - Eksamenvraestel<br />

Give the definition <strong>of</strong> the asymptotic upper bound - O(). (4)<br />

2.2 Gee ‘n volledige asimptotiese ontleding van die volgende klas:<br />

Give a complete asymptotic analysis <strong>of</strong> the following class: (6)<br />

1 public class Question 2<br />

2 public static int numbers (int n)<br />

3 {<br />

4 int prod = 1;<br />

5 for (int i=0; i


Vraag 2 / Question 2<br />

2.1 Gee die definisie van die asimtotiese bo-grens - O().<br />

Appendix 3<br />

Give the definition <strong>of</strong> the asymptotic upper bound - O(). (4)<br />

2.2 Gee ‘n volledige asimptotiese ontleding van die volgende klas:<br />

Give a complete asymptotic analysis <strong>of</strong> the following class: (6)<br />

1 public class Question 2<br />

2 public static int numbers (int n)<br />

3 {<br />

4 int prod = 1;<br />

5 for (int i=0; i


}<br />

{<br />

}<br />

data[position-base]= object;<br />

count++;<br />

protected int compareTo (Comparable object)<br />

{<br />

return 0;<br />

}<br />

Bylaag 3 - Eksamenvraestel<br />

Skryf ‘n metode vir die klas: Array, genaamd deleteSmallest() wat die kleinste element uit<br />

die skikking verwyder. Die metode moet die waarde van die kleinste getal aan die roepende<br />

program terugstuur en die kleinste getal uit die skikking verwyder.<br />

Write a method for the class Array called deleteSmallest() that removes the smallest number from the<br />

array. The method should return the value <strong>of</strong> the smallest number to the calling program, and remove<br />

the smallest number from the array.<br />

(10)<br />

Vraag 4 / Question 4<br />

Bestudeer die volgende skermuitdruk en die meegaande program:<br />

Study the following screen printout and the associated program:<br />

1 import java.applet.Applet;<br />

2 import java.awt.*;<br />

3 import java.awt.event.*;<br />

4 public class Driver extends Applet<br />

5 {<br />

6 public void init()<br />

7 {<br />

8 LinkedList list = new LinkedList();<br />

9 }<br />

10 public boolean action(Event e, Object arg)<br />

11 {<br />

12 String s;<br />

13 char in;<br />

14 Button pressed;<br />

15 if (e.target instance<strong>of</strong> Button)<br />

77


}<br />

{<br />

}<br />

data[position-base]= object;<br />

count++;<br />

protected int compareTo (Comparable object)<br />

{<br />

return 0;<br />

}<br />

Appendix 3<br />

Skryf ‘n metode vir die klas: Array, genaamd deleteSmallest() wat die kleinste element uit die<br />

skikking verwyder. Die metode moet die waarde van die kleinste getal aan die roepende<br />

program terugstuur en die kleinste getal uit die skikking verwyder.<br />

Write a method for the class Array called deleteSmallest() that removes the smallest number<br />

from the array. The method should return the value <strong>of</strong> the smallest number to the calling<br />

program, and remove the smallest number from the array.<br />

Vraag 4 / Question 4<br />

Bestudeer die volgende skermuitdruk en die meegaande program:<br />

Study the following screen printout and the associated program:<br />

1 import java.applet.Applet;<br />

2 import java.awt.*;<br />

3 import java.awt.event.*;<br />

4 public class Driver extends Applet<br />

5 {<br />

6 public void init()<br />

7 {<br />

8 LinkedList list = new LinkedList();<br />

9 }<br />

10 public boolean action(Event e, Object arg)<br />

11 {<br />

12 String s;<br />

13 char in;<br />

14 Button pressed;<br />

15 if (e.target instance<strong>of</strong> Button)<br />

(10)<br />

77


16 {<br />

17 pressed = (Button)e.target;<br />

18 if (pressed == sort)<br />

19 {<br />

20 list.sort();<br />

21 }<br />

22 if (pressed == prepend)<br />

23 {<br />

24 s =input.getText();<br />

25 in = s.charAt(0);<br />

26 list.prepend(new Char(in));<br />

27 }<br />

28 if (pressed == append)<br />

29 {<br />

30 s = input.getText();<br />

31 in = s.charAt(0);<br />

32 list.append(new Char(in));<br />

33 }<br />

34 showString = list.toString();<br />

35<br />

36 resultString.setText(showString);<br />

37 return true;<br />

38 }<br />

39 return false;<br />

40 }<br />

41 }<br />

Bylaag 3 - Eksamenvraestel<br />

4.1 Skryf die Java-kode om die skermuitleg te doen deur die kode van die init()-metode te<br />

skryf. Hou die res van die kode in gedagte wanneer name van veranderlikes gekies<br />

word.<br />

Write the Java code to do the screen layout by writing the code <strong>of</strong> the init() method.<br />

Keep the rest <strong>of</strong> the code in mind when choosing variable names. (5)<br />

4.2 Verduidelik die werking van lyne 15 tot 21 in jou eie woorde.<br />

Explain the operation <strong>of</strong> lines 15 to 21 in your own words. (5)<br />

4.3 Verduidelik die werking van lyne 34 tot 39 in jou eie woorde.<br />

Explain the operation <strong>of</strong> lines 34 to 39 in your own words. (5)<br />

78


16 {<br />

17 pressed = (Button)e.target;<br />

18 if (pressed == sort)<br />

19 {<br />

20 list.sort();<br />

21 }<br />

22 if (pressed == prepend)<br />

23 {<br />

24 s =input.getText();<br />

25 in = s.charAt(0);<br />

26 list.prepend(new Char(in));<br />

27 }<br />

28 if (pressed == append)<br />

29 {<br />

30 s = input.getText();<br />

31 in = s.charAt(0);<br />

32 list.append(new Char(in));<br />

33 }<br />

34 showString = list.toString();<br />

35<br />

36 resultString.setText(showString);<br />

37 return true;<br />

38 }<br />

39 return false;<br />

40 }<br />

41 }<br />

Appendix 3<br />

4.1 Skryf die Java-kode om die skermuitleg te doen deur die kode van die init() metode te<br />

skryf. Hou die res van die kode in gedagte wanneer name van veranderlikes gekies<br />

word.<br />

Write the Java code to do the screen layout by writing the code <strong>of</strong> the init() method.<br />

Keep the rest <strong>of</strong> the code in mind when choosing variable names. (5)<br />

4.2 Verduidelik die werking van lyne 15 tot 21 in jou eie woorde.<br />

Explain the operation <strong>of</strong> lines 15 to 21 in your own words. (5)<br />

4.3 Verduidelik die werking van lyne 34 tot 39 in jou eie woorde.<br />

Explain the operation <strong>of</strong> lines 34 to 39 in your own words. (5)<br />

78


Vraag 5 / Question 5<br />

Bestudeer die volgende klas:<br />

Study the following class:<br />

public class LinkedList extends AbstractObject<br />

{<br />

protected Element head;<br />

protected Element tail;<br />

}<br />

public LinkedList()<br />

{<br />

purge();<br />

}<br />

public void purge()<br />

{<br />

head = null;<br />

tail = null;<br />

}<br />

public boolean isEmpty()<br />

{<br />

return head == null;<br />

}<br />

public final class Element<br />

{<br />

public Object datum;<br />

public Element next;<br />

}<br />

Element (Object userDatum, Element userNext)<br />

{<br />

datum = userDatum;<br />

next = userNext;<br />

}<br />

public Object getDatum()<br />

{<br />

return datum;<br />

}<br />

public Element getNext()<br />

{<br />

return next;<br />

}<br />

Bylaag 3 - Eksamenvraestel<br />

Gestel hierdie geskakelde lys word soos ‘n tou bestuur. Skryf ‘n metode vir die klas:<br />

LinkedList genaamd dequeue(), wat ‘n element uit die tou verwyder. Jy mag nie die<br />

bestaan van enige ander behalwe die bogenoemde metodes van die klas LinkedList<br />

aanvaar nie.<br />

Assume this linked list is managed as a queue. Write a method for the class LinkedList called dequeue() that<br />

removes an element from the queue. You may not assume the existence <strong>of</strong> any other than the above given<br />

methods in the class LinkedList<br />

(8)<br />

79


Vraag 5 / Question 5<br />

Bestudeer die volgende klas:<br />

Study the following class:<br />

public class LinkedList extends AbstractObject<br />

{<br />

protected Element head;<br />

protected Element tail;<br />

public LinkedList()<br />

{<br />

purge();<br />

}<br />

public void purge()<br />

{<br />

head = null;<br />

tail = null;<br />

}<br />

public boolean isEmpty()<br />

{<br />

return head == null;<br />

}<br />

public final class Element<br />

{<br />

public Object datum;<br />

public Element next;<br />

}<br />

}<br />

Element (Object userDatum, Element userNext)<br />

{<br />

datum = userDatum;<br />

next = userNext;<br />

}<br />

public Object getDatum()<br />

{<br />

return datum;<br />

}<br />

public Element getNext()<br />

{<br />

return next;<br />

}<br />

Appendix 3<br />

Gestel hierdie geskakelde lys word soos ‘n tou bestuur. Skryf ‘n metode vir die klas:<br />

LinkedList genaamd dequeue(), wat ‘n element uit die tou verwyder. Jy mag nie die<br />

bestaan van enige ander behalwe die bogenoemde metodes van die klas LinkedList<br />

aanvaar nie.<br />

Assume this linked list is managed as a queue. Write a method for the class LinkedList<br />

called dequeue() that removes an element from the queue. You may not assume the<br />

existence <strong>of</strong> any other than the above given methods in the class LinkedList. (8)<br />

79


Vraag 6 / Question 6<br />

Bylaag 3 - Eksamenvraestel<br />

Verduidelik die gebruik van die throw en throws sleutelwoorde in Java. Jy moet ‘n voorbeeld gebruik<br />

om jou verduideliking toe te lig.<br />

Explain the use <strong>of</strong> the throw and throws keywords in Java. You must use an example to elucidate<br />

your explanation.<br />

Vraag 7 / Question 7<br />

7.1 Verduidelik die verskil tussen ‘n objek en ‘n klas. Jy moet ‘n voorbeeld gebruik om jou<br />

verduideliking toe te lig.<br />

Explain the difference beteen an object and a class. You must use an example to elucidate your<br />

explanation.<br />

7.2 Verduidelik wat oorerwing is en verwys spesifiek na die nut daarvan. Jy moet ‘n voorbeeld gebruik<br />

om jou verduideliking toe te lig.<br />

Explain inheritance and refer specifically to its benefit. You must use an example to elucidate your<br />

explanation.<br />

Vraag 8 / Question 8<br />

Verduidelik die volgende terme ten opsigte van bome:<br />

Explain the following termimology with regard to trees:<br />

8.1 Graad van ‘n node / Degree <strong>of</strong> a node<br />

8.2 Hoogte van ‘n boom / Height <strong>of</strong> a tree<br />

8.3 Voorouer van ‘n node / Ancestor <strong>of</strong> a node<br />

TOTAAL<br />

TOTAL 70<br />

(6)<br />

(3)<br />

(3)<br />

(6)<br />

80


Vraag 6 / Question 6<br />

Appendix 3<br />

Verduidelik die gebruik van die throw en throws sleutelwoorde in Java. Jy moet ‘n voorbeeld gebruik<br />

om jou verduideliking toe te lig.<br />

Explain the use <strong>of</strong> the throw and throws keywords in Java. You must use an example to elucidate<br />

your explanation.<br />

Vraag 7 / Question 7<br />

7.1 Verduidelik die verskil tussen ‘n objek en ‘n klas. Jy moet ‘n voorbeeld gebruik om jou<br />

verduideliking toe te lig.<br />

Explain the difference beteen an object and a class. You must use an example to<br />

elucidate your explanation.<br />

7.2 Verduidelik wat oorerwing is en verwys spesifiek na die nut daarvan. Jy moet ‘n<br />

voorbeeld gebruik om jou verduideliking toe te lig.<br />

Explain inheritance and refer specifically to its benefit. You must use an example to<br />

elucidate your explanation.<br />

Vraag 8 / Question 8<br />

Verduidelik die volgende terme ten opsigte van bome:<br />

Explain the following termimology with regard to trees:<br />

8.1 Graad van ‘n node / Degree <strong>of</strong> a node<br />

8.2 Hoogte van ‘n boom / Height <strong>of</strong> a tree<br />

8.3 Voorouer van ‘n node / Ancestor <strong>of</strong> a node<br />

(6)<br />

(3)<br />

(3)<br />

(6)<br />

TOTAAL<br />

TOTAL 70<br />

80

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!