Key to CSE142 Sample Midterm, Spring 2022 handout #10 1. Expression Value ----------------------------------------------- 3 * (5 - 2) - 3 - 2 * 2 2 4 * 7 % 8 + 132 % 10 + 3 % 4 9 27 / 5 / 2 + 3.4 * 2 - 1.1 * 2 6.6 9 + 9 + "9 + 9" + 9 + 9 "189 + 999" 19 / 2 / 2.0 + 2.5 * 6 / 2 + 0.5 * 4 14.0 2. Parameter Mystery. The program produces the following output. a snow and slippery for sleet a storm and snow for sleetsnow a snowsleet and sleetsnow for snowstorm a sun and storm for sunny 3. Method Call Output Produced --------------------------------------- ifElseMystery(2, 2); 4 2 ifElseMystery(3, 1); 1 4 ifElseMystery(4, 0); 4 1 ifElseMystery(5, 3); 4 7 ifElseMystery(1, 2); 2 0 ifElseMystery(7, 4); 8 7 4. Method Call Output Produced --------------------------------------- mystery(8); 1 8 mystery(32); 2 5 mystery(184); 3 13 mystery(8239); 4 22 5. x == 1 x % 2 == 1 y == 0 +---------------------+---------------------+---------------------+ Point A | sometimes | sometimes | always | +---------------------+---------------------+---------------------+ Point B | never | sometimes | sometimes | +---------------------+---------------------+---------------------+ Point C | sometimes | sometimes | never | +---------------------+---------------------+---------------------+ Point D | never | never | sometimes | +---------------------+---------------------+---------------------+ Point E | always | always | sometimes | +---------------------+---------------------+---------------------+ 6. One possible solution appears below. public static int generate(Scanner console) { System.out.print("number between -5 and 5? "); int target = console.nextInt(); Random r = new Random(); int next = r.nextInt(11) - 5; System.out.print("numbers are: " + next); int count = 1; while (next != target) { next = r.nextInt(11) - 5; System.out.print(", " + next); count++; } System.out.println(); System.out.println("came up after " + count + " tries"); return count; } 7. One possible solution appears below. public static int digitRange(int n) { int min = n % 10; int max = n % 10; while (n > 0) { int digit = n % 10; n = n / 10; if (digit < min) { min = digit; } if (digit > max) { max = digit; } } return max - min; } 8. Two 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); }
Stuart Reges
Last modified: Fri Apr 29 11:18:10 PDT 2022