solution - queen's...

24
HAND IN Answers Are Recorded on Exam Paper QUEEN'S UNIVERSITY SCHOOL OF COMPUTING CMPE212, WINTER TERM, 2016 FINAL EXAMINATION 9am to 12pm, 19 APRIL 2016 Instructor: Alan McLeod If the instructor is unavailable in the examination room and if doubt exists as to the interpretation of any problem, the candidate is urged to submit with the answer paper a clear statement of any assumptions made. Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written. Please write your answers in the boxes provided. Extra space is available on the last page of the exam. The back of any page can be used for rough work. This exam is three hours long and refers exclusively to the use of the Java language. Comments are not required in the code you write. For full marks, code must be efficient as well as correct. This is a closed book exam. No computers or calculators are allowed. Problem 1: / 40 Problem 4: / 10 Problem 2: / 20 Problem 5: / 10 Problem 3: / 10 Problem 6: / 50 TOTAL: / 140 This material is copyrighted and is for the sole use of students registered in CMPE212 and writing this exam. This material shall not be distributed or disseminated. Failure to abide by these conditions is a breach of copyright and may also constitute a breach of academic integrity under the University Senate's Academic Integrity Policy Statement. Student Number: SOLUTION

Upload: others

Post on 09-Jun-2020

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

HAND IN Answers Are Recorded on Exam Paper

QUEEN'S UNIVERSITY SCHOOL OF COMPUTING CMPE212, WINTER TERM, 2016 FINAL EXAMINATION 9am to 12pm, 19 APRIL 2016 Instructor: Alan McLeod If the instructor is unavailable in the examination room and if doubt exists as to the interpretation of any problem, the candidate is urged to submit with the answer paper a clear statement of any assumptions made. Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written. Please write your answers in the boxes provided. Extra space is available on the last page of the exam. The back of any page can be used for rough work. This exam is three hours long and refers exclusively to the use of the Java language. Comments are not required in the code you write. For full marks, code must be efficient as well as correct. This is a closed book exam. No computers or calculators are allowed. Problem 1: / 40 Problem 4: / 10 Problem 2: / 20 Problem 5: / 10 Problem 3: / 10 Problem 6: / 50

TOTAL: / 140

This material is copyrighted and is for the sole use of students registered in CMPE212 and writing this exam. This

material shall not be distributed or disseminated. Failure to abide by these conditions is a breach of copyright and may also constitute a breach of academic integrity under the University Senate's Academic Integrity Policy Statement.

Student Number: SOLUTION

Page 2: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 2 of 24 Problem 1) [40 marks] Indicate if each of the following statements is True or False by writing a “T” or “F” on the line before the statement: ____ Proper object encapsulation is based on having attributes declared as private. ____ The implements keyword is used to create a child class from a parent class. ____ The first line of code in the constructor of a child class must be a call to the constructor of

the parent class. ____ An immutable class has a mutator for each attribute. ____ An attribute of type String must be cloned by its accessor to avoid a privacy leak. ____ The keyword “this” can be used to access the immediate parent object from within the child

object. ____ A fully concrete child class must implement all abstract methods inherited from an abstract

parent class. ____ An interface can contain final static attributes. ____ An object can be declared to be of an interface type. ____ An abstract class can be instantiated. ____ It is not possible to overload constructors. ____ Only constructors can throw exceptions. ____ The throws decoration is used in a class declaration to indicate that the class contains

methods that throw exceptions. ____ A constructor must be invoked during instantiation. ____ Java automatically provides a default constructor for a class that does not have its own

constructor.

T

T

T

T

T

T

T

F

F

F

F

F

F

F

F

Page 3: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 3 of 24 Problem 1, Cont.) ____ It is possible to define a class within another class. ____ An outer class can only invoke non-static inner class methods from an instance of that inner

