Key to CSE142 Sample Midterm, Winter 2006 handout #18 1. Expression Value ----------------------------------------------- 3 * 4 + 5 * 6 42 23 % 5 + - 17 % (16 % 10) -2 or 4 "1" + 2 + 3 * 4 + (5 + 6) "121211" 1.5 * 2 + 20 / 3 / 4.0 + 6 / 4 5.5 345 / 10 / 3 + 10 / (5 / 2.0) 15.0 2. Parameter Mystery. The program produces the following output. foo wants buzz to sue. bill wants sue to buzz. hope wants foo to bill. bill wants sue to hope. hope wants bill to sue. 3. Method Call Value Returned -------------------------------------- mystery(1); 1 mystery(3); 2 mystery(4); 3 mystery(5); 5 mystery(6); 8 4. y > x z < 0 z > 0 +---------------------+---------------------+---------------------+ Point A | sometimes | never | never | +---------------------+---------------------+---------------------+ Point B | never | never | sometimes | +---------------------+---------------------+---------------------+ Point C | sometimes | never | always | +---------------------+---------------------+---------------------+ Point D | always | never | sometimes | +---------------------+---------------------+---------------------+ Point E | always | sometimes | sometimes | +---------------------+---------------------+---------------------+ 5. Four possible solutions appear below. public static boolean hasMidpoint(int x, int y, int z) { return (2 * x == y + z || 2 * y == x + z || 2 * z == x + y); } public static boolean hasMidpoint(int x, int y, int z) { if (x == (y + z) / 2.0) { return true; } if (y == (x + z) / 2.0) { return true; } if (z == (x + y) / 2.0) { return true; } return false; } public static boolean hasMidpoint(int x, int y, int z) { double average = (x + y + z) / 3.0; if (x == average) { return true; } if (y == average) { return true; } if (z == average) { return true; } return false; } public static boolean hasMidpoint(int x, int y, int z) { return (x - y == y - z || x - z == z - y || y - x == x - z); } 6. One possible solution appears below. public static void printMultiples(int n, int times) { System.out.print("The first " + times + " multiples of " + n + " are " + + n); for (int i = 2; i <= times; i++) { System.out.print(", " + i * n); } System.out.println(); } 7. Three possible solutions appear below. public static void printStripped(String s) { boolean inComment = false; for (int i = 0; i < s.length(); i++) { char next = s.charAt(i); if (next == '<') { inComment = true; } else if (inComment && next == '>') { inComment = false; } else if (!inComment) { System.out.print(next); } } System.out.println(); } public static void printStripped(String s) { int start = s.indexOf('<'); while (start != -1) { int stop = s.indexOf('>', start + 1); s = s.substring(0, start) + s.substring(stop + 1); start = s.indexOf('<'); } System.out.println(s); } public static void printStripped(String s) { System.out.println(s.replaceAll("<[^>]*>", "")); }
Stuart Reges
Last modified: Mon Oct 31 19:09:12 PST 2005