RAIK 183H Examination 2 Solution November 10, 2014 Name: NUID: This examination consists of 5 questions and you have 110 minutes to complete the test. Show all steps (including any computations/explanations) that lead you to the answers. Please read every question carefully. If you have questions, please raise your hand and I will come to you. Since most of the questions are open-ended, that means you could spend too much time than necessary for some of the questions. Please manage your time well. Answer questions that are more straightforward first. Including this page, there are 8 pages. As part of the requirements of this exam, you must personally pick up the exam after meeting with me in my office for the exam score to be counted. 1
1. (20 points) Event-Driven Programming (10 points) What are the three key components of event-driven programming in Java, and how do they work together? What are the roles of the user, client programmer, and Java? (Hint: You may want to use a diagram.) The three key components are event sources, listeners, and handlers. An event source is a JButton, for example. When a user clicks on a JButton object, it generates an event. Each event source must be attached to a listener to capture the events that occur at that source. This is done by the client programmer. Events captured are then passed to event handlers, which are methods that a client programmer must implement adhering to the prototypes specified by Java through their listener interfaces. For example, to use ActionListener, one must implement the method actionperformed() according to the specification. This allows Java to automatically invoke actionperformed() with the captured event as the argument. (b) (c) (10 points) Write a Java application that displays the following. And, when a user clicks on the ClickMe button, the text Button 1 has been clicked 1 times is displayed. 2
Of course, if the user continues to click the button, number of times will be updated and displayed accordingly. (Note: Please pay attention to syntax, including importing the correct Java packages.) import javax.swing.*; import java.awt.*; import java.awt.event.*; public class OneButton extends JFrame implements ActionListener { private JButton button1; private JTextField field1; private int count; public OneButton() { count = 0; // initialization setlayout(new FlowLayout()); button1 = new JButton("ClickMe"); button1.addactionlistener(this); add(button1); field1 = new JTextField("",20); add(field1); setsize(500,500); setvisible(true); public void actionperformed(actionevent e) { count++; field1.settext("button 1 has been clicked + count + times"); public static void main(string[] arg) { 3
OneButton cool = new OneButton(); 2. (20 points) Exceptions. In exception handling, a method can be a thrower, and/or a catcher, and/or a propagator. (15 points) Show clearly how a single method can be a thrower, a catcher, and a propagator. (Please pay attention to the syntax.) There are many possible solutions. Here is one: public void supermethod(int x) throws Exception { try { if (x < 0) { throw new NumberFormatException( nothing much ); else throw new Exception( okay ); catch (NumberFormatException e) { System.out.println(e.getMessage()); // end supermethod So, in the above, the method throws two types of exception. It catches one (NumberFormatException). It propagates the other (Exception). (b) (5 points) What are checked exceptions and unchecked (runtime) exceptions? Also, give one example of each type of exceptions. Checked exceptions are exceptions that Java checks at compile time such that client programmers must handle in order for Java to compile the program successfully. Unchecked exceptions are runtime exceptions that Java does not check at compile time. An example of checked exceptions is IOException, and an example of unchecked exceptions is NullPointerException. 3. (20 points) Arrays. Suppose that the following has been created with all its constructors, setters, and getters built. 4
class Council { private String name; private Jedi[] members; private int nummemberssofar; // a counter to store # members private final int MAX_COUNCIL_NUM; // a constant the max # // in a council Suppose that the class Jedi has also been created with its constructors, setters, and getters, together with data members private String name, private int force, and private int age. (Note: Pay attention to your syntax.) (6 points) Add a method identifystrongestmember() to the Council class that computes identify the council member with the highest force value and returns that Jedi object. public Jedi identifystrongestmember() { int maxindex = 0; // initialization if (nummemberssofar == 0) return null; else { for (int i = 0; i < nummemberssofar; i++) if (council[maxindex].getforce() < council[i].getforce()) maxindex = i; return council[maxindex]; // end method (b) (8 points) Add a method insertnewmember(jedi newmember, int loc) to the Council class so that the newmember is assigned to members[loc], and members after the location loc are pushed down, and all other data members are updated appropriately. The method should return true if it is okay to insert one new member; and false otherwise. public boolean insertnewmember(jedi newmember, int loc) { boolean okay = false; if (nummemberssofar < MAX_COUNCIL_NUM) { for (int i = nummemberssofar; i > loc; i--) council[i] = council[i-1];// push each down by one loc council[loc] = newmember; nummemberssofar++; 5
okay = true; return okay; // end method (c) (6 points) Add a method clonestrongestmember(int n) that identifies the strongest member of the council, performs a deep copy, and insert it to the list at location 0 of the members, such that there are n clones of that strongest member in the beginning of the members array. (Hint: make use of the methods in parts (b) and (c).) public void clonestrongestmember(int n) { Jedi strongest = identifystrongestmember(); for (int i = 0; i < n; i++) { Jedi clone = new Jedi(); clone.setname(strongest.getname()); clone.setforce(strongest.getforce()); clone.setage(strongest.getage()); boolean success = insertnewmember(clone,0); // end for loop // end method 4. (20 points) Sorting (15 points) Specify the heapsort algorithm. (Must include the definition of a heap, and the algorithm s two phases and corresponding steps.) The heapsort algorithm has two phases: (1) construction and (2) extraction and reconstruction. Construction and reconstruction are very similar. First, we need to define what a heap is. A heap is a tree that satisfies two constraints: (1) structural constraint, and (2) value relationship constraint. The structural constraint states that each node in a heap has at most two children nodes, (b) the nodes of a heap must be packed top-down, and left-to-right. The value relationship constraint states that the value in a parent node must be greater than the values in its children nodes. Construction Phase: 1. Put all the items to be sorted into the tree, packing them top-down, and from left-toright, with at most two children per node. Once this is done, we have satisfied the structural constraint. Then, for all parent nodes, iterating from the last parent node to the first parent node: 6
a. Check whether its value is greater than its children s. If yes. Then move to the next parent node. If no, replace the parent s value with the greater of its children s. For the node that now has the original parent s value, check again to make sure that this value is also greater than its children s. Repeat this until there is no swapping of values. b. Stop once the first parent node is processed as in. Extraction and Reconstruction Phase: 1. The top node s value is the largest value. Extract it and put it in the sorted array. Then, promote the value of the last node in the heap to the top. This is extraction. 2. Then to reconstruct the heap, for only the top node s new value, apply the same process as described in Step above in the construction phase. 3. Repeat until all nodes have been extracted to the sorted array. (b) (5 points) How is a heap represented in an array? Also, how is sort-in-place in Heapsort achieved? A heap is presented in array using the following scheme: an element at position P has children nodes at positions (2*P + 1) and (2*P + 2). Sort-in-place in Heapsort is achieved by storing the extracted root node s value towards the end of the array. 5. (20 points) Short Answers (5 points) Given the following: 1 Jedi council[] = new Jedi[2]; 2 council[0] = new Jedi( Anakin ); // instantiate and name 3 council[1] = new Jedi( Luke ); // instantiate and name 4 Jedi temp = council[0]; 5 council[1] = temp; 6 temp.setname( Yoda ); What are the names of the Jedi objects of council[0], council[1], and temp after line 6? Draw a diagram to support your answer. The names are all Yoda since all three point to the same object. 7
(b) (5 points) Given the following methd, what are the values of x[0] and x[1] after line 4? Show your trace and provide justifications. public static int change(int[] x, int y) { x[0] = x[0]*y; y = x[0]*y; x[1] = x[1]*y; return y; 1 int x[] = new int[10]; 2 x[0] = 1; 3 x[1] = 2; 4 x[1] = change(x,x[1]); The array x is passed in by reference while the integer x[0] is passed in by value to the method. x[0] is assigned 1* 2 = 2. The local variable y is assigned 2*2 = 4. x[1] is assigned 2*4 = 8. The local value of y ( = 4) is returned and stored in x[1] = 4. So, x[0] is 2 and x[1] is changed to 4. (c) (5 points) Given the following list of numbers: 5 9 2 10 1 3 8 7 2 6 What does the list look like after three passes of Bubble Sort (assuming that we sort the list in ascending order)? After first pass: 5 2 9 1 3 8 7 2 6 10 After second pass: 2 5 1 3 8 7 2 6 9 10 8
After third pass: 2 1 3 5 7 2 6 8 9 10 (d) (5 points) What is the difference between a regular Java class and an interface class in Java when we as client programmers use them? An interface class consists of only abstract methods and does not have any data members. To use an interface class, one will need to implement the abstract methods and use the following: class MyClass implements InterfaceClass { To use a regular class, one usually extends the class by: class MyClass extends RegularClass { 9