class. ____ A child class instance can be assigned to a pointer of a parent class type. ____ Object is the base class for all classes in the Java API. ____ “Late binding” is another name for the process of polymorphism. ____ “Early binding” must be satisfied for the process of polymorphism to take place. ____ Only attributes can be declared outside a class definition. ____ In JavaFX, the root Pane class does not have a built-in layout manager algorithm. It can

only use absolute layout positions. ____ The StackPane class is used to place nodes in a grid layout. ____ When using a GridPane, nodes can be added to any row, column position in any order. ____ Visible grid lines can be used to help with layout when using a GridPane. ____ By default, a GridPane column is set to be as wide as the widest node in that column. ____ It is not possible to make a GridPane row any taller than the tallest node in that row. ____ The relative positions of nodes within an HBox pane can change if the pane size changes. ____ The relative positions of nodes within a TilePane can change if the pane size changes.

T

T

T

T

T

T

T

T

T

T

T

F

F

F

F

Page 4: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 4 of 24 Problem 1, Cont.) ____ A *.css file or “stylesheet” can be used to change the appearance of individual nodes, all

nodes of a certain type or all nodes in a JavaFX window. ____ Only one node can be the root node for a Scene object. ____ All nodes must be added directly to the Stage object so that they can be seen. ____ A JavaFX window is modal by default. ____ An event handler to listen for a mouse click event can implement the

EventHandler<ActionEvent> interface. ____ The EventHandler<ActionEvent> interface is a “functional interface”. ____ The “root” node is typically a Pane object. ____ A Button’s .setOnAction() mutator can be used to attach an event handler to the button. ____ It is not possible to use a Lambda function to define an event handler. ____ A Lambda function can only contain a single line of code. ____ A Lambda function can only be written for methods defined in a functional interface that

accept a single argument. ____ Settings made in the stylesheet will override any appearance settings made in the *.fxml file

in the same JavaFX project. ____ The *.fxml file must know the name and folder location of the controller *.java file that it is

supposed to work with. ____ Nodes must be instantiated in the controller *.java file rather than in the *.fxml file that it is

associated with. ____ The initialize() method in the controller *.java class is invoked only after all nodes have

been injected into the file.

T

T

T

T

T

T

T

T

T

F

F

F

F

F

F

Page 5: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 5 of 24 Problem 1, Cont.) ____ The @FXML annotation is used to specify methods and attributes in the controller class

that are not to be processed by the *.fxml file. ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It is not possible to change the graphic image used in a JavaFX dialog window. ____ Dialogs cannot be used to obtain text from the user. ____ Change listeners must be added to node properties rather than to the node itself. ____ A change listener added to a text field property can obtain the text in the field as it was

before it was changed by the user. ____ Change listeners can be used to detect changes to spinners and sliders. ____ Drawing methods can be invoked directly on an instance of a Canvas object. ____ The border colour of a filled oval can be different from its fill colour. ____ The (0, 0) pixel position in a Canvas object is the lower, left corner of the Canvas. ____ The Canvas object is not capable of displaying images loaded from files. ____ A Canvas object can interact with the cursor once an event handler has been added to the

Canvas. ____ A Transition animation can be used to animate several nodes at once. ____ A Timeline animation can only be constructed with a single KeyFrame object. ____ A Duration object must be supplied to the constructor of a KeyFrame object. ____ A Duration object is used to specify the time delay between KeyFrame objects.

T

T

T

T

T

T

T

T

T

F

F

F

F

F

F

F

Page 6: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 6 of 24 Problem 1, Cont.) ____ An AnimationTimer object can be used to create an event that will be triggered every time

the window’s frame is re-drawn. ____ An AnimationTimer object must be attached to a Timeline object. ____ A Timeline object is started as soon as it is instantiated. ____ A Timeline object cannot be halted until the application containing the object is closed. ____ KeyFrame objects can be used to trigger events when the KeyFrame has completed. ____ There is no point in designing an animation that updates at any rate higher than the monitor

refresh rate. ____ A loop that endlessly iterates until a second has passed and then re-starts can be added to

