Key to CSE142 Sample Midterm, Fall 2005 handout #17
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.
skip likes to drive with george
john likes to skip with mary
george likes to work with drive
george likes to skip with mary
john likes to dance with mary
3. Method Call Output Produced
---------------------------------------
mystery(8); 1 8
mystery(32); 2 5
mystery(72); 2 9
mystery(184); 3 13
mystery(8239); 4 22
4. next < 0 y > 0 x > 0
+---------------------+---------------------+---------------------+
Point A | sometimes | always | never |
+---------------------+---------------------+---------------------+
Point B | sometimes | sometimes | sometimes |
+---------------------+---------------------+---------------------+
Point C | always | sometimes | always |
+---------------------+---------------------+---------------------+
Point D | sometimes | sometimes | sometimes |
+---------------------+---------------------+---------------------+
Point E | never | sometimes | sometimes |
+---------------------+---------------------+---------------------+
5. Two possible solutions appear below.
public static void rollDoubles(Random r) {
int count = 1;
int roll1 = r.nextInt(6) + 1;
int roll2 = r.nextInt(6) + 1;
while (roll1 != roll2) {
System.out.println("Next roll = " + roll1 + ", " + roll2);
roll1 = r.nextInt(6) + 1;
roll2 = r.nextInt(6) + 1;
count++;
}
System.out.println("Next roll = " + roll1 + ", " + roll2);
System.out.println("Doubles after " + count + " rolls");
System.out.println();
}
public static void rollDoubles(Random r) {
int count = 0;
int roll1 = -1;
int roll2 = -2;
while (roll1 != roll2) {
roll1 = r.nextInt(6) + 1;
roll2 = r.nextInt(6) + 1;
System.out.println("Next roll = " + roll1 + ", " + roll2);
count++;
}
System.out.println("Doubles after " + count + " rolls");
System.out.println();
}
6 Two possible solutions appear below.
public static boolean before(int month1, int day1, int month2, int day2) {
if (month1 == month2)
return (day1 < day2);
else
return (month1 < month2);
}
public static boolean before2(int month1, int day1, int month2, int day2) {
if (month1 < month2)
return true;
else if (month1 > month2)
return false;
else if (day1 < day2)
return true;
else
return false;
}
7. One possible solution appears below.
public static int weave(int x, int y) {
int answer = 0;
int multiplier = 1;
while (x != 0 || y != 0) {
answer = answer + multiplier * (x % 10 * 10 + y % 10);
multiplier *= 100;
x /= 10;
y /= 10;
}
return answer;
}