Key to CSE142B Midterm, Winter 2013 handout #16
1. Expression Value
-------------------------------------------------
16 / 3 + 3.2 * 2 11.4
8 / 7 + "5 / 4" + 8 / 3 "15 / 42"
88 % 10 % 3 * 16 / 10 3
29 / 3 / 2 / 4.0 + 3.6 * 2 8.2
1.4 + (3 + 2 * 6) / (8 - 14 / 3) * 2.2 8.0
2. Parameter Mystery. The program produces the following output.
to walk the walk is good
to hear the good is bad
to feel the walk is song
to feel the talk is bad
3. Method Call Output Produced
---------------------------------------
ifElseMystery(4, 15); 6 15
ifElseMystery(7, 17); 9 17
ifElseMystery(12, 5); 12 1
ifElseMystery(16, 8); 16 4
4. Method Call Value Returned
--------------------------------------
mystery(4); 2 2
mystery(5); 1 5
mystery(24); 4 3
mystery(28); 3 7
5. x > y z == 0 x == y
+---------------------+---------------------+---------------------+
Point A | sometimes | always | sometimes |
+---------------------+---------------------+---------------------+
Point B | sometimes | sometimes | never |
+---------------------+---------------------+---------------------+
Point C | always | never | never |
+---------------------+---------------------+---------------------+
Point D | never | never | never |
+---------------------+---------------------+---------------------+
Point E | never | sometimes | always |
+---------------------+---------------------+---------------------+
6. 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");
}
}
7. One possible solution appears below.
public static boolean hasOddEvenDigit(int n) {
int evens = 0;
int odds = 0;
while (n > 0) {
int digit = n % 10;
n = n / 10;
if (digit % 2 == 0) {
evens++;
} else {
odds++;
}
}
return evens > 0 && odds > 0;
}
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 Sep 16 16:16:07 PDT 2011