the Application thread in a JavaFX program without changing the responsiveness of the window.

____ A javafx.concurrent.Task object cannot access scenegraph nodes directly, but must bind

with their properties instead. ____ A Task object cannot be re-started. ____ A Task object is a generic class. ____ The implementation of a Task object requires you to override the call() method that returns

an object of type “T”. ____ A javafx.concurrent.Service object is used to manage a Task object. ____ A Service object cannot be re-started. ____ A Service object must be “wrapped” in a Thread object in order to be changed to a Daemon

thread. ____ Daemon threads are automatically halted before any user application threads are stopped. ____ There is no way to change the thread priority of a thread in a JavaFX program.

T

T

T

T

T

T

T

T

T

F F

F

F

F

F

F

Page 7: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 7 of 24 Problem 1, Cont.) ____ The Thread.sleep() method will not propagate a thread interrupt exception. ____ The Thread.yield() method is used to halt a thread’s execution. ____ I am really happy that this is the last true/false question! Problem 2) [20 marks]: Answer the following questions as briefly as possible: What is the underlying data structure used by an ArrayList<T> collection? What is the convenience obtained by a class when it implements the Comparable<T> interface? What is the reason for making non-final attributes private? What is the advantage to declaring class members static? What is a null pointer?

T or F

That object can be sorted by built-in sorting methods from the Java API such as Arrays.sort().

Private attributes cannot be changed directly from outside the object. If permitted at all, changes can only be made through mutator methods, which can check possible attribute values for legality.

F

F

Object[]

All instances of that class will share the same static member – they are not duplicated, making memory use more efficient.

A null pointer is a variable of an object type that has not been assigned to point to an instantiated object. It does not yet contain a memory address.

Page 8: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 8 of 24 Problem 2, Cont.) What does it mean to say that an exception is “propagated” after it is thrown? Name one advantage of using inheritance. Why is a try-with-resources block better than a normal try-catch block when used with File I/O? Which file format – binary or text – produces the most compact file for storing floating point numeric data and why? What is a Scene Graph as used in JavaFX?

If an exception is thrown but not caught inside the method in which it was thrown, the method will be halted and the exception will be propagated to the next method down on the call stack.

Resources in a try-with-resources block will be automatically closed as soon as the end of the try block is reached. No explicit .close() calls are required, which is good because they will not work well if the stream is already in an erroneous state.

Binary. Numbers are stored using the exact same bit pattern as used in RAM – 4 bytes for a float, 8 bytes for a double. To store numbers in a text file all digits would have to become text characters taking up at least one byte each.

Avoids code duplication. Enforces class structure on child classes. Allows the use of polymorphism.

A “Scene Graph” refers to the hierarchy of nodes that will be added to the root of a Scene object. A node is an individual control or container in a window.

Page 9: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 9 of 24 Problem 3) [10 marks] Provide the console window output of each of the following println statements. If you think the statement will cause an error, write “error” instead. System.out.println ( 15 / 2.0 ); ........................... System.out.println ( (double)( 7 / 2 ) ); .................. System.out.println ( 6 * ( 2 / 3 ) + 7 ); .................. System.out.println ( true && 1 ); .......................... System.out.println ( 6 * 2 / 3.0 + 7 ); .................... System.out.println ( 6 * 20 / ( 3 + 7 ) ); ................. System.out.println ( 5 > 2 || 3 <= 1 ); .................... System.out.println ( 2 ** 3 ); ............................. System.out.println ( 26 % 3 ); ............................. System.out.println ( 4 + 6 * 2 - 7 + 10 / 5 - 1 ); ......... System.out.println ( true && 9 != 7 ); ..................... System.out.println ("4" + 3 + 1); .......................... System.out.println (2 + 1 + "7" - 4); ...................... System.out.println ( 5 > 2 && 6 != 5 || 7 < 3 ); ........... System.out.println ( 6 + 7 <> 13 ); ........................ System.out.println ( 2.4 / (int) 1.2 ); .................... System.out.println ( (int) ( 9.6 / 2.0 ) ); ................ System.out.println ( 7 + 2 > 3 && 9 >= 2 + 2 + 2 ); ........ System.out.println ( Character.isDigit("123") ); ........... System.out.println ( Character.toLowerCase('B') ); .........

