RAIK 183H Examination 2 Solution. November 11, 2013

Similar documents
RAIK 183H Examination 2 Solution. November 10, 2014

MIT AITI Swing Event Model Lecture 17

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

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

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

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

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

Swing from A to Z Some Simple Components. Preface

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

SINGLE EVENT HANDLING

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

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

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

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

1 Looping Constructs (4 minutes, 2 points)

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

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

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

Introduction. Introduction

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

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

Midterm assessment - MAKEUP Fall 2010

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

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

Programming Language Concepts: Lecture 8

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

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

CMP 326 Midterm Fall 2015

GUI Forms and Events, Part II

Graphical Interfaces

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

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

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

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

CS180 Recitation. More about Objects and Methods

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

Graphical Interfaces

We are on the GUI fast track path

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

AP CS Unit 11: Graphics and Events

CS Exam 3 - Spring 2010

CS 113 MIDTERM EXAM 2 SPRING 2013

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

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

CSIS 10A Assignment 7 SOLUTIONS

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

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

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

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

CS Exam 3 - Spring 2010

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

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

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

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

SampleApp.java. Page 1

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords

Final Exam CS 251, Intermediate Programming December 10, 2014

Attempt FOUR questions Marking Scheme Time: 120 mins

CS 113 PRACTICE FINAL

University of Cape Town Department of Computer Science Computer Science CSC1017F

Window Interfaces Using Swing Objects

CS108, Stanford Handout #22. Thread 3 GUI

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

COMP16121 Notes on Mock Exam Questions

Name: Username: I. 20. Section: II. p p p III. p p p p Total 100. CMSC 202 Section 06 Fall 2015

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

Introduction to the JAVA UI classes Advanced HCI IAT351

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

CSE 2123: Collections: Priority Queues. Jeremy Morris

CSci 1103 Final. Name: Student ID:

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

Points Missed on Page page 1 of 8

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

CS211 GUI Dynamics. Announcements. Motivation/Overview. Example Revisted

EXCEPTIONS & GUI. Errors are signals that things are beyond help. Review Session for. -Ankur Agarwal

Final Examination Semester 3 / Year 2008

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

CSE wi Final Exam 3/12/18. Name UW ID#

University of Palestine. Mid Exam Total Grade: 100

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

Fundamentals of Object Oriented Programming

Original GUIs. IntroGUI 1

What Is an Event? Some event handler. ActionEvent. actionperformed(actionevent e) { }

CMP-326 Exam 2 Spring 2018 Total 120 Points Version 1

Class 27: Nested Classes and an Introduction to Trees

Swing - JTextField. Adding a text field to the main window (with tooltips and all)

Final Examination Semester 2 / Year 2012

Advanced Java Unit 6: Review of Graphics and Events

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

COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) )

Largest Online Community of VU Students

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

University of Cape Town Department of Computer Science. Computer Science CSC117F Solutions

1.00/1.001 Introduction to Computers and Engineering Problem Solving. Quiz 2: April 16, 2004

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 2: April 16, 2004

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

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

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

Transcription:

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