Key to CSE142 Sample Midterm #2 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. she can't take she with her it can't take her with you you can't take it with you fred can't take her with him 3. Method Call Output Produced --------------------------------------- ifElseMystery(4, 15); 15 18 ifElseMystery(7, 17); 27 10 ifElseMystery(12, 5); 15 10 ifElseMystery(16, 8); 28 2 4. Method Call Output Produced --------------------------------------- mystery(1); 1 mystery(3); 2 mystery(5); 5 mystery(7); 13 5. n == 0 n % 2 == 1 x == 0 +---------------------+---------------------+---------------------+ Point A | sometimes | sometimes | always | +---------------------+---------------------+---------------------+ Point B | never | sometimes | sometimes | +---------------------+---------------------+---------------------+ Point C | never | always | never | +---------------------+---------------------+---------------------+ Point D | sometimes | sometimes | sometimes | +---------------------+---------------------+---------------------+ Point E | always | never | sometimes | +---------------------+---------------------+---------------------+ 6. One possible solution appears below. public static int quadrant(double x, double y) { if (x > 0 && y > 0) { return 1; } else if (x < 0 && y > 0) { return 2; } else if (x < 0 && y < 0) { return 3; } else if (x > 0 && y < 0) { return 4; } else { // at least one equals 0 return 0; } } 7. One possible solution appears below. public static void printTwoDigit(Random r, int n) { boolean seen42 = false; for (int i = 1; i <= n; i++) { int number = r.nextInt(90) + 10; System.out.println("next = " + number); if (number == 42) { seen42 = true; } } if (seen42) { System.out.println("We saw a 42"); } else { System.out.println("no 42"); } } 8. One possible solution appears below. public static int digitsInARow(int n) { int count = 1; int last = -1; int max = 1; while (n > 0) { if (n % 10 == last) { count++; } else { count = 1; } if (count > max) { max = count; } last = n % 10; n = n / 10; } return max; }