7.5

3.0

7

error

11.0

12

true

error

2

10

true

431

error

true

error

2.4

4

true

error

b

Page 10: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 10 of 24 Problem 4) [10 marks] Write the output of the following complete program, which runs without error, in the box provided:  public class Problem1 {  public static double  fiddle(int num1, int[] nums1, int[] nums2, String str) {   str = str.toLowerCase();   int size = str.length();   String flipped = str.charAt(size ‐ 1) + str.substring(1, size ‐ 1) +            str.charAt(0);   System.out.println(flipped);   num1 = size;   for (int num : nums1)     num *= 10;   System.out.println(nums1[0]);   double sum = 0;   for (int i = 0; i < nums2.length; i++) {     sum += nums2[i];     nums2[i] *= 10;   }   System.out.println(nums2[0]);   return sum; }  // Displays numbers on one line public static void showArray(int[] array) {   System.out.print("Array: ");   for (int num : array)     System.out.print(num + ", ");   System.out.println(); }  public static void main(String[] args) {   int[] array1 = {2, 3, 4, 5};   int[] array2 = {1, 2, 3, 4};   String aString = "Hello Class!";   int aNum = 20;   double aVal = fiddle(aNum, array1, array2, aString);   System.out.println(aNum);   showArray(array1);   showArray(array2);   System.out.println(aString);   System.out.println(aVal); }  } 

!ello classh 2 10 20 Array: 2, 3, 4, 5,  Array: 10, 20, 30, 40,  Hello Class! 10.0

Page 11: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 11 of 24 Problem 5) [10 marks] Here are a bunch of classes and an interface from the same Java project: public abstract class Base {    public int sum(int a, int b) {     return a + b;   }      public int multiply(int a, int b) {     return a * b;   }      public abstract int subtract(int a, int b);    } // end Base  interface Dividing {    int divide(int a, int b) throws DivideByZero;    } // end Dividing  public class DivideByZero extends Exception {    public DivideByZero(String message) {     super(message);   }    } // end DivideByZero  public class Concrete extends Missing {    public int multiply(int a, int b, int c) {     return a * b * c;   }    } // end Concrete 

 There are two more classes in this project. The one on the next page contains a main method that tests the other classes:    

Page 12: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 12 of 24 Problem 5, Cont.)  public class Demonstration {    public static int remainder(int a, int b) {     return a % b;   }      public static void main(String[] args) {      Concrete test = new Concrete();      // Prints:     System.out.println(test.sum(4, 5));    // 9     System.out.println(test.sum(4, 5, 6));   // 15     System.out.println(remainder(12, 5));   // 2     System.out.println(test.multiply(4, 5));  // 20     System.out.println(test.multiply(3, 4, 5)); // 60     System.out.println(test.subtract(4, 5));  // ‐1          try {       System.out.println(test.divide(10, 0));     

} catch (DivideByZero e) {       System.out.println(e.getMessage()); //Attempt to divide by 0!     }     try {       System.out.println(test.divide(10, 2)); // 5     } catch (DivideByZero e) {       System.out.println(e.getMessage());     }     try {       Dividing dTest = new Missing();       System.out.println(dTest.divide(15, 2)); // 7     } catch (DivideByZero e) {       System.out.println(e.getMessage());     }        } // end main  } // end Demonstration  As you can see the listing shown above contains the output of the program when run as in-line comments. One class is Missing. The Missing class extends one class and implements an interface. Write the Missing class on the next page:

Page 13: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 13 of 24 Problem 5, Cont.) public class Missing extends Base implements Dividing {      public int subtract(int a, int b) {     return a ‐ b;   }      public int divide(int a, int b) throws DivideByZero {     if (b == 0)       throw new DivideByZero("Attempt to divide by zero!");     return a / b;   }      public int sum(int a, int b, int c) {     return a + b + c;   }  }

Page 14: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 14 of 24 Problem 6) [50 marks] For this problem you are going to write a properly encapsulated class call “CallLog” that is designed to hold data for a call centre’s single phone call response. Start below by writing an exception class called “LogException” that will be used by the CallLog class: Write the LogException class below: public class LogException extends Exception {    public LogException(String message) {     super(message);   } }  The CallLog class encapsulates the following attributes:

