Key to CSE142 Midterm
1. Expression Value
-----------------------------------------------
8 * 2 - 2 * 3 10
87 % 10 + 28 % 5 % 2 8
1 + 2 + "3" + 4 + 5 * 6 "33430"
2 * 2.3 + 5 / 2 + 19 / 4 * 2.0 14.6
436 / 10 / 5 - 9 / 2 * 2.5 / 2 3.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(1, 2); 4 2
ifElseMystery(4, 2); 3 8
ifElseMystery(3, 2); 5 3
ifElseMystery(2, 2); 3 2
ifElseMystery(4, 4); 4 9
ifElseMystery(8, 6); 7 12
4. Method Call Output Produced
---------------------------------------
mystery(4); 2 2
mystery(5); 1 5
mystery(24); 4 3
mystery(28); 3 7
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 Sep 16 16:16:07 PDT 2011