Key to CSE142 Midterm, Winter 2011 handout #15
1. Expression Value
-----------------------------------------------
13 + 2 * 5 / 3 16
2.5 * 2 * 5 / 10 + 1.5 4.0
85 % 10 + 4 % 10 - 17 % 3 7
2 + 3 + "." + (3 + 4) + 2 * 3 "5.76"
482 / 10 / 5 / 2.0 * 2 + 14 / 5 11.0
2. Parameter Mystery. The program produces the following output.
skip likes to drive with george
george likes to work with drive
george likes to skip with mary
john likes to dance with mary
3. Method Call Output Produced
---------------------------------------
ifElseMystery(14, 14); 14 13
ifElseMystery(4, 5); 7 5
ifElseMystery(10, 5); 12 10
ifElseMystery(2, 8); 3 8
4. Method Call Output Produced
---------------------------------------
mystery(8); 1 8
mystery(32); 2 5
mystery(184); 3 13
mystery(8239); 4 22
5. next == 0 prev == 0 next == prev
+---------------------+---------------------+---------------------+
Point A | sometimes | always | sometimes |
+---------------------+---------------------+---------------------+
Point B | never | sometimes | sometimes |
+---------------------+---------------------+---------------------+
Point C | never | never | always |
+---------------------+---------------------+---------------------+
Point D | sometimes | never | sometimes |
+---------------------+---------------------+---------------------+
Point E | always | sometimes | sometimes |
+---------------------+---------------------+---------------------+
6. Two possible solutions appear below.
public static int numUnique(int x, int y, int z) {
if (x == y && y == z) {
return 1;
} else if (x != y && x != z && y != z) {
return 3;
} else {
return 2;
}
}
public static int numUnique(int x, int y, int z) {
int count = 0;
if (x != y) {
count++;
}
if (y != z) {
count++;
}
if (x != z) {
count++;
}
if (count == 0) {
count = 1;
}
return count;
}
7. One possible solution appears below.
public static void printNumbers(Random r) {
int n = r.nextInt(50) + 1;
System.out.print("[" + n);
while (n % 10 != 5) {
n = r.nextInt(50) + 1;
System.out.print(", " + n);
}
System.out.println("]");
}
8. Two possible solutions appear below.
public static int numWords(String s) {
int count = 0;
boolean inWord = false;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
inWord = false;
} else if (!inWord) {
count++;
inWord = true;
}
}
return count;
}
public static int numWords(String s) {
int count = 0;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i - 1) == ' ' && s.charAt(i) != ' ') {
count++;
}
}
if (s.length() > 0 && s.charAt(0) != ' ') {
count++;
}
return count;
}
Stuart Reges
Last modified: Fri Sep 16 15:53:53 PDT 2011