The operator’s name. Must contain at least one space and be at least three characters in length.

The month for the call. An int that must lie between 1 and 12 inclusive. The day for the call. An int that must lie between 1 and 31 inclusive. The start time for the call as an int in the form hhmm, where hh is the hour that must be

between 08 and 20 (8am to 8pm) and mm is the minute that must lie between 00 and 59. The finish time for the call in the same form as the start time. The finish time must be later

than or the same as the start time. If an attempt is made to instantiate or mutate a CallLog instance with illegal arguments, the constructor or mutator being used must throw the LogException exception with an appropriate message. The CallLog class has one constructor that accepts arguments for all parameters and a second constructor that does not need the finish time, but assumes that the finish time is the same as the start time. Write a mutator for each attribute.

2 marks

Page 15: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 15 of 24 Problem 6, Cont.) You can write as many accessors as you need, but at a minimum you must have accessors for the name, the month and the day. As you continue to work on this problem you may find that additional accessors will help simplify your code. You also need to write the other four standard methods: compareTo, equals, toString and clone. Comparison using compareTo is based just on the full starting time of the call. This means a time that consists of the month, the day and the starting time of the call. You will see examples of the use of this method later in the description of this problem. Equality is defined as the name, the month, the day and the starting time all being equal. You must override the equals method inherited from the Object class. You will see examples of the output of the toString method later on in this description. The clone method must return a deep copy of the current CallLog object. All string comparisons in this problem can be assumed to be case sensitive. You can use the String methods .equals(otherString) which returns a boolean and .compareTo(otherString) which returns a negative number if the supplied string comes after the current string (the one used to invoke the method) in the alphabet, zero if they are equal and a positive number if the supplied string comes before the current string. Start writing the CallLog class below and continue on the next five pages. Note that this problem continues after these five blank pages and that output examples are provided at the end of the problem statement. The CallLog class: public class CallLog implements Comparable<CallLog> {    private String name;   private int month;   private int day;   private int startTime;   private int finishTime; 

32 marks

Page 16: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 16 of 24 Problem 6, Cont.) The CallLog class, Cont.: public CallLog(String name, int month, int day, int start, int finish)        throws LogException {     setName(name);     setMonth(month);     setDay(day);     setStart(start);     setFinish(finish);     if (finish < start)     throw new LogException("Start time must be before finish time.");   }      public CallLog(String name, int month, int day, int start)        throws LogException {     this(name, month, day, start, start);   }    public void setName(String name) throws LogException {     if (name.length() > 2 && name.contains(" "))       this.name = name;     else       throw new LogException("Illegal name.");   }   public void setMonth(int month) throws LogException {     if (month > 0 && month < 13)       this.month = month;     else       throw new LogException("Illegal month.");   }   public void setDay(int day) throws LogException {     if (day > 0 && day < 32)       this.day = day;     else       throw new LogException("Illegal day.");   }   private int extractMinutes(int time) {     return time ‐ 100 * (time / 100);   }   public void setStart(int start) throws LogException {     if (start >= 800 && start <= 2000 && extractMinutes(start) < 60)       startTime = start;     else       throw new LogException("Illegal start time.");   }  

