RAIK 183H Examination 2 Solution November 11, 2013 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? (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. Events captured are then passed to event handlers, which are methods that one 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. (10 points) Write Java application that displays the following. And, when a user clicks on the ClickMe button, the text I am clicked! is displayed. (Note: Please pay attention to syntax, including importing the correct Java packages.) import javax.swing.*; 2
import java.awt.*; import java.awt.event.*; public class OneButton extends JFrame implements ActionListener { private JButton button1; private JTextField field1; public OneButton() { setlayout(new FlowLayout()); button1 = new JButton("ClickMe"); button1.addactionlistener(this); add(button1); field1 = new JTextField("",10); add(field1); setsize(500,500); setvisible(true); public void actionperformed(actionevent e) { field1.settext("i am clicked!"); public static void main(string[] arg) { 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 { 3
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). (5 points) What is the difference between checked and unchecked exceptions? Also give one example of an unchecked exception. Checked exceptions are exceptions that are checked at compile time and thus client programmers must catch them when they implement their solution and unchecked exceptions are not. An unchecked exception is NullPointerException. 3. (20 points) Arrays. Suppose that the following has been created with all its constructors, setters, and getters built. 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 computeaverageforce() to the Council class that computes the average force of all its members and returns that value. public double computeaverageforce() { double sum = 0; double average; 4
for (int i = 0; i < nummemberssofar; i++) sum = sum + members[i].getforce(); if (nummemberssofar > 0) average = sum/(1.0*nummemberssofar); else average = -1; return average; // end method (6 points) Add a method identifystrongestmember() to the Council class that finds the member with the strongest force and returns the location of that member in the array. public int identifystrongestmember() { double max = 0; double maxindex = -1; for (int i = 0; i < nummemberssofar; i++) if (members[i].getforce() > max) { max = members[i].getforce(); maxindex = i; return maxindex; // end method (c) (8 points) Add a method expelstrongestmembers() to the Council class that finds the members with the strongest force, removes them from the Council, and updates all relevant data members accordingly. (Hint: Make use of your solutions in above) public void expelstrongestmembers() { int keyforce = identifystrongestmember().getforce(); if (keyforce >= 0) { int maxforce = members[keyforce].getforce(); for (int i = 0; i < nummemberssofar; i++) if (members[i].getforce() == maxforce) { // found one! for (int j = i; j < nummemberssofar-1; j++) members[j] = members[j+1]; // shift nummemberssofar--; // one fewer member UPDATE // end if found i--; // just in case 5
// end if keyforce // end method 4. (20 points) Sorting (15 points) Describe the heapsort algorithm clearly. (Include its two phases.) 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, 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: 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. (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). 6
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: int rainfall[] = new int[2]; rainfall[0] = 3; rainfall[1] = 2; Show how to swap the values of the two elements of the array. int temp = rainfall[0]; rainfall[0] = rainfall[1]; rainfall[1] = temp; (5 points) Given the following, 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; return y; 1 int x[] = new int[10]; 2 x[0] = 1; 3 x[1] = 2; 4 x[0] = 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 = 3. The local variable y is assigned 3 + 2 = 5. This value is returned and stored in x[0] = 5. So, x[0] = 5 and x[1] remains as 2. (c) (5 points) Given the following list of numbers: 5 9 10 10 1 3 8 7 2 6 What does the list look like after three passes of Selection Sort (assuming that we sort the list in ascending order)? 7
Using the maximum version: After first pass: 5 9 6 10 1 3 8 7 2 10 After second pass: 5 9 6 2 1 3 8 7 10 10 After third pass: 5 7 6 2 1 3 8 9 10 10 Using the minimum version: After first pass: 1 9 10 10 5 3 8 7 2 6 After second pass: 1 2 10 10 5 3 8 7 9 6 After third pass: 1 2 3 10 5 10 8 7 9 6 (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 { 8