Solution to CSE142 Final handout #28 1. Expression Value --------------------------------------------------- 12/5 + 8/4 4 2.5 * 2 + 17/4 9.0 41 % 15 % 7 + 17 % 3 6 21/2 + "7 % 3" + 17 % 4 "107 % 31" 46/3/2.0/3 * 4/5 2.0 2. Original List Final List -------------------------------------------------------------- () () (7) (0) (3, 2) (0, 2) (5, 4, 3) (0, 4, 6) (2, 4, 6, 8) (0, 4, 12, 24) 3. Polymorphism. The output produced is as follows. b c 1 a 2 b c 1 b 2 c c 1 c 2 b d 1 b 2 4. Token-Based File Processing. One possible solution appears below. public static void printStrings(Scanner input) { while (input.hasNextInt()) { int times = input.nextInt(); String word = input.next(); for (int i = 0; i < times; i++) System.out.print(word); System.out.println(); } } 5. Line-Based File Processing. One possible solution appears below. public static void reverseLines(Scanner input) { while (input.hasNextLine()) { String text = input.nextLine(); for (int i = text.length() - 1; i >= 0; i--) System.out.print(text.charAt(i)); System.out.println(); } } 6. Arrays. One possible solution appears below. public static boolean isAllEven(int[] list) { for (int i = 0; i < list.length; i++) if (list[i] % 2 != 0) return false; return true; } 7. ArrayLists. One possible solution appears below. public static void removeShorterStrings(ArrayList list) { for (int i = 0; i < list.size() - 1; i++) { String first = (String)list.get(i); String second = (String)list.get(i + 1); if (first.length() <= second.length()) list.remove(i); else list.remove(i + 1); } } 8. Critters. One possible solution appears below. public class Pigeon implements Critter { private int count; private int max; public char getChar() { return 'P'; } public int getMove(int x, int y) { if (this.count == 2 * this.max) { this.count = 0; double n = Math.random(); if (n < 0.25) this.max = 2; else if (n < 0.5) this.max = 4; else if (n < 0.75) this.max = 6; else // n > 0.75 this.max = 8; } this.count++; if (this.count <= this.max) return SOUTH; else return NORTH; } } 9. Arrays. One possible solution appears below. public static boolean isUnique(int[] list) { for (int i = 0; i < list.length; i++) for (int j = i + 1; j < list.length; j++) if (list[i] == list[j]) return false; return true; } 10. Programming. One possible solution appears below. public static int[] collapse(int[] list) { int[] result = new int[list.length / 2 + list.length % 2]; for (int i = 0; i < list.length; i++) result[i / 2] += list[i]; return result; }
Stuart Reges
Last modified: Thu Jun 9 14:05:53 PDT 2005