Page 17: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 17 of 24 Problem 6, Cont.) The CallLog class, Cont.: public void setFinish(int finish) throws LogException {     if (finish >= 800 && finish <= 2000 && extractMinutes(finish) < 60)       finishTime = finish;     else       throw new LogException("Illegal finish time.");   }      public String getName() { return name; }      public int getMonth() { return month; }      public int getDay() { return day; }    public int getDuration() {     int hours = finishTime / 100 ‐ startTime / 100;     int minutes = extractMinutes(finishTime) ‐ extractMinutes(startTime);     int duration = hours * 60 + minutes;     if (duration == 0)       return 1;     else       return duration;   }      // Must be public if use Lambda function for Comparator<T>   public int getFullTime() {     return (month * 100 + day) * 10000 + startTime;   }      public static int compareToWithName(CallLog left, CallLog right) {     int nameCompare = left.name.compareTo(right.name);     if (nameCompare == 0)       return left.getFullTime() ‐ right.getFullTime();     else       return nameCompare;       }      public int compareTo(CallLog other) {     return getFullTime() ‐ other.getFullTime();   }  

Page 18: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 18 of 24 Problem 6, Cont.) The CallLog class, Cont.:   public boolean equals(Object other) {     if (other instanceof CallLog) {       CallLog oLog = (CallLog)other;       return oLog.name.equals(name) &&            oLog.getFullTime() == getFullTime();     }     return false;   }      public CallLog clone() {     CallLog out = null;     try {       out = new CallLog(name, month, day, startTime, finishTime);     } catch (LogException e) {       // empty     }     return out;   }      public String toString() {     return "Call log for " + name + " on month " + month + ", day " +              day + ", starting at " + startTime + ", finishing at " + finishTime;   }    }

Page 19: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 19 of 24 Problem 6, Cont.) The CallLog class, Cont.:

Page 20: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 20 of 24 Problem 6, Cont.) The CallLog class, Cont.:

Page 21: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 21 of 24 Problem 6, Cont.) Imagine, but do not write (!), another class containing static methods that is using the CallLog object you have just completed. Also, imagine that there are other CallLog child type objects that extend your CallLog class that are designed to hold other pieces of information in addition to the ones you encapsulated above. In the box below, write a static method for inclusion in this class called “totalCallTime” that accepts as arguments:

An ArrayList collection of objects of type CallLog or of any object that extends CallLog, An operator’s name, A month as an int between 1 and 12, and A day as an int between 1 and 31.

This method searches the supplied collection for all objects that have been created for the operator name supplied and for the supplied month and day. It then sums up and returns the total time in minutes for all calls that match the search criteria. If a call has the same finish time as the start time, assume a one minute duration for this call. Write just the totalCallTime method below. You may add accessor(s) to the CallLog class above in order to support the work of the totalCallTime method if you wish. The totalCallTime method: public static int totalCallTime(ArrayList<? extends CallLog> list,      String name, int month, int day) {   int sum = 0;   for (CallLog item : list)     if (item.getName().equals(name) &&       item.getMonth() == month && item.getDay() == day)       sum += item.getDuration();   return sum; } 

6 marks

Page 22: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 22 of 24 Problem 6, Cont.) Without all the javadoc comments the Comparable<T> interface from the Java API is: package java.lang; public interface Comparable<T> {     public int compareTo(T o); } 

And the relevant part of the Comparator<T> interface is: package java.util; @FunctionalInterface public interface Comparator<T> {     int compare(T o1, T o2); } The ArrayList.sort() method accepts a Comparator object that can be used to specify the sort criteria to be used by this method. Write a line of code to be included in some method in this other class that will sort an array list called logList that is of type ArrayList<CallLog> using the ArrayList.sort() method. Note that if you supply null to the .sort() method it sorts using the “natural ordering” of the objects contained in the ArrayList.     logList.sort(null);  Write another line of code that uses the ArrayList .sort() method with a Comparator object that changes the ordering to sort first by name then by time. Modify your CallLog class if you wish.   logList.sort(CallLog::compareToWithName);  or   logList.sort((CallLog left, CallLog right) ‐>   {     int nameCompare = left.getName().compareTo(right.getName());     if (nameCompare == 0)       return left.getFullTime() ‐ right.getFullTime();     else       return nameCompare;             }); 

