RAIK 183H Examination 2 Solution. November 10, 2014

Similar documents
RAIK 183H Examination 2 Solution. November 11, 2013

CSCI 136 Written Exam #2 Fundamentals of Computer Science II Spring 2012

SE1021 Exam 2. When returning your exam, place your note-sheet on top. Page 1: This cover. Page 2 (Multiple choice): 10pts

H212 Introduction to Software Systems Honors

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

MIT AITI Swing Event Model Lecture 17

Name Section Number. CS210 Exam #3 *** PLEASE TURN OFF ALL CELL PHONES*** Practice

1.00/1.001 Introduction to Computers and Engineering Problem Solving Final Examination - December 15, 2003

Queens College, CUNY Department of Computer Science. CS 212 Object-Oriented Programming in Java Practice Exam 2. CS 212 Exam 2 Study Guide

Swing from A to Z Some Simple Components. Preface

Review sheet for Final Exam (List of objectives for this course)

CSE331 Fall 2014, Final Examination December 9, 2014 Please do not turn the page until 2:30. Rules:

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

Introduction This assignment will ask that you write a simple graphical user interface (GUI).

Midterm Test II Object Oriented Programming in Java Computer Science, University of Windsor Fall 2014 Time 2 hours. Answer all questions

COMP Assignment #10 (Due: Monday, March 11:30pm)

Midterm assessment - MAKEUP Fall 2010

1.00/1.001 Introduction to Computers and Engineering Problem Solving Final Examination - December 15, 2003

1 Looping Constructs (4 minutes, 2 points)

Graphical User Interface (Part-1) Supplementary Material for CPSC 233

CS180 Recitation. More about Objects and Methods

We are on the GUI fast track path

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

SINGLE EVENT HANDLING

CMP 326 Midterm Fall 2015

First Name: AITI 2004: Exam 2 July 19, 2004

DEMYSTIFYING PROGRAMMING: CHAPTER SIX METHODS (TOC DETAILED) CHAPTER SIX: METHODS 1

First Name: AITI 2004: Exam 2 July 19, 2004

Java Help Files. by Peter Lavin. May 22, 2004

Programming Language Concepts: Lecture 8

Systems Programming. Bachelor in Telecommunication Technology Engineering Bachelor in Communication System Engineering Carlos III University of Madrid

CS180 Spring 2010 Exam 2 Solutions, 29 March, 2010 Prof. Chris Clifton

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Graphical Interfaces

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

CS 180 Final Exam Review 12/(11, 12)/08

JRadioButton account_type_radio_button2 = new JRadioButton("Current"); ButtonGroup account_type_button_group = new ButtonGroup();

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:

Name: Checked: Learn about listeners, events, and simple animation for interactive graphical user interfaces.

Queen s University Faculty of Arts and Science School of Computing CISC 124 Final Examination December 2004 Instructor: M. Lamb

Graphical Interfaces

University of Cape Town Department of Computer Science Computer Science CSC1017F

Introduction to Programming Using Java (98-388)

AP CS Unit 11: Graphics and Events

GUI Forms and Events, Part II

CS Exam 3 - Spring 2010

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

Introduction. Introduction

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

CS108, Stanford Handout #22. Thread 3 GUI

CS 113 MIDTERM EXAM 2 SPRING 2013

Introduction to the JAVA UI classes Advanced HCI IAT351

University of Cape Town ~ Department of Computer Science. Computer Science 1016S / 1011H ~ November Exam

Points Missed on Page page 1 of 8

CS 113 PRACTICE FINAL

CS Exam 3 - Spring 2010

Final Exam CS 251, Intermediate Programming December 13, 2017

Advanced Java Unit 6: Review of Graphics and Events

CSCI 136 Written Exam #2 Fundamentals of Computer Science II Spring 2015

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Name: CSC143 Exam 1 1 CSC 143. Exam 1. Write also your name in the appropriate box of the scantron

CSE 332 Autumn 2013: Midterm Exam (closed book, closed notes, no calculators)

University of Cape Town ~ Department of Computer Science. Computer Science 1016S / 1011H ~ January Exam

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

ANSWER KEY Exam 2 Computer Programming 230 Dr. St. John Lehman College City University of New York Thursday, 5 November 2009

Interfaces & Polymorphism part 2: Collections, Comparators, and More fun with Java graphics

CSE 2123: Collections: Priority Queues. Jeremy Morris

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

CSC Java Programming, Fall Java Data Types and Control Constructs

Theory Test 3A. University of Cape Town ~ Department of Computer Science. Computer Science 1016S ~ For Official Use

(a) Write the signature (visibility, name, parameters, types) of the method(s) required

Largest Online Community of VU Students

Final Exam CS 251, Intermediate Programming December 10, 2014

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

SampleApp.java. Page 1

More About Objects and Methods

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

Prelim 2. CS 2110, November 19, 2015, 7:30 PM Total. Sorting Invariants Max Score Grader

COMP16121 Notes on Mock Exam Questions

Final. Please write (printing clearly) the infonnation requested in the boxes at the top of this page.

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

CMP-326 Exam 2 Spring 2018 Solutions Question 1. Version 1. Version 2

Object-Oriented Programming: Revision. Revision / Graphics / Subversion. Ewan Klein. Inf1 :: 2008/09

Graphical User Interfaces 2

Fundamentals of Object Oriented Programming

1.00/1.001 Introduction to Computers and Engineering Problem Solving Fall (total 7 pages)

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

CS56 final (E03) W15, Phill Conrad, UC Santa Barbara Wednesday, 03/18/2015. Name: Umail umail.ucsb.edu. Circle one: 4pm 5pm 6pm

CS 11 java track: lecture 3

Final Examination Semester 2 / Year 2012

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Exceptions Handling Errors using Exceptions

PASS4TEST IT 인증시험덤프전문사이트

Transcription:

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