You are on page 1of 14
CARLETON UNIVERSITY Summer. 1.999) Pdmieation 94.2048 Final DURATION: 3 HOURS No. of Students 95 Department Name & Course Number: Systens and Computer Engineering 94. 204A Course instructors) Professor Don Baile; - is MUST count the number of pages in this examination question paper Before beginawg Te 2nd report any discrepancy immediately t0 a proctor. This question paper has 1 eoes. amination question paper May Hot” be taken from the examination oom , Vebeorl We OSES OFS instructions: 1. Attempt all questions. Read each question thoroughly before attempting to waite answers ‘Apswer the questions in your answer booklet on the lined (rightchand) pages Use the blank, {AS left-hand pages in the answer booklet for your rough work. Solutions written on the blank ‘Pages will be assumed to be rough work and will not be graded unless you clearly indicate ‘that you want me to mark them; for example, by drawing a box around the rough work and writing "Mark this" next to the box. 2. ALL PAGES OF THIS FXAM PAPER MUST BE TURNED IN. DO NOT REMOVE ANY PAGES FROM THE EXAM ROOM, 3. Please, do not ask me to explain the questions to you. If you think somethin is unclear or ambiguous, make a reasonable assumption (one that does not contradict the question), write it at the start of your answer, and solve the problem. (However, if you think you have found ‘an error in a question, feel free to ask for assistance!) 4. Unless otherwise noted, you may not change the visibility of the classes, variables, or methods that are presented in this exam paper. IMPORTANT: A Java API reference located at the end of the exam paper. ee sce eel ee We ae Question 1 (4 marks) Class BmailDirectory is a partial definition a Java class that maintains a directory of people's names and their e-mail addresses, This information is stored as key/value pairs in the Hashtable object referred to by ht. ela: mailDirectory ( private Hashtable nt; public EmailDirectory() {ht = new Ha: sable (ys) Public void addaddress(string aName, String anAddress) ( public Vector getaddresses (string aName) {..-) public String getName(string ankddress) { Each name and e-mail address is stored in a St ring object. The keys for the table are the names, Because each person can have more than one e-mail address, the value associated with each key is a Vector of e-mail addresses (that is, a Vector of String objects) Here is an example: Names (keys) Vectors of e-mail addresses (values) Python mpwihon@engsoc.carletoncs, ‘prihow@chatcarleionca, gx1364@sympaticacs Bailey bailev@scecarictonca, donald bailey@earlewon.ca (@) Method getAddresses () is passed a reference to a String object containing a person's name. This method returns a Vector object containing the e-mail addresses for that person Ifthe person's name is not in the directory, the method returns mu, Write the code for this method. (b) Method getName () is passed a reference to a String object containing an e-mail address. ‘This method returns a Str ing object containing the name of the person who has that e-mail address. Ifthe e-mail address is not in the directory, the method returns nuil 1. Write the code for this method, (©) Method addaddress () is passed references to two String objects: one containing a person's name and another containing an e-mail address. This method updates the directory with the name and the address. Write the code for this method. This method must handle two special cases. The first time a particular name is passed to addAddress ()., there will be no entry in the directory for the name, that is, there will be no list of e-mail addresses associated with that name in the hash table. The second special case that addAddress () must handle is when an e-mail address for a particular person has already been added to the directory. In this case, the duplicate address must not be stored in the person's list of e-mail addresses Engineering 94.204* Summer 1999 Page 3 iS Question 2 2emarks) When you looked at the methods declarations in the MouseLi.stenex interface, you might have asked yourself, “What's the difference between pressing the mouse and clicking the mouse?" Here is a partial definition for class MouseDemo, which forms the core of a Java application that answers that question. public class MouseDemo extends Closeablerrane implements MouseListener { public Mousepemo() (...} public static final int FRAMEWIDTH ~ 400; public static final int FRAMEHEIGHT = 300; public static void main(string{] args) t Frane € = new MouseDemo()+ £.setSize(FRAMEWIDTH, FRAMEHEIGHT) ; FlsetVisibie (true)? Using this class, write an application that listens for mouse events on the application's frame Every time a mouse event is sent ta one of the MouseLiistoner methods, the program outputs ‘a message on the system console. The message indicates the kind of mouse event that occurred and the position of the mouse when the event occurred, Here is an example of the messages that might he displayed: Mouse entered @ (100, 40) Mouse pressed @ (109, 87) Mouse released @ (109, 87) Mouse clicked @ (109, 87) Mouse pressed @ (205, 37) Mouse released @ (287, 105) Important: the messages are not displayed in a GUI component inside the application's frame, but are instead sent to the System. aut object. In addition to the Java API provided at the end of the exam, the following may be of use + the position of the mouse when a mouse event occurs can be determined by sending, the getX () and get () messages to the MouseEvent abject that is sent to the mouse stener method for the event. Engineering 94.204* Summer 1999 Page 4 ‘Question 3 (20 marks) x Here are partial definitions for two classes, Counter and MyButtonListener, which form the core of a Java application public class Counter extends Closeableframe ‘ public Counter() (. // entry point for the application public static void main(sering[] args) c Frame £ = new Counter (); f-pack()? £lseevisdbie (true); > Public void countUp() // NOTE: this method has no parameters (// code that updates the text field") Public void countbown() // NOTE: thie method has no parameters (// code that updates the text £ield } , public class MyButtoniistener implements ActionListener t public void actionPerformed (ai fonsvent e) (...) : Using this class, write an application that meets the following specification: ‘© when the program initializes itself, it creates a text field and places it in the upper portion of the application's frame. The textfield displays the text ‘when the program initializes itself, it creates one button labeled "Count up" and another button labeled "Count down". The "Count up" button is placed on the left side of a panel and the "Count down" button is placed on the right side of the panel. The panel is placed in the lower portion of the application's frame ‘+ when the program initializes itself, it arranges for a single instance of MyButtonListener to be registered as the listener object for both buttons. + each time the "Count up” button is pressed, method count Up () increments the value displayed in the textfield by 1. Each time the "Count down" button is pressed, method countDown () decrements the value displayed in the textfield by 1 Note: if you have a String object = that contains the string representation of an integer (€-8., 123"), the following statement calculates the equivalent integer value and stores it in variable 4. oftype int Engineering 94.204* Summer 1999 Page 5 Spe at Question 4 (20 marks) A queue is a data abstraction (abstract data type) that holds an unordered collection of elements Elements are always added to the end of the queue and removed from the front of the queue. As such, we say that elements are added to and removed from a queue according to a FIFO (first-in, first-out) protocol: the first element added is always the first one removed. Here is a partial definition of a Java Queue class: oueue J/ Initialize che queue object se that it is enpty. Public Quewe() Ie .s) J/ aed olom at the end of the queue. public Void add(Object elem) (oss) Jf Remove the object from the front of the queue and discard it. 77 wrine an error message if there are mo elements in the queue to remove public void remove) { JJ Return a reference to the object at the front of the queue without 17 xemoving the object from the queue. Return mull if the queue is empty. Public Object front) (oc) , Mere is an example of how a Queue object could be used to maintain a queue of integers. Java's Ant type is a primitive type, not a class, so we can't store values of type int ina Queue object. The Integer wrapper class is provided so that we can wrap values of type int in objects, An object of class Integer contains a single field of type int. Queue q = new Queues Integer i = new Integer (3); // create an Integer objec: containing the V7 Integer value 3 integer 3 = new Integer(7) integer k = new integer (9) > G.add(i)s // q contains a (reference to} Integer object 3 Gladd(}); // 4 contains (zeferences to) Ineager objects 3. 7 Integer m =! (Integer}q.front(}; // m refers to Integer osject 3 quacdiios 7/ q contains (zeferences to) integer objects 3,35 3 Girenove();//7 q contains {references to) Ineeger aojecte 7, (Although only Integer objects are stored in the queue in this example, when answering, this, question remember that a Queue object can store instances of any class.) (@) Define a class called Queue that inherits from Java's Vector class Write the complete class definition; that is, the code for the constructor and the ada {), front (), and remove () methods. You may change the first statement of the class definition, pub ic class Queue, ifnecessary, but you may not change the specification of the methods, Engineering 94.204* mmer 1999 Page 6 (b) Does the Queue class you wrote in part (a) have an és-a or hast Vector? Briefly explain your answer (©) Ifthe statement did not contain a typecast (downeast) the code would not compile. Explain why the typecast is necessary. (@) The code fragment: vi = new Queued)s Mlustrates an important object-oriented concept. What is the name of this concept? (©) “The Queue class allows the user to manipulate queue objects in ways that violate the queue protocol”. Explain what this statement means and write a line of Java code that illustrates the (© Define another version of the Queue class that uses composition to reuse Java's Vector class. Write the complete class definition; that is, the code for the constructor and the add}, front (), and remove () methods. You may change the first statement of the class definition, public class Queue, if necessary, but you may not change the specification of the methods. (g) Does the Queue class you wrote in part (f) have an #s-a or has-a relationship with class Vector? Briefly explain your answer Engineering 94.204* Summer 1999 Page 7 Question 5 (20 marks) Here are partial definitions of two classes that model students and courses: public ctass student { private int studentNumbers 7+ metheds not shown */ 7 =“ public class course | Private String courseNumber; // e.g., 94.2047, 97.267" Brivate String sections 17 8.50 Re Bye 7° methods noe shown 9/ , (@) Suppose we want to maintain information about the relationship between a student and the ‘entire set of courses in which the student is registered in a particular term: for example, the academic year (¢.g., "1999/2000") and the session (e.g., "Fall", "Winter", or "Summet"). A ‘common approach is to define a StudentCourse class to model the relationship. Here is the specification for the class: + AstudentCourse object has two attributes: one for the academic year and another for the session + AstudentUourse object contains a reference to a Student object and a list of ‘Course objects for the courses in which a student is registered, A Vector is used to maintain the list of courses. + The Student Course constructor is passed three arguments: a reference to the Student object for a particular student, and initial values for the academic year and session attributes. + Student Course has getter methods to return the current values of the academic year and session attributes. * StudentCourse has a void method called addCourse (), which is invoked to add 8 course to the list of courses in which the student is registered. This method has one parameter, a reference to the Course object that is to be added to the list Write the complete class definition for class StudentCourse; that is, define all instance variables, the constructor, the getter methods, and the adaCourse () method. You ean assume that no-one will attempt to add duplicate Course objects to. a StucentCourse; that is, addCourse () does not have to check if its argument has already been stored in the vector, () Write a method for class Student called register tnCourse (), which is passed a reference to a Course object. This method will update the student's Studentcourse object. (Don't write the code for the entire Student: class - just write the code for the registerinCourse() method) Engineering 94.204* Summer 1999. Page 8 wus (©) Write a method for class Stucient called isRegisteredrn (), which determines Whether a student is registered in a particular section of a particular course. ‘The method has wo arguments, the course number and the course section Here is the declaration for the method. Jf Returns true if the student is registered in th 77 ehascoursetlumber) otherwise returns, false. Public boolean ishegisteredin(String thisceurseNumber, String thissection) Before answering part (i), read both parts (i) and (i) @ Write the code for isRegisteredin () @)__norderto write isRegisteredin (), you will need to define additional methods in class StudentCourse and class Course. Write the code for these methods, (@) Draw a UML diagram that depicts the relationships between the Student, StudentCourse, and Course classes, Question 6 (5 marks) This question continues the design of the classes from Question 5. You don't need to repmacuce any of theclass definitions or methods that you wrote for Question 5 in your answer for Ouestion 6; instead, just write the code for any new methods that must be added fo class $tuce, StudentCourse, or Course. ‘The intent of the iterator pattern is to provide a way to access the elements of a collection object Sequemtially without exposing its underlying representation. Objects that implement Java's Enumeration interface implement the iterator pattern, Before answering part (i), read both parts (3) and (i) @) Define a method called a11Courses () for class Student. This method returns an enumeration object (that is, an instance ofa class that implements the Enumeration interface) that allows us to iterate through all the courses in which the student is registered. By repeatedly invoking this object's nextiLement (} method, we can access the Course objects for all of the student's courses. The method is declared as: public Enumeration allCourses(); (i) In order to waite a11Courses () , you will need to define an additional method in class StudentCourse. Write the code for this method. Engineering 94.204" Summer 1999 Page 9 Java API Reference U7 equals() returns true if tho object iz equal te ob} public boolean equals (Object 053) + {/ bashCode() returns the hash value of the object public int hashcode (7 Uf clone () coturns a new ahjact that 4a a copy (a duplicate) of ulin object // voStsing() returns a string representation of the object public string tostringt)+ ‘Size Determination U7 size{) returns the number of components in the vector // Astmpty() returns true Lf the vector is empty Public boolean isEmpty) Uf capacity() returns the current capacity of the vector Uf setsize() sors che siue of the vector, truncatiny os expanding it 70 as necessary Public void setSize(int newsizels // "contains () returns true if elem is a component in the vector public Boolean contains (Object elem > Jf fizseBlenent() returns the Eirst component in the vector public Object firetelement()s Jf YastElement() returns the last component in the vector public object instelemcntt)s // elementAt() returns the component stored at the specified index PUbIEC Object elamentaclint inden)? Insertion and Modification (/ adablement() adds elem to the end of the vector, increasing its size by 17 The capacity Of the vector 1s increased 1f its size becomes gieatee chen 07 Sts Capacity Pablic void addélement (object elem) s Engineering 94208" Summer 1999, Page 10 we, U1 settlement () stores elem in the vector at specified index, 71 dsscerding any previous component at that positions Public void setElementat (Object elem, int index)? // AnsextBlomentAt() inserts elem in the vector at the specified index. zach Jf component in this vector with an index greater or aquel to che specified 47 Andox is shifted upward to have an andes one greater chan the value it had 77 previously. Public voSd insextBlementat (Object elem, int inden); (7 renoveBlenentAt() deletes the component at the specified index. Each 4/ component in this vector with an index greater or equal to the specified 47 sndex is shifted downward to have an index one smalice than the eaiae ic 77 had previously Public void removeRLementat (int index) + 4/ xemoveBlement() removes the first occurrence of elem from this vector. If 4/ the object is found in this vector, each component in the vector with an Jf Andex greater or equal to the object's index is shifted downward vo have 4/ an index one smaller than the value it had previously. Returns exue Lf at 77 Yeast one instance of elem is Found. Public boolean removeElement (Object elem) J/ romoveAliElements () deletes all components from the vector and sets its 17 size 0 0. Public vosd removeAliblements () Search Uf AndexOf() returns the index of the fizet occurrence of elem in the vectors Vi returns -1 1f the object iz not found. Public int indexof topjece elem) Jf AaseIndexof() returns the index of the Last occurrence of elem in tho 77 vector; returns -1 af the object is net founds Public int lactindexof (object elem) + Miscellaneous // clone() returns © copy (a duplicate) of the vecter (everrides Object). Public Object cione()+ JJ etements() returns an enumeration of the components in the vector that “7 Amploments the Enumeration interface. ‘This enumeration object can be ucod V7 bo iterate through all the elements stored in the vector Public Enumeration elements (0) 7/ Sostesng() returns a string representation of the vector Public String toseeingti? Engineering 94.204" Summer 1999 Page 11 clase Hashtable f/clear() clears this hashtable 0 that it contains ne keys. pubiie void ciwart) (/ clone!) creates a shallow copy of this hashtable. Public Gbject clone!) ? (2 contains () returns true if some key maps into the specified value in this Wf hashtable (i.e., it tests if the hash table contains a key/value pair with 77 Bhe specified value; otherwise it returns false bubiie boolean contains {object values Uf containsKey() returns true Lf the specified object is a key in this 47 hashtable (1.e., it tests if the hash table contains a key/value pair with “7 the specified value); otherwise it returns fala public boolean containakey (Onject key? * 7/ slements (returns an enumeration of the values in this hashtable. public Enumeration elements () Jf gee) returns the value to which the specified key is mapped in this 77 hashtable; null if the key iz not mapped to any value in this hasheable. Public Object get (object key) s Jf Asmmpty() returns true if this hashtable maps no keys to values; V7 iten Af the hashtable is smpey, public heolean 1emmpey) + (2 keys returns an enumeration of the keys in this hashtable. Public Enumeration keyet)s (7 Sve.) Gt" Svores the specified key/value pals’ (2 weither the key nor the value can be null. Wf The value can be retrieved by invoking the get method with a key that ss W1 equal to the original key. Y/ Returns the previous value associated with the specified key in this 77 hashtable, of mull if ie did not have one. Public Object puc (object key, Object value]? Uf, rewove|) removes the key (and its corresponding value) from the hashtable WJ This method does nothing if the key ia nse in che hashtable. 7) Returns the value to which the key had bean mapped in this hashtable, or Yi null tf the key did nov have a mapping. Public Object. remove (Object hey) s {J size!) returns the number of keys in this hashtable. public int sizes Jf womteing() returns 9 vather long athiny supeesentation of this hashtable. public String toString Engincering 94.204 Summer 1999 Page 12 WAS, Collection classes in the Java API provide method elements (), which retums an enumeration object; that is, an ‘object that implements the Enumeration interéace 7/ hasMozeBlements() returns true if there are more elements to be enumerated public abstract bociean hasMoreblenenes () // nexttlement () returns the next element in the enumeration Public aostrace object nextilement {7 , Ud constructor. public TextrseldQ // constrictor that initializes the textfield with the specified text. Public TexeFicla(string texts U7 sevText!) displays string 2 in the text field: // govtexe() returns the string currently displayed in the text field Uf adcroxtusstener|) registers a Textiicstoner object with the text field 11 the TentPiola object, * public void addfextlistener(Textiistener 1); Jf kemovetextListener() removes cha specified TextListener object from the 77 text field's set of Listeners. public void removetentiistencs (PextListener 1); YJ The Actiontistener object is invoked when user has changed the tone an 77 the text field and hit the Enter key. Public void adaActioniistence (ActionListener 2); 77 romovenctionListener{) removes the specified Actioniictener object from the V7 text field's set of listeners, Public void removeActioniistencs (ActionListener 1): Engineering 94.204* Summer 1999 Page 13 // constructor - initialize a new button with no label. puplie Button ts // constructor = initialize a new button, with label 3. poblic Button (string 07 UJ setiabel () sets the button's label to a. Public void seehabel isteing 6) > U/ gettabel() returns the button's label public Sering getuabel () Uf sdanctionbistener() registers an ActionListener object with the button. Uf The Actioniistener object is invoked when the burton is clicked with che 11 mouse: Public Void addactionLiscener (ActionListener 2) 4/ romovenctionbistenes() removes the specified ActionListener object from the 77 buttons set of listeners. Public void renoveactionbistaner (ActionListener 2); class Point public int 4; // the x coordinate Public int yi // the y coordinate Uf constructor = initsalive » new Point ae (0, 0) pubite pone) s // constructor ~ initialize a new Point object at (x ¥) J/ Moves this point to the specified location in the #-y coordinate plane. Public void move(iat x, ine ¥)s jf Branslates this point, at location (x, yi by dit along the x aziz and 77 dy slong the y axis so that it now fepresents the point wet, wader public void trensiate(int xe iat yo J/ Returns true if this point and the point referred to by obj 17 nave identical x and y coordinates Public boolean equals (Object ob3)7 U/ Returns 4 representation of this point and its iecation public string eosering() Sone Listener interfaces public interface ActionListener extends EventListene: { Public void actionPerformed (actionsvent €)? , Public interface Textiisrener extends Eventiistener { Public void textValuechanged (TexeBven= @!? , Engineering 94.204* Summer 1999 Page 14 Public interface Adjustmenthistenes extends Eventtistener { Public void adjustmentValuechanged (Adjustmentevene @) Public interface rtembistener extends Eventtistence { Public stenstatechanged(itenEvent 6)? ) Public interface MouseListener extends Eventiistener { public void mouseClicked(MouseBvent ¢): Invoked when the mouse haz Been clicked on a component, y Invoked when @ mouse button has been pressed on a component *y Public void mourePressed (MouseEvent e)s ye a 7 a public void mouseReleased(MouseEvent ¢) i Public void mouseBntered(Mousezvent ¢)s ys public void mouseExited(Mousefvent ©);

You might also like