1 mark

9 marks

Page 23: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 23 of 24 Problem 6, Cont.) For example, here is the output generated by the code:

logList.forEach(item ‐> System.out.println(item)) 

for some test data in the same order as it was added to the ArrayList “logList”: Call log for Joe Keen on month 2, day 12, starting at 1005, finishing at 1010 Call log for Joe Keen on month 1, day 28, starting at 1005, finishing at 1010 Call log for Joe Keen on month 2, day 12, starting at 905, finishing at 912 Call log for Joe Keen on month 2, day 12, starting at 1407, finishing at 1410 Call log for Joe Keen on month 2, day 12, starting at 1225, finishing at 1227 Call log for Joe Keen on month 2, day 12, starting at 1358, finishing at 1405 Call log for Sue Keen on month 2, day 12, starting at 1005, finishing at 1010 Call log for Joe Keen on month 7, day 12, starting at 1005, finishing at 1010 Call log for Joe Keen on month 2, day 12, starting at 1005, finishing at 1005 Call log for Joe Keen on month 2, day 9, starting at 1105, finishing at 1110 Call log for Joe Keen on month 2, day 14, starting at 1005, finishing at 1010 Call log for Amy Keen on month 2, day 12, starting at 1005, finishing at 1010 The totalCallTime method, if invoked for “Joe Keen”, month 2 and day 12, would return the value of 25 minutes. After sorting using “natural ordering”, logList would look like: Call log for Joe Keen on month 1, day 28, starting at 1005, finishing at 1010 Call log for Joe Keen on month 2, day 9, starting at 1105, finishing at 1110 Call log for Joe Keen on month 2, day 12, starting at 905, finishing at 912 Call log for Joe Keen on month 2, day 12, starting at 1005, finishing at 1010 Call log for Sue Keen on month 2, day 12, starting at 1005, finishing at 1010 Call log for Joe Keen on month 2, day 12, starting at 1005, finishing at 1005 Call log for Amy Keen on month 2, day 12, starting at 1005, finishing at 1010 Call log for Joe Keen on month 2, day 12, starting at 1225, finishing at 1227 Call log for Joe Keen on month 2, day 12, starting at 1358, finishing at 1405 Call log for Joe Keen on month 2, day 12, starting at 1407, finishing at 1410 Call log for Joe Keen on month 2, day 14, starting at 1005, finishing at 1010 Call log for Joe Keen on month 7, day 12, starting at 1005, finishing at 1010 After sorting with the new Comparator object: Call log for Amy Keen on month 2, day 12, starting at 1005, finishing at 1010 Call log for Joe Keen on month 1, day 28, starting at 1005, finishing at 1010 Call log for Joe Keen on month 2, day 9, starting at 1105, finishing at 1110 Call log for Joe Keen on month 2, day 12, starting at 905, finishing at 912 Call log for Joe Keen on month 2, day 12, starting at 1005, finishing at 1010 Call log for Joe Keen on month 2, day 12, starting at 1005, finishing at 1005 Call log for Joe Keen on month 2, day 12, starting at 1225, finishing at 1227 Call log for Joe Keen on month 2, day 12, starting at 1358, finishing at 1405 Call log for Joe Keen on month 2, day 12, starting at 1407, finishing at 1410 Call log for Joe Keen on month 2, day 14, starting at 1005, finishing at 1010 Call log for Joe Keen on month 7, day 12, starting at 1005, finishing at 1010 Call log for Sue Keen on month 2, day 12, starting at 1005, finishing at 1010

Page 24: SOLUTION - Queen's Universityresearch.cs.queensu.ca/.../Winter2020/CMPE212Final2016WinterSol… · ____ By default, built-in JavaFX dialog windows are modal in behaviour. ____ It

Student Number: ____________________ Page 24 of 24

Extra Page