aps101s_2009_exam

pdf

School

York University *

*We aren’t endorsed by this school

Course

2B

Subject

Computer Science

Date

Dec 6, 2023

Type

pdf

Pages

18

Uploaded by MinisterQuail2783

Report
UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING April-May 2009 FINAL EXAMS APS101H1 ~ Computer Programming Examiner: Yaroslav Riabinin Duration 2.5 hours Exam Type: B: (The JAVA API sheet attached as the last page) Calculator Type: 4 (None) . Student Number: Last (Family) Name(s): First (Given) Name(s): Do not turn this page until you have received the signal to start. (In the meantime, please fill out the identification section above, and read the instructions below carefully.) MARKING GUIDE This final examination consists of 6 questions on 18 pages (including this one). #1: /28 When you receive the signal to start, please make sure that your copy of the examination is complete. #2: ' /10 Do NOT detach any paper from the examination book. 43 30 Comments are not necessary except where we ask for them. 44 6 After you receive the signal to start, write your student number in the space provided at the bottom of every page. . #5: 124 - #6 /20 TOTAL.: /138 Good Luck! Student #: Pagel . CONT'D..
APS101H1 FINAL EXAMINATION April-May 2009 Question 1. [28 marks] Short Answer. Describe one advantage of using arrays: [l mark] Describe two disadvantages of arrays: [2 marks] 1) 2) What is the difference between this and super? [2 marks] What is the result of the following lines of code? (write “error” for any errors) [10 marks] > import java.util.*; > String Tokenizer st = new StringTokenizer("APS101, Final Exam:2009 ; Ap ril 27", ", ™); > st.countTokens() // RESULT: > StringTokenizer st2 = new StringTokenizer("LOL"); > st2.hasMoreTokens() // RESULT: > StringTokenizer st3 = new StringTokenizer("a, b, c, d, ¢, f,‘ g ht" "y > st3.nextToken() // RESULT: > st3.nextToken().length() // RESULT: > for (int i = 1; i <2; i++) {System.out.printin(st2.nextToken()); } // RESULT: > st2.countTokens() // RESULT: >st!=st3 //RESULT: > String s = ""; while(st3.hasMoreTokens()) { s = st3.nextToken() +s; } >s //RESULT: > for (inti=0;1<7;1+=2) { st.nextToken(); st.nextToken(); } // RESULT:. >st==st3 //RESULT: Student #: ' Page 2 of 18 , CONT'D...
APS101H1 FINAL EXAMINATION April-May 2009 Examine the following mystery method (hint: it has no compile errors!): [7 marks] public static void mystery1() { inti=0,j=3; for(i=0;i<5;i++) { // outer loop System.out.printin("Executing outer loop: " + i); while (j > i) { // middle loop j= for (int k = j; k < 6; k += 2) { // inner loop System.out.print("jis " +j+ ", kis" + k + ") } // end of inner loop Systei’n.out.println(); } // end of middle loop ji=3-i-1; } // end of outer loop System.out.printin("iis " + i+ ", jis " + i) What is the exact output that is produced by this method? Write it in the space below. Student #: Page 3 of 18 CONT'D...
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
APS101H1 FINAL EXAMINATION April-May 2009 Examine the following mystery method (hint: it also has no compile errors!): [6 marks] public static boolean mystery2(boolean[][] bArray) { for (int r =-1; r < bArray.length - 1; r++) { for (intc = 1; c < bArray[r+1].length; c++) { if (bArray[r+1][c] && bArray[r][c-1]) { C++; } else if ('bArray[r+1][c-1] |} bArray{r+11{c]) { return true || bArray[r+1]ic+1]; ) return false; Give nwo examples of an input array that would make this method return true. Give rwo examples of an input array that would make this method return false. Give rwo examples of an input array that would produce a run-time error in this method. Student #: Page 4 of 18 CONT'D...
APS101H1 FINAL EXAMINATION April-May 2009 1 ~~y Question 2. [10 marks] Exceptions. Part (a) [4 marks] Write a customized exception class called APS101ExamException, which has two constructors (and no other methods): one constructor with no parameters that produces a standard error message (“This exam is too hard!”); and another constructor with one String parameter for the error message. | Part (b) [6 marks] Examine the following code. Assume that there are no compile errors. int mark; try { mark = 85; if (mark > 90) { throw new Exception("Yikes!"); } else if (mark < 65) { throw new APS101ExamException(); What would be the output if mark = 917 } else { What is the output of this code? System.out.printin("Hello!"); } System.out.printin(*Goodbye."); } catch (APS101ExamException e) { System.out.printin(e.getMessage()); What would be the output if mark = 33? } catch (Exception e) { } System.out.printin("End of code."); Student #: _ Page 5 of 18. CONT'D...
APS5101H1 FINAL EXAMINATION April-May 2009 Question 3. [30 marks] The following is a different implementation of the Passport class that you wrote for Assignment 2. This time, an array is used to store the countries visited. Part (a) [2 marks] Complete the constructor. Do not add any more instance/static variables! public class Passport { private String name; /** The name of the passport owner. */ private String[][] visited; /** The countries visited by the owner of the passport. */ // The format of this variable is as follows: { {countryl, duration}, {country2, duration}, ...} /** A new passport with name n, and NO countries visited. Initialize both instance variables! */ public Passport(String n) { } // end of constructor Part (b) [28 marks] Complete the following 3 methods. Do not add any helper methods. /¥* Return the country that the owner of this passport has visited for the longest duration, or empty string ( countries, return the left-most country (i.e. the country that appears earliest in the array). */ ) if no countries have been visited; If there is a tie between two or more public String longestVisitedCountry() { //[6 marks] } // end of longestVisitedCountry method Student #4: Page 6 of 18 CONT'D...
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
© e - APS101H1 - FINAL EXAMINATION . April-May 2009 /** Add the new entry (country ¢ and duration d) to the the countries visited variable. Do this by increasing the size of the array by one and adding the new entry to the end. (hint: you should make a new array and copy the elements). Ex. begin with visited = { } ' addCountry("Canada", 3) -> { {"Canada", "3" ) addCountry("Germany", 10) - { {"Canada", "3"}, {"Germany", "10"} } However, just like in Assignment 2, there must be NO consecutive entries with the same country. If the previous entry has the same country, then the two entries must be merged and their durations added together to form one entry. */ public void addCountry(String c, int d) { //[12 marks) } // end of addCountry method Student #: Page 7 of 18 "CONT'D...
I\ APS101H1 FINAL EXAMINATION April-May 2009 /** Remove the country and duration at index i (starting from 0) from the array. Ex. visited = { {Canada, 5}, {Germany, 43}, {UK, 12} }. removeCountry(0) - { {Germany, 43}, {UK, 12} } Note that this decreases the size of the array by one. If the removal of an entry results in two consecutive entries with the same country, you must not perform the removal. Ex. visited = { {Canada, 5}, {Germany, 43}, {Canada, 8} } can’t remove entry at index I. Y ou should not make any assumptions about the validity of index i. Your program should never crash from an error. Return true if the removal is successful; return false otherwise. */ public boolean removeCountry(int i) { // [10 marks] }'// end of removeCountry method Student #: Page 8 of 18 CONT'D...
APS101H1 FINAL EXAMINATION April-May 2009 Question 4. [26 marks] Assume that the following 2 classes exist. public class Building { private int x; // x-coordinate private int y; // y-coordinate public Building{int r, int c) { this.x =r; -~ this.y = ¢; } public String location{() { return "(" + x4+ ", " +y+ ") } } public class House extends Building { ~ /** Number of people living in the house. */ private int numResidents; public House(int x, int y) { super(x, y); this.numResidents = 5; } public int getNumResidents() { return this.numResidents; } } Write a class called City, with the following specifications: Variable Type Variable Description Building(l[] The City is represented by a grid of buildings. Method Method Description The constructor for this City. It takes one String argument, of the form: XY xy)Z&Xy):Z ... (xy):Z”" where X and Y specify the size of the city grid, the (x,y) pairs are the coordinates of buildings in the City, and Z indicates the type of building that is in that location: either “B” for a general Building, or “H” for a City(String) House. Ex. “55(0,4):B (1,2):H (12,0):H (-1,2):B (0,4):H” You can assume that this format will always be preserved, but you should not make any assumptions about the validity of the x and y values. In case of duplicate coordinates, only add the first entry. If no building or house is specified at a particular coordinate, leave that location null. getGrid() Returns the representation of this City (as a Building[][}). . Returns the population (number of residents) of this City (as an int). The getPopulation() L. Gy number of people living in general Buildings should be counted as 10. Compare this City to the given City. Do this by dividing the population of each City by its size (number of elements on its 2D grid). If this value is compareTo(City) . . L o A , ) bigger for this City, returns 1. If this value is bigger for the given City, returns -1. If this value is the same for both Cities, returns 0 (as an int). Student #: CONT'D... Page 9 of 18
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
APS101H1 FINAL EXAMINATION April-May 2009 // beginning of City class Assume that all necessary import statements have been made. Student #: Page 10 of 18 CONT'D...
APS5101H1 . FINAL EXAMINATION April-May 2009 // end of City class Student #: , Page 11 of 18 ) CONT'D...
APS101H1 FINAL EXAMINATION April-May 2009 Question 5. [24 marks] The following program encrypts words and stores the result in a file. Part (a) [10 marks] Complete the encrypt method. You will be marked on correctness and code readability, so you must write comments within the method. The encryption algorithm works by swapping consecutive pairs of letters. (i.e. swap the Ist letter with the 2nd, the 3rd with the 4th, etc.). Note: if the word has an odd number of letters, you must move the last letter to the beginning, BEFORE doing the swapping, and ignore the 2nd last letter (i.e. don't swap it). Ex. | (even): "abed" -> "badc". Ex. 2 (odd): "abcde" > "aecbd". public static String encrypt(String word) { /** Return the encrypted version of the given word. */ } // end of encrypt method Student #: Page 12 of 18 CONT'D...
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
APS101H1 FINAL EXAMINATION C April-May 2009 Part (b) [14 marks] This question continues from Part (a). Write a main method that reads in any number of words from the command-line (i.e. java ProgramName word1 word2 word3 ...). (If no words are specified on the command-line, prompt the user to enter words from the keyboard this process should stop when the user enters “-17) Encrypt each word using the encrypt method from the previous part and store each result (encrypted String) on a new line in a file called “encrypted.txt”. Assume that all necessary import statements have been made. You should not catch any exceptions. Student #: Page 13 of 18 CONT'D...
APS101H1 FINAL EXAMINATION April-May 2009 Question 6. [20 marks] Sorting and Searching. Part (a) [16 marks] Recall the 4 sorting algorithms we implemented in lecture. Given the following list of integer elements, state how many comparisons and swaps it would take for each algorithm to sort the list in ascending order. int[] list = {0, 10, 8, -1, -2, 5, 6} Comparisons Swaps bubbleSort bubbleSort2 (improved) insertionSort selectionSort Part (b) [4 marks] Recall the binary search algorithm we implemented in lecture. Given the following code: Search.binarySearch(new int[]{1, 3, 4, 6, 9, 10}, 8) In total, how many iterations does the binary search algorithm go through? What is the value of the middle index during the 2nd iteration? Given the following code: Search.binarySeafch(new int[1{1, 3,4,5,6, 7,9, 10, 12}, 5) In total, how many iterations does the binary search algorithm go through? What is the value of the end index during the 2nd iteration? Student #: Page 14 of 18 . 'CONT'D...
APS101H1 FINAL EXAMINATION - April-May 2009 [Use the space below for rough work. This page will not be marked, unless you clearly indicate the part of your work that you want us to mark. Do NOT detach this page.] Student #: Page 15 of 18 : . CONT'D...
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
APS101H1 FINAL EXAMINATION . April-May 2009 [Use the space below for rough work. This page will not be marked, unless you clearly indicate the part of your work that you want us to mark. Do NOT detach this page.] Student #: Page 16 of 18 CONT'D...
APS101H1 FINAL EXAMINATION April-May 2009 [Use the space below for rough work. This page will not be marked, unless you clearly indicate the part of your work that you want us to mark. Do NOT detach this page.] ' Student#: Page 17 of 18 . CONTD...
APS101H1 FINAL EXAMINATION April-May 2009 Short Java APL descriplions (everylhing is public) Integer: . static int parselnt(String s) // = s’s value, as an int Double: static double parseDouble(String s) // = s's value, as a double string: String substring(int i, int j) // = the letters from i (inclusive) to j (non-inclusive) String substring(int i) // = the letters from i (inclusive) to the end int indexOf(String s) // = the index of s in this String; -1 if s is not a substring int indexOf(String s, int i) // = index of s after index i (inclusive); -1 if s not found int compareTo(String s) // < 0, = 0, or > 0 depending on whether this < s, =5, or > s. int length() // = the number of characters in this String boolean equals(String s) // = this String has the same contents as s StringTokenizer: StringTokenizer(String s) // Create a tokenizer for s with delimiters " \t\n\r\f" StringTokenizer(String s, String d) // Create a tokenizer for s with delimiters ind’ StringTokenizer(String s, String d, true) //delimiters are also considered as tokens. boolean hasMoreTokens() // = whether this string tokenizer has more tokens String nextToken() // = the next token in this tokenizer's string int countTokens() // = the number of remaining tokens in this tokenizer's string File: File(String pathname) // Create a File linked with a file named f BufferedReader: : BufferedReader(Reader in) // Create a reader reading from ’'in’ String readLine() // Return the next line in the BufferedReader, or null if at end FileReader: FileReader(String f) // Create a Reader reading from a file named f FileReader(File f) // Create a Reader reading from a file f InputStreamReader: InputStreamReader(InputStream in) // Create a Reader reading from in FileOutputStream: (a subclass of OutputStream) FileOutputStream(File f) // Create an OutputStream writing to f FileOutputStream(String fn) // Create an OutputStream writing to a file named fn PrintStream: PrintStream(OutputStream out) // Create a print stream sending output to out print(String s) // Print s to the output printin(String s) // similar to above plus it terminates the line print(int i) // Print i to the output (similar methods exist for all primitive types) printIn(int i) // similar to above plus it terminates the line printin() // terminate the line System: static InputStream in // input from the keyboard _static PrintStream out // standard output stream Math: ) static double abs(double a) // = the absolute value of a * static double min(double a, double b) // = minimum of a and b static double max(double a, double b) // = maximum of a and b Stud_ent #: Page 18 of 18 END OF EXAMINATION
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help