Very brief answers to Final Jeopardy Last CS111 Lecture May 5, 2011 Arrays 1. A.length 2. (1) all elements accessed with same efficency (2) slots are mutable 3. boolean tmp = B[0]; B[0] = B[B.length-1]; B[B.length-1] = tmp; 4. public static String concatAll(String [] a) { String ans=""; for (int i = 0; i < a.length; i++) { ans = ans+a[i]; } return ans; } 5. // build up the list from the last elt, to preserve order public static IntList intArrayToList(int [] a) { IntList ans=empty(); for (int i = a.length-1; i >= 0; i--) { ans = prepend(a[i],ans); } return ans; } ----------------------------------- Objects 1. instance variables 2. static 3. methods: 1) instance 2) class 3) constructor variables: 1) instance 2) class 4. animation In console window: 42 18 6 5. Counter: c = 1; i = 1 c = 1; i = 2; c = 2; i = 1; c = 2; i = 3; ----------------------------------- Iteration/Recursion 1. tail 2. int i = 0; while (i< a.length) { s[i] = a[i]+b[i]; i++; } 3. public static int sumLengths(StringList strs) { if (isEmpty(strs)) return 0; else return (head(strs)).length() + sumLengths(tail(strs)); } 4. public static StringList dropPlurals (StringList L) { if (isEmpty(L)) return L; else { // decide if word is plural or not int foundS = head(L).indexOf("s"); if (foundS == head(L).length()-1) // found a plural return dropPlurals(tail(L)); else return prepend(head(L), dropPlurals(tail(L))); } } 5. public int countLines(String fileName) throws IOException { Scanner reader = new Scanner (new File(fileName)); int lines = 0; while (reader.hasNextLine()) { lines++; } reader.close(); return lines; } ----------------------------------- Lists 1. tail 2. can extend size (essential for recursive methods) 3. [4, 10, 8] 4. resulting list: [1, 2, 3, 2, 3, 3] 5. public static int digitsToInt(StringList ds) { if (isEmpty(ds)) return 0; else return Integer.parseInt(head(ds)) + (10* digitsToInt(tail(ds))); } ----------------------------------- Bugs that bite 1. i<= a.length causes error, referencing a cell that does not exist 2. missing return if len <=0 3. assumes a 2-item list, with singleton list, isSorted([2]) causes error with head(tail(l)) 4. (a) Constructor method shouldn't have return type void. (b) Point constructor method must be invoked with new. (c) In Circle constructor, center variable is redeclared. (d) radius = radius should be ``this.radius = radius''. 5. (a) need to move (i >= 0) before (n > a[i]) (b) need to return (i >= 0) && (n == a[i]) (c) (a third bug) without above changes, doesn't work for empty array. ----------------------------------- Potpourri 1. glue 2. this 3. args[2] 4. see drawing.gif (black lines not part of drawing, are coordinates 0-80 0-80 for reference 5. (a && (b || !c)) || (!a && d) OR a ? (b || !c) : d