Key to CSE142 Midterm, Autumn 2014 handout #13
1. Expression Value
-----------------------------------------------
3 * 4 + 5 * 6 42
23 % 5 - 17 % (16 % 10) -2
"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.
bill wants sue to buzz.
hope wants foo to bill.
bill wants sue to hope.
hope wants bill to sue.
3. Method Call Output Produced
---------------------------------------
ifElseMystery(2, 3); 6 2
ifElseMystery(1, 4); 4 3
ifElseMystery(5, 4); 5 8
ifElseMystery(4, 4); 8 3
4. Method Call Output Produced
---------------------------------------
mystery(1); 1 1
mystery(5); 3 4
mystery(10); 4 8
mystery(42); 6 32
5. x > y z > 0 y % 2 == 0
+---------------------+---------------------+---------------------+
Point A | sometimes | never | never |
+---------------------+---------------------+---------------------+
Point B | always | sometimes | sometimes |
+---------------------+---------------------+---------------------+
Point C | sometimes | always | sometimes |
+---------------------+---------------------+---------------------+
Point D | sometimes | always | always |
+---------------------+---------------------+---------------------+
Point E | never | sometimes | sometimes |
+---------------------+---------------------+---------------------+
6. One possible solution appears below.
public static void randomWalk(Random r, int goal) {
int position = 0;
int max = 0;
int min = 0;
System.out.println("goal = " + goal + ", pos = 0");
while (position != goal) {
int add = r.nextInt(5) - 2;
position = position + add;
System.out.println("adding " + add + ", pos = " + position);
if (position > max) {
max = position;
}
if (position < min) {
min = position;
}
}
System.out.println("min = " + min + ", max = " + max);
}
7. One possible solution appears below.
public static boolean checkPrime(int n) {
System.out.print("factors of " + n + " = 1");
int count = 1;
for (int i = 2; i <= n; i++) {
if (n % i == 0) {
System.out.print(", " + i);
count++;
}
}
System.out.println();
System.out.println("Total factors = " + count);
return count == 2;
}
8. Two possible solutions appear below.
public static String undouble(String s) {
String result = "";
if (s.length() > 0) {
char last = s.charAt(0);
result += last;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) != last) {
result += s.charAt(i);
}
last = s.charAt(i);
}
}
return result;
}
public static String undouble(String s) {
String result = "";
if (s.length() > 0) {
result = s.substring(0, 1);
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) != s.charAt(i - 1)) {
result += s.charAt(i);
}
}
}
return result;
}
Stuart Reges
Last modified: Fri Sep 16 16:16:07 PDT 2011