Key to CSE142 Midterm, Spring 2006 handout #17
1. Expression Value
-----------------------------------------------
4 * (2 + 4) - 3 * 5 9
54 % 10 + 8 * 3 % 9 10
3 * 2 + 4 + "+" + 2 + 3 * 4 "10+212"
2.3 * 3 + 19 / 5 / 2 + 6.0 / 5 9.1
108 / 20 * 3 / 4 / 2.0 + 1.0 / 2 2.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 claim the talk is feel
to feel the talk is bad
3. Method Call Output Produced
---------------------------------------
mystery(2); 1 2
mystery(4); 2 2
mystery(5); 1 5
mystery(24); 4 3
mystery(28); 3 7
4. 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 |
+---------------------+---------------------+---------------------+
5. One possible solution appears below.
public static void flip(Random r) {
int count = 0;
int heads = 0;
while (heads < 3) {
count++;
int next = r.nextInt(2);
if (next == 0) {
System.out.println("heads");
heads++;
} else {
System.out.println("tails");
heads = 0;
}
}
System.out.println("3 heads in a row after " + count + " flips");
System.out.println();
}
6. One possible solution appears below.
public static int minHailstoneValue(int n, int steps) {
int min = n;
for (int i = 1; i < steps; i++) {
if (n % 2 == 0) {
n /= 2;
} else {
n = 3 * n + 1;
}
if (n < min) {
min = n;
}
}
return min;
}
7. Two possible solutions appear below.
public static boolean sameDashes(String str1, String str2) {
int i1 = str1.indexOf('-');
int i2 = str2.indexOf('-');
while (i1 != -1 || i2 != -1) {
if (i1 != i2) {
return false;
}
str1 = str1.substring(i1 + 1, str1.length());
str2 = str2.substring(i2 + 1, str2.length());
i1 = str1.indexOf('-');
i2 = str2.indexOf('-');
}
return true;
}
public static boolean sameDashes(String str1, String str2) {
for (int i = 0; i < str1.length(); i++) {
if (str1.charAt(i) == '-') {
if (i > str2.length() || str2.charAt(i) != '-') {
return false;
}
}
}
for (int i = 0; i < str2.length(); i++) {
if (str2.charAt(i) == '-') {
if (i > str1.length() || str1.charAt(i) != '-') {
return false;
}
}
}
return true;
}