Key to CSE142 Sample Midterm, Spring 2017 handout #10
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.
she can't take she with her
it can't take her with you
you can't take it with you
fred can't take her with him
3. Method Call Output Produced
---------------------------------------
ifElseMystery(5, 20); 7 5
ifElseMystery(42, 42); 43 41
ifElseMystery(6, 1); 9 7
ifElseMystery(2, 0); 3 -1
ifElseMystery(7, 10); 9 7
ifElseMystery(4, 4); 5 3
4. Method Call Output Produced
---------------------------------------
mystery(2); 1 2
mystery(5); 1 5
mystery(9); 2 3
mystery(12); 3 3
5. y == 0 y % 2 == 0 z == 0
+---------------------+---------------------+---------------------+
Point A | never | always | always |
+---------------------+---------------------+---------------------+
Point B | never | always | sometimes |
+---------------------+---------------------+---------------------+
Point C | sometimes | always | never |
+---------------------+---------------------+---------------------+
Point D | never | never | sometimes |
+---------------------+---------------------+---------------------+
Point E | always | always | sometimes |
+---------------------+---------------------+---------------------+
6. One possible solution appears below.
public static void spinWheel(Random r, int n) {
int spin = r.nextInt(5) * 10 + 20;
System.out.print("spins: " + spin);
int count = 0;
if (spin == 20) {
count++;
}
int totalSpins = 1;
while (count < n) {
spin = r.nextInt(5) * 10 + 20;
totalSpins++;
System.out.print(", " + spin);
if (spin == 20) {
count++;
} else {
count = 0;
}
}
System.out.println();
System.out.println(n + " in a row after " + totalSpins + " spins");
}
6. One possible solution appears below.
public static boolean balanceCheckbook(Scanner console) {
System.out.print("initial balance? ");
double balance = console.nextDouble();
System.out.print("how many transactions? ");
int count = console.nextInt();
double min = balance;
for (int i = 1; i <= count; i++) {
System.out.print(i + "/" + count + " amount? ");
double amount = console.nextDouble();
balance = balance + amount;
System.out.println("new balance = $" + balance);
if (balance < min) {
min = balance;
}
}
System.out.println("minimum balance = $" + min);
return (min < 0);
}
8. One possible solution appears below.
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;
}