TEST BANK FOR BUILDING JAVA PROGRAMS A BACK TO BASIC APPROACH 4TH EDITION

Page 1


Sample Midterm Exam #1 1. Expressions For each expression in the left-hand column, indicate its value in the right-hand column. Be sure to list a constant of appropriate type (e.g., 7.0 rather than 7 for a double, Strings in quotes, true/false for a boolean). Expression

Value

3 * 4 + 5 * 6 + 7 * -2

_________________________

1.5 * 2.0 + (5.5 / 2) + 5 / 4

_________________________

23 % 5 + 31 / 4 % 3 - 17 % (16 % 10)

_________________________

"1" + 2 + 3 + "4" + 5 * 6 + "7" + (8 + 9)

_________________________

345 / 10 / 3 * 55 / 5 / 6 + 10 / (5 / 2.0)

_________________________

1 / 2 > 0 || 4 == 9 % 5 || 1 + 1 < 1 - 1

_________________________

1 of 8


2. Parameter Mystery At the bottom of the page, write the output produced by the following program. public class ParameterMystery { public static void main(String[] args) { String x = "java"; String y = "tyler"; String z = "tv"; String rugby = "hamburger"; String java = "donnie"; hamburger(x, y, z); hamburger(z, x, y); hamburger("rugby", z, java); hamburger(y, rugby, "x"); hamburger(y, y, "java"); } public static void hamburger(String y, String z, String x) { System.out.println(z + " and " + x + " like " + y); } }

2 of 8


3. If/Else Simulation For each call of the method below, write the value that is returned: public static int mystery(int a, int b) { int c; if (a > b) { c = a; } else if (b % a == 0) { c = b; } else { c = b + (a - (b % a)); } return c; } Method Call

Value Returned

mystery(4, 2)

_______________________________

mystery(5, 4)

_______________________________

mystery(5, 13)

_______________________________

mystery(5, 17)

_______________________________

mystery(4, 8)

_______________________________

3 of 8


4. While Loop Simulation For each call of the method below, write the output that is printed: public static void mystery(int i, int j) { while (i != 0 && j != 0) { i = i / j; j = (j - 1) / 2; System.out.print(i + " " + j + " "); } System.out.println(i); } Method Call

Output

mystery(5, 0);

_______________________________

mystery(3, 2);

_______________________________

mystery(16, 5);

_______________________________

mystery(80, 9);

_______________________________

mystery(1600, 40);

_______________________________

4 of 8


5. Assertions For the following method, identify each of the three assertions in the table below as being either ALWAYS true, NEVER true or SOMETIMES true / sometimes false at each labeled point in the code. (You may abbreviate these choices as A/N/S respectively.) public static int mystery(int x) { int y = 1; int z = 0; // Point A while (y <= x) { // Point B y = y * 10; z++; // Point C } // Point D z--; // Point E return z; } y > x

z < 0

z > 0

Point A Point B Point C Point D Point E

5 of 8


6. Programming Write a static method named hasMidpoint that accepts three integers as parameters and returns true if one of the integers is the midpoint between the other two integers; that is, if one integer is exactly halfway between them. Your method should return false if no such midpoint relationship exists. The integers could be passed in any order; the midpoint could be the 1st, 2nd, or 3rd. You must check all cases.

Calls such as the following should return true : hasMidpoint(4, 6, 8) hasMidpoint(2, 10, 6) hasMidpoint(8, 8, 8) hasMidpoint(25, 10, -5)

Calls such as the following should return false : hasMidpoint(3, 1, 3) hasMidpoint(1, 3, 1) hasMidpoint(21, 9, 58) hasMidpoint(2, 8, 16)

6 of 8


7. Programming Write a static method named sequenceSum that prints terms of the following mathematical sequence:

1

1 1 1 1 1      ... 2 3 4 5 6

( also written as

1

 i ) 

i 1

Your method should accept a real number as a parameter representing a limit, and should add and print terms of the sequence until the sum of terms meets or exceeds that limit. For example, if your method is passed 2.0, print terms until the sum of those terms is at ≥ 2.0. You should round your answer to 3 digits past the decimal point. The following is the output from the call sequenceSum(2.0); 1 + 1/2 + 1/3 + 1/4 = 2.083

(Despite the fact that the terms keep getting smaller, the sequence can actually produce an arbitrarily large sum if enough terms are added.) If your method is passed a value less than 1.0, no output should be produced. You must match the output format shown exactly; note the spaces and pluses separating neighboring terms. Other sample calls:

Calls Output

sequenceSum(0.0);

sequenceSum(1.0); 1 = 1.000

sequenceSum(1.5); 1 + 1/2 = 1.500

Call Output

sequenceSum(2.7); 1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6 + 1/7 + 1/8 = 2.718

7 of 8


8. Programming Write a static method named favoriteLetter that accepts two parameters: a Scanner for the console, and a favorite letter represented as a one-letter String. The method repeatedly prompts the user until two consecutive words are entered that start with that letter. The method then prints a message showing the last word typed. You may assume that the user will type a single-word response to each prompt. Your code should be case-sensitive; for example, if the favorite letter is a, you should not stop prompting if the user types words that start with an A. For example, the following logs represent the output from two calls to your method: (User input is underlined.)

Call Output

Scanner console = new Scanner(System.in); favoriteLetter(console, "y"); Looking for two "y" words in a row. Type a word: hi Type a word: bye Type a word: yes Type a word: what? Type a word: yellow Type a word: yippee "y" is for "yippee"

Scanner console = new Scanner(System.in); favoriteLetter(console, "A"); Looking for two "A" words in a row. Type a word: I Type a word: love Type a word: CSE142! Type a word: AND Type a word: PROGRAMS Type a word: are Type a word: always Type a word: Absolutely Type a word: Awesome "A" is for "Awesome"

8 of 8


Sample Midterm Exam #1 Key Also check out Practice-It to test solving these problems or to type in your own solution to see if it works! 1. Expressions Expression 3 * 4 + 5 * 6 + 7 * -2 1.5 * 2.0 + (5.5 / 2) + 5 / 4 23 % 5 + 31 / 4 % 3 - 17 % (16 % 10) "1" + 2 + 3 + "4" + 5 * 6 + "7" + (8 + 9) 345 / 10 / 3 * 55 / 5 / 6 + 10 / (5 / 2.0) 1 / 2 > 0 || 4 == 9 % 5 || 1 + 1 < 1 - 1

Value 28 6.75 -1 "123430717" 24.0 true

2. Parameter Mystery tyler and tv like java java and tyler like tv tv and donnie like rugby hamburger and x like tyler tyler and java like tyler

3. If/Else Simulation Method Call

Value Returned

mystery(4, 2) mystery(5, 4) mystery(5, 13) mystery(5, 17) mystery(4, 8)

4 5 15 20 8

4. While Loop Simulation Method Call

Output

mystery(5, 0); mystery(3, 2); mystery(16, 5); mystery(80, 9); mystery(1600, 40);

5 1 0 1 3 2 1 0 1 8 4 2 1 2 0 2 40 19 2 9 0 4 0

5. Assertions

Point A Point B Point C Point D Point E

y > x SOMETIMES NEVER SOMETIMES ALWAYS ALWAYS

z < 0 NEVER NEVER NEVER NEVER SOMETIMES

z > 0 NEVER SOMETIMES ALWAYS SOMETIMES SOMETIMES

1 of 3


6. Programming (five solutions shown) public static boolean hasMidpoint(int a, int b, int c) { double mid = (a + b + c) / 3.0; if (a == mid || b == mid || c == mid) { return true; } else { return false; } } public static boolean hasMidpoint(int a, int b, int c) { double mid = (a + b + c) / 3.0; return (a == mid || b == mid || c == mid); } public static boolean hasMidpoint(int a, int b, int c) { return (a == (b + c) / 2.0 || b == (a + c) / 2.0 || c == (a + b) / 2.0); } public static boolean hasMidpoint(int a, int b, int c) { int max = Math.max(a, Math.max(b, c)); int min = Math.min(a, Math.min(b, c)); double mid = (max + min) / 2.0; return (a == mid || b == mid || c == mid); } public static boolean hasMidpoint(int a, int b, int c) { return (a - b == b - c || b - a == a - c || a - c == c - b); }

7. Programming (one solution shown) public static void sequenceSum(double limit) { if (limit >= 1) { System.out.print("1"); int denomenator = 1; double sum = 1.0; while (sum < limit) { denomenator++; sum += 1.0 / denomenator; System.out.print(" + 1/" + denomenator); } System.out.printf(" = %.3f\n", sum); } }

2 of 3


8. Programming (three solutions shown) public static void favoriteLetter(Scanner console, String letter) { System.out.println("Looking for two \"" + letter + "\" words in a row."); int count = 0; String word = ""; while (count < 2) { System.out.print("Type a word: "); word = console.next(); if (word.startsWith(letter)) { count++; } else { count = 0; } } System.out.println("\"" + letter + "\" is for \"" + word + "\""); } // uses two Strings instead of count, and uses forever/break loop public static void favoriteLetter(Scanner console, String letter) { System.out.println("Looking for two \"" + letter + "\" words in a row."); System.out.print("Type a word: "); String word1 = console.next(); System.out.print("Type a word: "); String word2 = console.next(); while (!(word1.startsWith(letter) && word2.startsWith(letter))) { word1 = word2; System.out.print("Type a word: "); word2 = console.next(); } System.out.println("\"" + letter + "\" is for \"" + word2 + "\""); } // uses do/while loop public static void favoriteLetter(Scanner console, String letter) { System.out.println("Looking for two \"" + letter + "\" words in a row."); int count = 0; String word; do { System.out.print("Type a word: "); word = console.next(); if (word.startsWith(letter)) { count++; } else { count = 0; } } while (count < 2); System.out.println("\"" + letter + "\" is for \"" + word + "\""); }

3 of 3


Sample Midterm Exam #2 1. Expressions For each expression in the left-hand column, indicate its value in the right-hand column. Be sure to list a constant of appropriate type (e.g., 7.0 rather than 7 for a double, Strings in quotes). Expression

Value

8 + 5 * 3 / 2

_________________________

1.5 * 4 * 7 / 8 + 3.4

_________________________

73 % 10 - 6 % 10 + 28 % 3

_________________________

4 + 1 + 9 + "." + (-3 + 10) + 11 / 3

_________________________

3 / 14 / 7 / (1.0 * 2) + 10 / 6

_________________________

10 > 11 == 4 / 3 > 1

_________________________

1 of 8


2. Parameter Mystery At the bottom of the page, write the output produced by the following program. public class ParameterMystery { public static void main(String[] args) { String x = "happy"; String y = "pumpkin"; String z = "orange"; String pumpkin = "sleepy"; String orange = "vampire"; orange(y, x, z); orange(x, z, y); orange(pumpkin, z, "y"); z = "green"; orange("x", "pumpkin", z); orange(y, z, orange); } public static void orange(String z, String y, String x) { System.out.println(y + " and " + z + " were " + x); } }

2 of 8


3. If/Else Simulation For each call of the method below, write the value that is returned: public static int mystery(int n) { if (n < 0) { n = n * 3; return n; } else { n = n + 3; } if (n % 2 == 1) { n = n + n % 10; } return n; } Method Call

Value Returned

mystery(-5)

_______________________________

mystery(0)

_______________________________

mystery(7)

_______________________________

mystery(18)

_______________________________

mystery(49)

_______________________________

3 of 8


4. While Loop Simulation For each call of the method below, write the value that is returned: public static int mystery(int i, int j) { int k = 0; while (i > j) { i = i - j; k = k + (i - 1); } return k; } Method Call

Value Returned

mystery(2, 9)

_______________________________

mystery(5, 1)

_______________________________

mystery(38, 5)

_______________________________

mystery(5, 5)

_______________________________

mystery(40, 10)

_______________________________

4 of 8


5. Assertions For the following method, identify each of the three assertions in the table below as being either ALWAYS true, NEVER true or SOMETIMES true / sometimes false at each labeled point in the code. You may abbreviate these choices as A/N/S respectively. public static int mystery(Scanner console) { int y = 0; int z = 1; int next = console.nextInt(); // Point A while (next >= 0) { // Point B if (y > z) { // Point C z = y; } y++; next = console.nextInt(); // Point D } // Point E return z; } next < 0

y > z

y == 0

Point A Point B Point C Point D Point E

5 of 8


6. Programming Write a static method named printMultiples that accepts an integer n and an integer m as parameters and that prints a complete line of output reporting the first m multiples of n. For example, the following calls: printMultiples(3, 5); printMultiples(7, 3);

should produce this output: The first 5 multiples of 3 are 3, 6, 9, 12, 15 The first 3 multiples of 7 are 7, 14, 21

Notice that the multiples are separated by commas. You must exactly reproduce this format. You may assume that the number of multiples you will be asked to generate is greater than or equal to 1.

6 of 8


7. Programming Write a static method named monthApart that accepts four integer parameters representing two calendar dates. Each date consists of a month (1 through 12) and a day (1 through the number of days in that month [28-31]). Assume that all dates occur during the same year. The method returns whether the dates are at least a month apart. For example, the following dates are all considered to be at least a month apart from 9/19 (September 19): 2/14, 7/25, 8/2, 8/19, 10/19, 10/20, and 11/5. The following dates are NOT at least a month apart from 9/19: 9/20, 9/28, 10/1, 10/15, and 10/18. Note that the first date could come before or after (or be the same as) the second date. Assume that all parameter values passed are valid. Sample calls: monthApart( 6, 14, monthApart( 4, 5, monthApart( 4, 15, monthApart( 4, 16, monthApart( 6, 14, monthApart( 7, 7, monthApart( 7, 8, monthApart(10, 14,

9, 21) should return true, 5, 15) should return true, 5, 15) should return true, 5, 15) should return false, 6, 8) should return false, 6, 8) should return false, 6, 8) should return true, 7, 15) should return true,

because June 14 is at least a month before September 21 because April 5 is at least a month before May 15 because April 15 is at least a month before May 15 because April 16 isn't at least a month apart from May 15 because June 14 isn't at least a month apart from June 8 because July 7 isn't at least a month apart from June 8 because July 8 is at least a month after June 8 because October 14 is at least a month after July 15

7 of 8


8. Programming Write a static method named threeHeads that repeatedly flips a coin until three heads in a row are seen. You should use a Random object to give an equal chance to a head or a tail appearing. Each time the coin is flipped, what is seen is displayed (H for heads, T for tails). When 3 heads in a row are flipped a congratulatory message is printed. Here are possible outputs of two calls to threeHeads: T T T H T H H H Three heads in a row! T H T H T T T T T H H T H H H Three heads in a row!

8 of 8


Sample Midterm Exam #2 Key Also check out Practice-It to test solving these problems or to type in your own solution to see if it works! 1. Expressions Expression 8 + 5 * 3 / 2 1.5 * 4 * 7 / 8 + 3.4 73 % 10 - 6 % 10 + 28 % 3 4 + 1 + 9 + "." + (-3 + 10) + 11 / 3 3 / 14 / 7 / (1.0 * 2) + 10 / 6 10 > 11 == 4 / 3 > 1

Value 15 8.65 -2 "14.73" 1.0 true

2. Parameter Mystery happy and pumpkin were orange orange and happy were pumpkin orange and sleepy were y pumpkin and x were green green and pumpkin were vampire

3. If/Else Simulation Method Call

Value Returned

mystery(-5) mystery(0) mystery(7) mystery(18) mystery(49)

-15 6 10 22 52

4. While Loop Simulation Method Call

Value Returned

mystery(2, 9) mystery(5, 1) mystery(38, 5) mystery(5, 5) mystery(40, 10)

0 6 119 0 57

5. Assertions

Point A Point B Point C Point D Point E

next < 0 SOMETIMES NEVER NEVER SOMETIMES ALWAYS

y > z NEVER SOMETIMES ALWAYS SOMETIMES SOMETIMES

y == 0 ALWAYS SOMETIMES NEVER NEVER SOMETIMES

1 of 2


6. Programming (one solution shown) public static void printMultiples(int n, int times) { System.out.print("The first " + times + " multiples of " + n + " are " + n); for (int i = 2; i <= times; i++) { System.out.print(", " + i * n); } System.out.println(); }

7. Programming (four solutions shown) public static boolean monthApart(int m1, int d1, int m2, int d2) { if (m1 == m2) { return false; } else if (m1 <= m2 - 2) { return true; } else if (m1 >= m2 + 2) { return true; } else if (m1 == m2 - 1) { if (d1 <= d2) { return true; } else { return false; } } else if (m1 == m2 + 1) { if (d1 >= d2) { return true; } else { return false; } } else { return false; } } public static boolean monthApart(int m1, int d1, int m2, int d2) { if (m1 < m2 - 1 || m1 > m2 + 1) { return true; } else if (m1 == m2 - 1 && d1 <= d2) { return true; } else if (m1 == m2 + 1 && d1 >= d2) { return true; } else { return false; } } public static boolean monthApart(int m1, int d1, int m2, int d2) { return (m2 - m1 > 1) || (m1 - m2 > 1) || (m2 - m1 == 1 && d1 <= d2) || (m1 - m2 == 1 && d1 >= d2); } public static boolean monthApart(int m1, int d1, int m2, int d2) { return Math.abs((m1 * 31 + d1) - (m2 * 31 + d2)) >= 31; }

8. Programming (one solution shown) public static void threeHeads() { Random r = new Random(); int numHeads = 0; while (numHeads < 3) { int flip = r.nextInt(2); // flip coin if (flip == 0) { // heads numHeads++; System.out.print("H "); } else { numHeads = 0; System.out.print("T "); } } System.out.println(); System.out.println("Three heads in a row!"); }

2 of 2


Sample Midterm Exam #3 1. Expressions For each expression in the left-hand column, indicate its value in the right-hand column. Be sure to list a constant of appropriate type (e.g., 7.0 rather than 7 for a double, Strings in quotes). Expression

Value

1 + 2 * 3 - 4 * 5

_____________________________

5 / 2 + 9.0 / 2.0 - 2 * 1.25

_____________________________

29 % 2 % 5 + 34 % 3

_____________________________

8 + 6 * -2 + 4 + "0" + (2 + 5)

_____________________________

31 / 2 / 10.0 + 10 / (5 / 2.0)

_____________________________

(1 != 2) != (2 != 3)

_____________________________

1 of 8


2. Parameter Mystery At the bottom of the page, write the output produced by the following program. public class ParameterMystery { public static void main(String[] args) { String a = "felt"; String b = "saw"; String c = "drew"; String saw = "sue"; String drew = "b"; mystery(a, b, c); mystery(b, a, saw); mystery(drew, c, saw); mystery("a", saw, drew); mystery(a, a, "drew"); } public static void mystery(String b, String a, String c) { System.out.println(c + " " + a + " the " + b); } }

2 of 8


3. If/Else Simulation For each call of the method below, write the output that is produced: public static void mystery(int x, int y) { if (x > y) { x = x - 5; y = y + 5; } if (x < y) { x++; y--; } else { x = y * 2; } System.out.println(x + " " + y); }

Method Call

Output

mystery(4, 7);

____________________________________________

mystery(3, 3);

____________________________________________

mystery(10, 5);

____________________________________________

mystery(20, 4);

____________________________________________

mystery(1, 1);

____________________________________________

3 of 8


4. While Loop Simulation For each call of the method below, write the output that is produced: public static void mystery(int a, int b) { while (b != 0) { if (a > b) { System.out.print(a + " "); a = a - b; } else { System.out.print(b + " "); b = b - a; } } System.out.println(a); }

Method Call

Output

mystery(42, 0);

____________________________________________

mystery(6, 12);

____________________________________________

mystery(18, 27);

____________________________________________

mystery(24, 60);

____________________________________________

mystery(50, 15);

____________________________________________

4 of 8


5. Assertions For the following method, identify each of the three assertions in the table below as being either ALWAYS true, NEVER true or SOMETIMES true / sometimes false at each labeled point in the code. You may abbreviate these choices as A/N/S respectively. public static int assertions(int n) { int x = 2; // Point A while (x < n) { // Point B if (n % x == 0) { n = n / x; x = 2; // Point C } else { x++; // Point D } }

}

// Point E return n;

x > 2

x < n

n % x == 0

Point A Point B Point C Point D Point E

5 of 8


6. Programming (15 points) Write a static method named enoughTimeForLunch that accepts four integers hour1, minute1, hour2, and minute2 as parameters. Each pair of parameters represents a time on the 24-hour clock (for example, 1:36 PM would be represented as 13 and 36). The method should return true if the gap between the two times is long enough to eat lunch: that is, if the second time is at least 45 minutes after the first time. Otherwise the method should return false. You may assume that all parameter values are valid: the hours are both between 0 and 23, and the minute parameters are between 0 and 59. You may also assume that both times represent times in the same day, e.g. the first time won't represent a time today while the second time represents a time tomorrow. Note that the second time might be earlier than the first time; in such a case, your method should return false. Here are some example calls to your method and their expected return results:

Call

Value Returned

enoughTimeForLunch(11, 00, 11, 59) enoughTimeForLunch(12, 30, 13, 00) enoughTimeForLunch(12, 30, 13, 15) enoughTimeForLunch(14, 20, 17, 02) enoughTimeForLunch(12, 30, 9, 30) enoughTimeForLunch(12, 00, 11, 55)

true false true true false false

6 of 8


7. Programming (15 points) Write a static method named printGrid that accepts two integer parameters rows and cols. The output is a commaseparated grid of numbers where the first parameter (rows) represents the number of rows of the grid and the second parameter (cols) represents the number of columns. The numbers count up from 1 to (rows x cols). The output are displayed in column-major order, meaning that the numbers shown increase sequentially down each column and wrap to the top of the next column to the right once the bottom of the current column is reached. Assume that rows and cols are greater than 0. Here are some example calls to your method and their expected results:

Call Output

printGrid(3, 6);

printGrid(5, 3);

printGrid(4, 1);

printGrid(1, 3);

1, 4, 7, 10, 13, 16 2, 5, 8, 11, 14, 17 3, 6, 9, 12, 15, 18

1, 6, 11 2, 7, 12 3, 8, 13 4, 9, 14 5, 10, 15

1 2 3 4

1, 2, 3

7 of 8


8. Programming (10 points) Write a static method named countEvenDigits that accepts an integer as its parameter and returns the number of even-valued digits in that number. An even-valued digit is either 0, 2, 4, 6, or 8. For example, the number 8546587 has four even digits (the two 8s, the 4, and the 6), so the call countEvenDigits(8346387) should return 4. You may assume that the value passed to your method is non-negative.

8 of 8


Sample Midterm Exam #3 Key Also check out Practice-It to test solving these problems or to type in your own solution to see if it works! 1. Expressions Expression 1 + 2 * 3 - 4 * 5 5 / 2 + 9.0 / 2.0 - 2 * 1.25 29 % 2 % 5 + 34 % 3 8 + 6 * -2 + 4 + "0" + (2 + 5) 31 / 2 / 10.0 + 10 / (5 / 2.0) (1 != 2) != (2 != 3)

Value -13 4.0 2 "007" 5.5 false

2. Parameter Mystery drew saw the felt sue felt the saw sue drew the b b sue the a drew felt the felt

3. If/Else Simulation Method Call

Output

mystery(4, 7); mystery(3, 3); mystery(10, 5); mystery(20, 4); mystery(1, 1);

5 6 6 3 6 9 18 9 2 1

4. While Loop Simulation Method Call

Output

mystery(42, 0); mystery(6, 12); mystery(18, 27); mystery(24, 60); mystery(50, 15);

42 12 6 6 27 18 9 9 60 36 24 12 12 50 35 20 15 10 5 5

5. Assertions

Point A Point B Point C Point D Point E

x > 2 NEVER SOMETIMES NEVER ALWAYS SOMETIMES

x < n SOMETIMES ALWAYS SOMETIMES SOMETIMES NEVER

n % x == 0 SOMETIMES SOMETIMES SOMETIMES SOMETIMES SOMETIMES

1 of 3


6. Programming (five solutions shown) public static boolean enoughTimeForLunch(int h1, int m1, int h2, int m2) { if (h1 > h2) { return false; } else if (h1 == h2) { return m2 - m1 >= 45; } else if (h1 == h2 - 1) { return 60 + m2 - m1 >= 45; } else { return true; } } public static boolean enoughTimeForLunch(int h1, int m1, int h2, int m2) { if (h2 > h1 + 1) { return true; } else if (h2 == h1 && m1 + 45 <= m2) { return true; } else if (h2 == h1 + 1 && m1 - 15 <= m2) { return true; } else { return false; } } public static boolean enoughTimeForLunch(int h1, int m1, int h2, int m2) { if (h1 > h2) { return false; } else if (h1 == h2) { // same hour if (m1 + 45 <= m2) { // must be >= 45 min apart return true; } else { return false; } } else if (h2 == h1 + 1) { // h1 is just before h2 if (m1 - 15 <= m2) { // must be >= -15 min apart return true; } else { return false; } } else { // time 1 is > 1 hour before time 2 return true; } } public static boolean enoughTimeForLunch(int h1, int m1, int h2, int m2) { if ((h1 == h2 && m1 + 45 <= m2) || (h2 == h1 + 1 && m1 - 15 <= m2) || (h1 < h2 - 1)) { return true; } else { return false; } } public static boolean enoughTimeForLunch(int h1, int m1, int h2, int m2) { return 60 * h1 + m1 + 45 <= 60 * h2 + m2; }

2 of 3


7. Programming (three solutions shown) public static void printGrid(int rows, int cols) { for (int i = 1; i <= rows; i++) { System.out.print(i); for (int j = 1; j <= cols - 1; j++) { System.out.print(", " + (i + rows * j)); } System.out.println(); } } public static void printGrid(int rows, int cols) { for (int i = 1; i <= rows; i++) { for (int j = 0; j < cols - 1; j++) { System.out.print((i + rows * j) + ", "); } System.out.println(i + rows * (cols - 1)); } } public static void printGrid(int rows, int cols) { int n = 1; int count1 = 1; int count2 = 1; while (count1 <= rows * cols) { if (count1 % cols == 0) { System.out.println(n); count2++; n = count2; } else { System.out.print(n + ", "); n = n + rows; } count1++; } }

8. Programming (two solutions shown) public static int countEvenDigits(int n) { int count = 0; while (n != 0) { int digit = n % 10; n = n / 10; if (digit % 2 == 0) { count++; } } return count; } public static int countEvenDigits(int n) { int count = 0; while (n > 0) { if (n % 2 == 0) { count++; } n = n / 10; } return count; }

3 of 3


Sample Midterm Exam #4 1. Expressions For each expression in the left-hand column, indicate its value in the right-hand column. Be sure to list a constant of appropriate type and capitalization. e.g., 7 for an int, 7.0 for a double, "hello" for a String, true or false for a boolean. Expression

Value

5 * 2 * 4 - 3 * 3

_____________________________

29 / 4 / 2.0 + 18 / 5 + 1.5

_____________________________

30 % (4 + 3) + 16 % 20

_____________________________

!(23 + 2 * 2 <= 27) && 5 % 2 == 1

_____________________________

1 + 1 + "(8 - 2)" + (8 - 2) + 1 + 1

_____________________________

1 of 8


2. Parameter Mystery At the bottom of the page, write the output produced by the following program, as it would appear on the console. (Though the program uses words related to arithmetic, the output does not necessarily follow the rules of addition.) public class ParameterMystery { public static void main(String[] args) { int one = 4; int two = 3; int three = 10; int num = 17; int four = 3; racket(one, two, three); racket(three, four, 5); racket(2, two * 2, num); racket(num, three * one, four); racket(three - four, one, two); } public static void racket(int two, int one, int three) { System.out.println(three + " is roughly " + two + " plus " + one); } }

2 of 8


3. If/Else Simulation For each call below to the following method, write the output that is produced, as it would appear on the console: public static void mystery(int n) { System.out.print(n + " "); if (n > 10) { n = n / 2; } else if (n < 10) { n = n * 2; } if (n % 2 == 1) { n++; } else { n--; } System.out.println(n); }

Method Call

Output

mystery(4);

____________________________________________

mystery(30);

____________________________________________

mystery(-6);

____________________________________________

mystery(18);

____________________________________________

mystery(15);

____________________________________________

3 of 8


4. While Loop Simulation For each call below to the following method, write the output that is produced, as it would appear on the console: public static void mystery(int x, int y) { int s = 0; while (x > 0 && 2 * y >= x) { System.out.print(s + " "); y = y - x; x--; s = s + x; } System.out.println(s); }

Method Call

Output

mystery(-2, -6);

____________________________________________

mystery(2, 3);

____________________________________________

mystery(4, 8);

____________________________________________

mystery(5, 40);

____________________________________________

mystery(10, 31);

____________________________________________

4 of 8


5. Assertions For each of the five points labeled by comments, identify each of the assertions in the table below as either being always true, never true, or sometimes true / sometimes false. public static int mystery(int a) { int b = 0; int c = 0; // Point A while (a != 0) { // Point B c = a % 10; if (c % 2 == 0) { b++; } else { b = 0; // Point C } a = a / 10; // Point D } // Point E return b; }

Fill in each box of the table below with one of the following words: ALWAYS, NEVER or SOMETIMES. (You may abbreviate these choices as A, N, and S.) a != 0

c % 2 == 0

b > 0

Point A Point B Point C Point D Point E

5 of 8


6. Programming Write a static method named graduation that takes a student's GPA, total credit count, and honors credit count as parameters, and returns a String representing that student's graduation status. The total credit count already includes the honors credits. The graduation status to return is determined by the following rules: 

Students must have completed at least 180 credits with a GPA of at least 2.0 to graduate. A student who does not meet both of these constraints should receive a return value of "not graduating".

Students who do have enough credits to graduate and sufficiently high GPAs will receive one of four return values depending on the GPA and number of honors credits: o

All students with GPAs between 2.0 and 3.6 receive a return value of "graduating".

o

Students with fewer than 15 honors credits receive a return of "cum laude" if their GPA is at least 3.6 but less than 3.8, and a return of "magna cum laude" if their GPA is at least 3.8.

o

Students with 15 or more honors credits receive a return of "magna cum laude" if their GPA is at least 3.6 but less than 3.8, and a return of "summa cum laude" if their GPA is at least 3.8.

Here are some example calls to the method and their resulting return values:

Call

Value Returned

graduation(3.87, 178, 16) graduation(1.5, 199, 30) graduation(2.7, 380, 50) graduation(3.6, 180, 14) graduation(3.62, 200, 20) graduation(3.93, 185, 0) graduation(3.85, 190, 15)

"not graduating" "not graduating" "graduating" "cum laude" "magna cum laude" "magna cum laude" "summa cum laude"

You may assume that the GPA will be between 0.0 and 4.0 and that both credit counts will be non-negative integers.

6 of 8


7. Programming Write a static method named cheerleader that accepts two integer parameters lines and cheers and prints a series of "cheer" lines at increasing levels of indentation. The first parameter represents the number of lines of output to print, and the second represents the number of "cheers" per line. For example, the call of cheerleader(2, 4) means that you should print 2 lines of output, each containing 4 "cheers." A "cheer" is an occurrence of the word "Go" in the output. Neighboring cheers are separated by the word "Team", so 1 cheer is printed as "Go", 2 cheers as "Go Team Go", 3 cheers are printed as "Go Team Go Team Go", and so on. The lines you print should be displayed at increasing levels of indentation. The first line displayed should have no indentation, but each following line should be intended by 3 spaces more than the one before it. In other words, the 2nd line of output should be indented by 3 spaces, the 3rd line by 6 spaces, and so on. You may assume that both parameters passed your method will have values of at least 1. The following calls demonstrate your method's behavior. Your method should match this output format exactly:

Call Output

cheerleader(2, 1); Go Go

cheerleader(4, 3); Go Team Go Team Go Go Team Go Team Go Go Team Go Team Go Go Team Go Team Go

cheerleader(2, 4); Go Team Go Team Go Team Go Go Team Go Team Go Team Go

7 of 8


8. Programming Write a static method named randomRects that calculates and displays the area of randomly-generated rectangles. The width and height of each rectangle should be a randomly generated integer between 1 and 10 inclusive. Your method should keep generating random rectangles until an increasing sequence of four areas is printed. In other words, if the last four rectangles generated have areas of a1, a2, a3 and a4 such that a1 < a2 < a3 < a4, the method should print the final message and stop. So your method will generate at least 4 total rectangles but possibly many more, stopping only when it sees 4 in a row with areas in increasing order. The following calls demonstrate your method's behavior. Your method should match this output format exactly:

Call Output

randomRects(); w: 5, h: 6, area: 30 w: 10, h: 5, area: 50 w: 2, h: 8, area: 16 w: 4, h: 4, area: 16 w: 2, h: 9, area: 18 w: 8, h: 3, area: 24 w: 7, h: 2, area: 14 w: 3, h: 10, area: 30 w: 7, h: 9, area: 63 w: 9, h: 8, area: 72 Four rectangles of increasing area.

randomRects(); w: 5, h: 2, area: 10 w: 6, h: 5, area: 30 w: 7, h: 6, area: 42 w: 8, h: 10, area: 80 Four rectangles of increasing area.

8 of 8


Sample Midterm Exam #4 Key Also check out Practice-It to test solving these problems or to type in your own solution to see if it works! 1. Expressions Expression 5 * 2 * 4 - 3 * 3 29 / 4 / 2.0 + 18 / 5 + 1.5 30 % (4 + 3) + 16 % 20 !(23 + 2 * 2 <= 27) && 5 % 2 == 1 1 + 1 + "(8 - 2)" + (8 - 2) + 1 + 1

Value 31 8.0 18 false "2(8 - 2)611"

2. Parameter Mystery 10 is roughly 4 plus 3 5 is roughly 10 plus 3 17 is roughly 2 plus 6 3 is roughly 17 plus 40 3 is roughly 7 plus 4

3. If/Else Simulation Method Call mystery(4); mystery(30); mystery(-6); mystery(18); mystery(15);

Output 4 7 30 16 -6 -13 18 10 15 8

4. While Loop Simulation Method Call mystery(-2, -6); mystery(2, 3); mystery(4, 8); mystery(5, 40); mystery(10, 31);

Output 0 0 1 1 0 3 5 6 0 4 7 9 10 10 0 9 17 24 30

5. Assertions

Point A Point B Point C Point D Point E

a != 0 SOMETIMES ALWAYS ALWAYS SOMETIMES NEVER

c % 2 == 0 ALWAYS SOMETIMES NEVER SOMETIMES SOMETIMES

b > 0 NEVER SOMETIMES NEVER SOMETIMES SOMETIMES


6. Programming (two solutions shown) public static String graduation(double gpa, int credits, int honorsCredits) { if (credits >= 180 && gpa >= 2.0) { if (honorsCredits >= 15 && gpa >= 3.8) { return "summa cum laude"; } else if ((honorsCredits >= 15 && gpa >= 3.6) || gpa >= 3.8) { return "magna cum laude"; } else if (gpa >= 3.6) { return "cum laude"; } else { return "graduating"; } } else { return "not graduating"; } } public static String graduation(double gpa, int credits, int honorsCredits) { if (credits < 180 || gpa < 2.0) { return "not graduating"; } else if (honorsCredits >= 15 && gpa >= 3.8) { return "summa cum laude"; } else if (honorsCredits >= 15 && gpa >= 3.6 || gpa >= 3.8) { return "magna cum laude"; } else if (gpa >= 3.6) { return "cum laude"; } else { return "graduating"; } }


7. Programming (three solutions shown) public static void cheerleader(int lines, int cheers) { for (int line = 0; line < lines; line++) { for (int space = 1; space <= line * 3; space++) { System.out.print(" "); } System.out.print("Go"); for (int cheer = 2; cheer <= cheers; cheer++) { System.out.print(" Team Go"); } System.out.println(); } } public static void cheerleader(int lines, int cheers) { String indent = ""; for (int line = 1; line <= lines; line++) { System.out.print(indent); for (int cheer = 1; cheer <= cheers - 1; cheer++) { System.out.print("Go Team "); } System.out.println("Go"); indent += " "; } } public static void cheerleader(int lines, int cheers) { for (int line = 1; line <= lines; line++) { for (int space = 1; space <= line - 1; space++) { System.out.print(" "); } for (int cheer = 1; cheer <= cheers - 1; cheer++) { System.out.print("Go Team "); } System.out.println("Go"); } }


8. Programming (three solutions shown) public static void randomRects() { Random r = new Random(); int last = 100; // can also be 0 int count = 0; while (count < 4) { int w = r.nextInt(10) + 1; int h = r.nextInt(10) + 1; System.out.println("w: " + w + ", h: " + h + ", area: " + w * h); if (last < w * h) { count++; } else { count = 1; // need to count first rect in sequence } last = w * h; } System.out.println("Four rectangles of increasing area."); } public static void randomRects() { Random r = new Random(); int a1 = 0, a2 = 0, a3 = 0, a4 = 0; while (a1 == 0 || a1 >= a2 || a2 >= a3 || a3 >= a4) { int w = r.nextInt(10) + 1; int h = r.nextInt(10) + 1; a1 = a2; a2 = a3; a3 = a4; a4 = w * h; System.out.println("w: " + w + ", h: " + h + ", area: " + a4); } System.out.println("Four rectangles of increasing area."); } public static void randomRects() { Random r = new Random(); int area = 0; int last = 0; int count = 0; while (count != 4) { int w = r.nextInt(10) + 1; int h = r.nextInt(10) + 1; area = w * h; if (area <= last) { count = 1; } else { count++; } System.out.println("w: " + w + ", h: " + h + ", area: " + area); last = area; } System.out.println("Four rectangles of increasing area."); }


Sample Midterm Exam #5 1. Expressions For each expression in the left-hand column, indicate its value in the right-hand column. Be sure to list a constant of appropriate type. (e.g., 7.0 rather than 7 for a double, Strings in quotes, true or false for a boolean). Expression

Value

3 + 4 * 5 / 2

_____________________________

13 % 5 + 43 % (11 % 3)

_____________________________

1.5 * 3.0 + 25.0 / 10.0

_____________________________

7 / 2 != 123 / 12 % 7

_____________________________

5 / 2 + 123 / 10 / 10.0

_____________________________

5 + 2 + "(1 + 1)" + 4 + 2 * 3

_____________________________

1 of 8


2. Parameter Mystery At the bottom of the page, write the output produced by the following program, as it would appear on the console. public class ParameterMystery { public static void main(String[] args) { String p = "cause"; String q = "support"; String r = "troops"; String support = "hillary"; String cause = "rudy"; troops(p, q, r); troops(q, r, p); troops(support, p, cause); troops(r, "p", support); troops(q, "cause", q); } public static void troops(String r, String p, String q) { System.out.println(q + " gave " + r + " to the " + p); } }

2 of 8


3. If/Else Simulation For each call below to the following method, write the output that is produced, as it would appear on the console: public static void mystery(int n) { System.out.print(n + " "); if (n > 10) { n = n / 2; } else { n = n + 7; } if (n * 2 < 25) { n = n + 10; } System.out.println(n); }

Method Call

Output

mystery(40);

____________________________________________

mystery(8);

____________________________________________

mystery(0);

____________________________________________

mystery(12);

____________________________________________

mystery(20);

____________________________________________

3 of 8


4. While Loop Simulation For each call below to the following method, write the value that is returned: public static int mystery(int x) { int a = 1; int c = 0; while (x > 0) { a = x % 2; if (a == 1) { c++; } x = x / 2; } return c; }

Method Call

Value Returned

mystery(2);

____________________________________________

mystery(-1);

____________________________________________

mystery(7);

____________________________________________

mystery(18);

____________________________________________

mystery(43);

____________________________________________

4 of 8


5. Assertions For the following method, identify each of the three assertions in the table below as being either ALWAYS true, NEVER true or SOMETIMES true / sometimes false at each labeled point in the code. (can abbreviate as A/N/S) public static int threeHeads() { Random rand = new Random(); int flip = 1; int heads = 0; int count = 0;

// Counts coin tosses till we get heads 3x in a row.

// Point A while (heads < 3) { // Point B flip = rand.nextInt(2); // flip coin if (flip == 0) { // heads heads++; // Point C } else { // tails // Point D heads = 0; } count++; }

}

// Point E return count; flip == 0

heads == 0

flip > heads

Point A Point B Point C Point D Point E

5 of 8


6. Programming Write a static method named printTwoDigit that accepts a Random object and an integer n as parameters and that prints a series of n randomly generated two-digit numbers. The method should use the Random object to select numbers in the range of 10 to 99 inclusive where each number is equally likely to be chosen. After displaying each number that was produced, the method should indicate whether the number 42 was ever selected ("we saw a 42!") or not ("no 42 was seen."). You may assume that the value of n passed is at least 0. The following table shows two sample calls and their output:

Call Output

Random r = new Random(); printTwoDigit(r, 4); next = 52 next = 10 next = 96 next = 86 no 42 was seen.

Random r = new Random(); printTwoDigit(r, 7); next = 83 next = 29 next = 42 next = 22 next = 91 next = 36 next = 73 we saw a 42!

6 of 8


7. Programming (15 points) In this question, we'll address the following problem: Can a cash register containing a given amount of pennies (1cent coins) and a given amount of nickels (5-cent coins) give a customer a given exact amount of cents of change? For example, if there are 3 pennies and 5 nickels in the cash register, is it possible to give exactly 19 cents of change? (No.) If there are 2 pennies and 7 nickels in the register, is it possible to give exactly 26 cents of change? (Yes.) Write a static method named canMakeChange that accepts three integer parameters representing the number of pennies in the cash register, the number of nickels in the cash register, and the desired amount of change to make. The method should return true if the coins in the register can produce this exact amount of change, and false if not. The coins in the register must be able to exactly produce the desired amount of change in order to return true; for example, if the register contains 0 pennies and 100 nickels, it is not able to exactly produce 8 cents of change. The following are several sample calls to your method and the values they should return. You may assume that no negative parameter values are passed, but otherwise your method should work with any values passed.

Call

Value Returned

canMakeChange(3, 4, 12) canMakeChange(1, 5, 26) canMakeChange(24, 2, 31) canMakeChange(87, 19, 134) canMakeChange(0, 0, 0)

// 3 pennies, 4 nickels, 12c change? // 1 penny, 5 nickels, 26c change? // 24 pennies, 2 nickels, 31c change? // 87 pennies, 19 nickels, 134c change? // 0 pennies, 0 nickels, 0c change?

true true true true true

canMakeChange(1, 1, 9) canMakeChange(2, 7, 8) canMakeChange(4, 3, 39) canMakeChange(3, 80, 14)

// // // //

false false false false

1 penny, 1 nickel, 2 pennies, 7 nickels, 4 pennies, 3 nickels, 3 pennies, 80 nickels,

9c change? 8c change? 39c change? 14c change?

7 of 8


8. Programming Write a static method named consecutiveDigits that accepts an integer n as a parameter and that returns the highest number of consecutive digits in a row from n that have the same value. For example, the number 3777785 has four consecutive occurrences of the number 7 in a row, so the call consecutiveDigits(3777785) should return 4. For many numbers the answer will be 1 because they don't have any adjacent digits that match. Below are sample calls on the method. You are not allowed to use a String to solve this problem. You may assume that the value passed to the method is greater than or equal to 0.

Call consecutiveDigits(0) consecutiveDigits(18) consecutiveDigits(394) consecutiveDigits(99) consecutiveDigits(8229)

Returns 1 1 1 2 2

Call consecutiveDigits(8823) consecutiveDigits(777) consecutiveDigits(82888) consecutiveDigits(7111171) consecutiveDigits(233333888)

Returns 2 3 3 4 5

8 of 8


Sample Midterm Exam #5 Key Also check out Practice-It to test solving these problems or to type in your own solution to see if it works! 1. Expressions Expression 3 + 4 * 5 / 2 13 % 5 + 43 % (11 % 3) 1.5 * 3.0 + 25.0 / 10.0 7 / 2 != 123 / 12 % 7 5 / 2 + 123 / 10 / 10.0 5 + 2 + "(1 + 1)" + 4 + 2 * 3

Value 13 4 7.0 false 3.2 "7(1 + 1)46"

2. Parameter Mystery troops gave cause to the support cause gave support to the troops rudy gave hillary to the cause hillary gave troops to the p support gave support to the cause

3. If/Else Simulation Method Call

Output

mystery(40); mystery(8); mystery(0); mystery(12); mystery(20);

40 20 8 15 0 17 12 16 20 20

4. While Loop Simulation Method Call

Value Returned

mystery(2); mystery(-1); mystery(7); mystery(18); mystery(43);

1 0 3 2 4

5. Assertions

Point A Point B Point C Point D Point E

flip == 0 NEVER SOMETIMES ALWAYS NEVER ALWAYS

heads == 0 ALWAYS SOMETIMES NEVER SOMETIMES NEVER

flip > heads ALWAYS SOMETIMES NEVER SOMETIMES NEVER

1 of 3


6. Programming (one solution shown) public static void printTwoDigit(Random r, int n) { boolean seen42 = false; for (int i = 1; i <= n; i++) { int number = r.nextInt(90) + 10; System.out.println("next = " + number); if (number == 42) { seen42 = true; } } if (seen42) { System.out.println("we saw a 42!"); } else { System.out.println("no 42 was seen."); } }

7. Programming (six solutions shown) public static boolean canMakeChange(int pennies, int nickels, int cents) { if (cents % 5 > pennies) { return false; } else if (pennies + 5 * nickels < cents) { return false; } else { return true; } } public static boolean canMakeChange(int pennies, int nickels, int cents) { while (cents >= 5 && nickels > 0) { cents -= 5; nickels--; } while (cents > 0 && pennies > 0) { cents--; pennies--; } return cents == 0; } public static boolean canMakeChange(int pennies, int nickels, int cents) { for (int p = 0; p <= pennies; p++) { for (int n = 0; n <= nickels; n++) { if (p + 5 * n == cents) { return true; } } } return false; } public static boolean canMakeChange(int pennies, int nickels, int cents) { if (nickels * 5 >= cents) { return (pennies >= cents % 5); // enough nickels to cover all except % 5 part } else { return (pennies >= cents - nickels * 5); // not enough nickels; need pennies } } public static boolean canMakeChange(int pennies, int nickels, int cents) { cents -= Math.min(nickels * 5, cents - cents % 5); return cents - pennies <= 0; } public static boolean canMakeChange(int pennies, int nickels, int cents) { return (pennies >= cents % 5) && (pennies + 5 * nickels >= cents); }

2 of 3


8. Programming (one solution shown) public static int consecutiveDigits(int n) { int count = 1; int last = -1; // dummy value; anything but 0-9 int max = 1; while (n != 0) { if (n % 10 == last) { count++; } else { count = 1; } if (count > max) { // or, max = Math.max(max, count); max = count; } last = n % 10; n = n / 10; } return max; }

3 of 3


Sample Midterm Exam #5

1. Expressions For each expression in the left-hand column, indicate its value in the right-hand column. Be sure to list a constant of appropriate type and capitalization. e.g., 7 for an int, 7.0 for a double, "hello" for a String, true or false for a boolean. Expression

Value

-(6 + 3 - 2 * 3)

_____________________________

15 % 6 + 5 % 5 + 12 % 7 % 3

_____________________________

9 / 2 / 2.0 + 9 / 2.0 / 2

_____________________________

5 + 6 + "7" + 8 + 9 + 2 * 3

_____________________________

!(3 < 7 && -1 != 8)

_____________________________

2. Parameter Mystery At the bottom of the page, write the output produced by the following program, as it would appear on the console. (Though the program uses words related to arithmetic, the output does not necessarily follow the rules of addition.)

public class ParameterMystery { public static void main(String[] args) { String i = "j"; int j = -1; int k = 2; String x = "5"; int y = 7; silly(k, i, j); silly(y, x, k); silly(k, "y", 4); silly(j + 1, x + 1, j); } public static void silly(int k, String i, int j) { System.out.println(j + " + " + k + " + " + i); } }

1 of 6


3. If/Else Simulation For each call below to the following method, write the output that is produced, as it would appear on the console:

public static void ifElseMystery(int a, int b) { if (a < b) { a = a * 2; } if (a > b) { a = a - 10; } else { b++; } System.out.println(a + " " + b); }

Method Call

Output

ifElseMystery(10, 3);

____________________________________________

ifElseMystery(6, 6);

____________________________________________

ifElseMystery(3, 4);

____________________________________________

ifElseMystery(4, 20);

____________________________________________

2 of 6


4. While Loop Simulation For each call below to the following method, write the output that is produced, as it would appear on the console:

public static void whileMystery(int x, int y, int z) { while (x < z || y < z) { x = x + y; y = y * 2; System.out.print(x + " " + y + " "); } System.out.println(); }

Method Call

Output

whileMystery(0, 5, 10);

____________________________________________

whileMystery(4, 2, 12);

____________________________________________

whileMystery(10, 1, 14);

____________________________________________

3 of 6


5. Assertions For each of the five points labeled by comments, identify each of the assertions in the table below as either being always true, never true, or sometimes true / sometimes false.

public static int randomWalk(int steps) { Random rand = new Random(); int x = 0; int r = rand.nextInt(2); // Point A while (steps > 0 || x == 0) { // Point B if (r == 0) { x++; // Point C } else { x = 0; // Point D } steps--; r = rand.nextInt(2); } // Point E return x; } Fill in each box below with one of ALWAYS, NEVER or SOMETIMES. (You may abbreviate them as A, N, or S.)

steps > 0

x > 0

r > 0

Point A Point B Point C Point D Point E

4 of 6


6. Programming Write a static method hopscotch that shows a sequence of numbers similar to the appearance of a hopscotch board. (Hopscotch is a "hopping" game played by children.) For this problem, a hopscotch board is an increasing sequence of numbers in lines in an alternating pattern. Odd lines contain a single number indented by 3 spaces. Even lines contain a pair of numbers with the first number not indented, followed by 5 spaces, followed by the second number. Your method should accept a parameter representing the number of "hops" worth of numbers to display. A board of 0 "hops" shows only the number 1, indented by 3 spaces. A "hop" is defined as a trio of additional numbers spread across 2 additional lines, following the pattern described previously. So for example, 1 hop means to show the numbers 2-3-4 to the board in the pattern shown below. 2 hops means to show the numbers 2-3-4, 5-6-7 on the board. 3 hops means to show 2-3-4, 5-6-7, 8-9-10, and so on. Assume that the number of hops passed will be at least 0. Here are some example calls to the method and their resulting console output:

Call Output

hopscotch(0); 1

hopscotch(1); 1 2 3 4

hopscotch(2); 1 2 3 4 5 6 7

hopscotch(3); 1 2 3 4 5 6 7 8 9 10

hopscotch(5); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

5 of 6


7. Programming Write a static method named containsBothDigits that accepts three integer parameters a, b, and c. Assume that a is a positive integer (greater than 0) and that b and c are single-digit numbers from 0-9 inclusive. Your method should return true if a contains both b and c at among its digits, and false otherwise. For example, the number 433407 contains 4, 3, 0, and 7 as its unique digit values, so a call to your method of containsBothDigits(433407, 7, 3) should return true. If b and c are the same number, your method should return true if that digit appears at least once among the digits; in other words, the same digit from a could match both b and c. So for example, a call of containsBothDigits(433407, 7, 7) should return true. Note that the digit b or c might appear more than once in a, as with 433407 containing two 3s. The following table lists some additional calls to your method and their expected return values:

Call

Value Returned

containsBothDigits(12345, 2, 5) containsBothDigits(3004955, 3, 0) containsBothDigits(1650, 6, 6) containsBothDigits(12198, 1, 7) containsBothDigits(42, 9, 2) containsBothDigits(904487, 2, 6) containsBothDigits(8, 2, 3)

true true true false false false false

Reason 12345 contains the digits 2 and 5 3004955 contains the digits 3 and 0 1650 contains the digit 6 12198 does not contain the digit 7 42 does not contain the digit 9 904487 does not contain the digit 2 or 6 8 does not contain the digit 2 or 3

Note: You may not use a String to solve this problem.

6 of 6


Sample Midterm Exam #6 Key Also check out Practice-It to test solving these problems or to type in your own solution to see if it works! 1. Expressions Expression -(6 + 3 - 2 * 3) 15 % 6 + 5 % 5 + 12 % 7 % 3 9 / 2 / 2.0 + 9 / 2.0 / 2 5 + 6 + "7" + 8 + 9 + 2 * 3 !(3 < 7 && -1 != 8)

Value -3 5 4.25 "117896" false

2. Parameter Mystery -1 + 2 + j 2 + 7 + 5 4 + 2 + y -1 + 0 + 51

3. If/Else Simulation Method Call ifElseMystery(10, 3); ifElseMystery(6, 6); ifElseMystery(3, 4); ifElseMystery(4, 20);

Output 0 3 6 7 -4 4 8 21

4. While Loop Simulation Method Call whileMystery(0, 5, 10); whileMystery(4, 2, 12); whileMystery(10, 1, 14);

Output 5 10 15 20 6 4 10 8 18 16 11 2 13 4 17 8 25 16

5. Assertions

Point A Point B Point C Point D Point E

steps > 0 SOMETIMES SOMETIMES SOMETIMES SOMETIMES NEVER

x > 0 NEVER SOMETIMES ALWAYS NEVER ALWAYS

r > 0 SOMETIMES SOMETIMES NEVER ALWAYS SOMETIMES


6. Programming There are many ways to solve any programming problem. Here are some common correct solutions we saw: public static void hopscotch(int hops) { System.out.println(" 1"); for (int i = 1; i <= hops; i++) { System.out.println((3 * i) + " " + (3 * i + 1)); System.out.println(" " + (3 * i + 2)); } } public static void hopscotch(int hops) { for (int i = 0; i < hops; i++) { System.out.println(" " + (3 * i + 1)); System.out.println((3 * i + 2) + " " + (3 * i + 3)); } System.out.println(" " + (3 * hops + 1)); } public static void hopscotch(int hops) { for (int i = 1; i <= hops * 3 + 1; i++) { if (i % 3 == 1) { System.out.println(" " + i); } else if (i % 3 == 2) { System.out.print(i); } else { System.out.println(" " + i); } } } public static void hopscotch(int hops) { System.out.println(" 1"); int num = 2; for (int i = 1; i <= hops; i++) { System.out.println(num + " " + (num + 1)); System.out.println(" " + (num + 2)); num = num + 3; } } public static void hopscotch(int hops) { System.out.println(" 1"); int num = 2; while (num <= 3 * hops + 1) { System.out.print(num); num++; System.out.println(" " + num); num++; System.out.println(" " + num); num++; } } public static void hopscotch(int hops) { int count = 1; for (int i = 1; i <= 2 * hops + 1; i++) { if (i % 2 == 1) { System.out.println(" " + count); count++; } else { System.out.println(count + " " + (count + 1)); count = count + 2; } } } public static void hopscotch(int hops) { int num = 1; System.out.println(" " + num++); for (int i = 1; i <= hops; i++) System.out.println(num++ + " " + num++ + "\n " + num++); }


7. Programming public static boolean containsBothDigits(int a, int b, int c) { int bCount = 0; int cCount = 0; while (a != 0) { int digit = a % 10; a = a / 10; if (digit == b) { bCount++; } if (digit == c) { cCount++; } }

}

if (bCount > 0 && cCount > 0) { return true; } else { return false; }

public static boolean containsBothDigits(int a, int b, int c) { boolean foundB = false; boolean foundC = false; while (a != 0) { int digit = a % 10; a = a / 10; if (digit == b) { foundB = true; } if (digit == c) { foundC = true; } } }

return foundB && foundC;

public static boolean containsBothDigits(int a, int b, int c) { int copyA = a; int count = 0; while (a != 0) { if (a % 10 == b) { count++; } a = a / 10; }

// look for b

a = copyA; // restore a while (a != 0) { // look for c if (a % 10 == c && count > 0) { return true; } a = a / 10; } }

return false;


public static boolean containsBothDigits(int a, int b, int c) { int count = 0; while (a != 0) { int digit = a % 10; a = a / 10; if (digit == b) { count++; b = -1; // so that it won't be counted twice } if (digit == c) { count++; c = -1; // so that it won't be counted twice } }

}

if (count == 2) { return true; } else { return false; }

public static boolean containsBothDigits(int a, int b, int c) { boolean foundB = false, foundC = false; while (a != 0) { foundB = foundB || a % 10 == b; foundC = foundC || a % 10 == c; a /= 10; } return foundB && foundC; } public static boolean containsBothDigits(int a, int b, int c) { return containsDigit(a, b) && containsDigit(a, c); } public static boolean containsDigit(int a, int b) { while (a != 0) { if (a % 10 == b) { return true; } a = a / 10; } return false; }


Sample Midterm Exam #10

1. Expressions For each expression at left, indicate its value in the right column. List a value of appropriate type and capitalization. e.g., 7 for an int, 7.0 for a double, "hello" for a String, true or false for a boolean. Expression

Value

1 + 2 * 3 * 4 - 5 * 2

_____________________________

2 + "(int)2.0" + 2 * 2 + 2

_____________________________

15 % 3 == 0 && !(3 > 2 && 1 > 3)

_____________________________

1 / 2 + -(157 / 10 / 10.0) + 9.0 * 1 / 2

_____________________________

24 % 5 + 9 % (6 % 4)

_____________________________

2. Parameter Mystery At the bottom of the page, write the output produced by the following program, as it would appear on the console.

public class ParameterMystery { public static void main(String[] args) { String literal = "8"; String brace = "semi"; String paren = brace; String semi = "brace"; String java = "42"; param(java, brace, semi); param(literal, paren, java); param(brace, semi, "literal"); param("cse", literal + 4, "1"); } public static void param(String semi, String java, String brace) { System.out.println(java + " missing a " + brace + " and " + semi); } }

1 of 7


3. If/Else Simulation For each call below to the following method, write the output that is produced, as it would appear on the console:

public static void ifElseMystery(int a, int b, int c) { if (a < b && a < c) { a = a + c; c++; } else if (a >= b) { a = a - b; b--; } if (a >= b && a >= c) { a++; c++; } System.out.println(a + " " + b + " " + c); }

Method Call

Output

ifElseMystery(2, 10, 3);

____________________________________________

ifElseMystery(8, 6, 1);

____________________________________________

ifElseMystery(4, 6, 7);

____________________________________________

ifElseMystery(20, 5, 5);

____________________________________________

2 of 7


4. While Loop Simulation For each call below to the following method, write the output that is produced, as it would appear on the console:

public static void whileMystery(int x, int y) { int z = 0; while (x % y != 0) { x = x / y; z++; System.out.print(x + ", "); } System.out.println(z); }

Method Call

Output

whileMystery(25, 2);

____________________________________________

whileMystery(10345, 10);

____________________________________________

whileMystery(63, 2);

____________________________________________

3 of 7


5. Assertions For each of the five points labeled by comments, identify each of the assertions in the table below as either being always true, never true, or sometimes true / sometimes false. (You may abbreviate them as A, N, or S.)

public static int count(int n) { int even = 0; int odd = 0; // Point A while (n != 0 && even <= odd) { if (n % 2 == 0) { even++; // Point B } else { // Point C odd++; } n = n / 2; // Point D } // Point E return even - odd; }

n == 0

even <= odd

n % 2 == 0

Point A Point B Point C Point D Point E

4 of 7


6. Programming Write a static method named longestName that reads names typed by the user and prints the longest name (the name that contains the most characters) in the format shown below. Your method should accept a console Scanner and an integer n as parameters and should then prompt for n names. The longest name should be printed with its first letter capitalized and all subsequent letters in lowercase, regardless of the capitalization the user used when typing in the name. If there is a tie for longest between two or more names, use the tied name that was typed earliest. Also print a message saying that there was a tie, as in the right log below. It's possible that some shorter names will tie in length, such as DANE and Erik in the left log below; but don't print a message unless the tie is between the longest names. You may assume that n is at least 1, that each name is at least 1 character long, and that the user will type single-word names consisting of only letters. The following table shows two sample calls and their output.

Call

Scanner console = new Scanner(System.in); longestName(console, 5);

Scanner console = new Scanner(System.in); longestName(console, 7);

Output

name #1? roy name #2? DANE name #3? Erik name #4? sTeFaNiE name #5? LaurA Stefanie's name is longest

name #1? TrEnt name #2? rita name #3? JORDAN name #4? craig name #5? leslie name #6? YUKI name #7? TaNnEr Jordan's name is longest (There was a tie!)

5 of 7


(extra writing space for Problem #6)

6 of 7


7. Programming Write a static method named largerDigits that accepts two integer parameters a and b and returns a new integer c where each digit of c gets its value from the larger of a's and b's digit in the same place. That is, the ones digit of c is the larger of the ones digit of a and the ones digit of b, and the tens digit of c is the larger of the tens digit of a and the tens digit of b, and so on. You may assume that a and b are positive integers (greater than 0). For example, suppose a is 603452384 and b is 921782. Their digits would be combined as follows to produce c: a 603452380 b 920784 -----------------c 952784

(return value)

Notice that if a particular digit place is absent from one number or the other, such as the 603 at the start of a above, no digit is carried over to c. The following table lists some more calls to your method and their expected return values:

Call

Value Returned

largerDigits(172, 312) largerDigits(21, 3) largerDigits(90, 38906735) largerDigits(56002, 123321) largerDigits(11223, 4466) largerDigits(12345, 12345) largerDigits(1, 34892)

372 3 95 56322 4466 12345 2

Hint: If you are building a result number, you may need to use Math.pow or accumulate a multiplier with each digit. You may not use a String to solve this problem.

7 of 7


Sample Midterm Exam #10 Key Also check out Practice-It to test solving these problems or to type in your own solution to see if it works! 1. Expressions Expression 1 + 2 * 3 * 4 - 5 * 2 2 + "(int)2.0" + 2 * 2 + 2 15 % 3 == 0 && !(3 > 2 && 1 > 3) 1 / 2 + -(157 / 10 / 10.0) + 9.0 * 1 / 2 24 % 5 + 9 % (6 % 4)

Value 15 "2(int)2.042" true 3.0 5

2. Parameter Mystery semi missing a brace and 42 semi missing a 42 and 8 brace missing a literal and semi 84 missing a 1 and cse

3. If/Else Simulation Method Call ifElseMystery(2, 10, 3); ifElseMystery(8, 6, 1); ifElseMystery(4, 6, 7); ifElseMystery(20, 5, 5);

Output 5 10 4 2 5 1 12 6 9 16 4 6

4. While Loop Simulation Method Call whileMystery(25, 2); whileMystery(10345, 10); whileMystery(63, 2);

Output 12, 1 1034, 103, 10, 3 31, 15, 7, 3, 1, 0, 6

5. Assertions

Point A Point B Point C Point D Point E

n == 0 SOMETIMES NEVER NEVER SOMETIMES SOMETIMES

even <= odd ALWAYS SOMETIMES ALWAYS SOMETIMES SOMETIMES

n % 2 == 0 SOMETIMES ALWAYS NEVER SOMETIMES SOMETIMES


6. Programming There are many ways to solve any programming problem. Here are three common correct solutions we saw: // longer solution; pull first post out of fencepost public static void longestName(Scanner console, int names) { System.out.print("name #1? "); String longest = console.next(); int count = 1; for (int i = 2; i <= names; i++) { System.out.print("name #" + i + "? "); String name = console.next(); if (name.length() == longest.length()) { count++; } if (name.length() > longest.length()) { longest = name; count = 1; } } String fixedName = longest.substring(0, 1).toUpperCase(); fixedName = fixedName + longest.substring(1).toLowerCase(); System.out.println(fixedName + "'s name is longest"); if (count > 1) { System.out.println("(There was a tie!)"); } } // shorter solution; boolean flag public static void longestName(Scanner console, int names) { String longest = ""; boolean tie = false; for (int i = 1; i <= names; i++) { System.out.print("name #" + i + "? "); String name = console.next(); if (name.length() > longest.length()) { longest = name; tie = false; } else if (name.length() == longest.length()) { tie = true; } } longest = longest.substring(0, 1).toUpperCase() + longest.substring(1).toLowerCase(); System.out.println(longest + "'s name is longest"); if (tie) { System.out.println("(There was a tie!)"); } } // store longest two strings and compare public static void longestName(Scanner console, int n) { String longest = ""; String longest2 = ""; for (int i = 1; i <= n; i++) { System.out.print("name #" + i + "? "); String name = console.next(); if (name.length() > longest.length()) { longest = name; longest2 = name; } else if (name.length() == longest.length()) { longest2 = name; } } String capitalized = longest.toUpperCase().charAt(0) + longest.toLowerCase().substring(1); System.out.println(capitalized + "'s name is longest"); if (!longest.equalsIgnoreCase(longest2)) { System.out.println("(There was a tie!)"); } }


7. Programming // count digits, use Math.pow to scale up; use if/else to compare public static int largerDigits(int a, int b) { int digits = 0; int result = 0; while (a != 0 && b != 0) { if (a % 10 > b % 10) { result += a % 10 * (int) Math.pow(10, digits); } else { result += b % 10 * (int) Math.pow(10, digits); } a = a / 10; b = b / 10; digits++; } return result; } // cumulative multiplier and Math.max public static int largerDigits(int a, int b) { int multiplier = 1; int result = 0; while (a != 0 && b != 0) { int digit = Math.max(a % 10, b % 10); result += digit * multiplier; a = a / 10; b = b / 10; multiplier = multiplier * 10; } return result; }


public static boolean containsBothDigits(int a, int b, int c) { int count = 0; while (a != 0) { int digit = a % 10; a = a / 10; if (digit == b) { count++; b = -1; // so that it won't be counted twice } if (digit == c) { count++; c = -1; // so that it won't be counted twice } }

}

if (count == 2) { return true; } else { return false; }

public static boolean containsBothDigits(int a, int b, int c) { boolean foundB = false, foundC = false; while (a != 0) { foundB = foundB || a % 10 == b; foundC = foundC || a % 10 == c; a /= 10; } return foundB && foundC; } public static boolean containsBothDigits(int a, int b, int c) { return containsDigit(a, b) && containsDigit(a, c); } public static boolean containsDigit(int a, int b) { while (a != 0) { if (a % 10 == b) { return true; } a = a / 10; } return false; }


Sample Midterm Exam #11

1. Expressions For each expression at left, indicate its value in the right column. List a value of appropriate type and capitalization. e.g., 7 for an int, 7.0 for a double, "hello" for a String, true or false for a boolean. Expression

Value

8 - 2 * 3 + (5 - 1)

_____________________________

10 - 2 + "6" + 3 * 25 + (33 - 3) + 9

_____________________________

19 % 8 == 3 && 2 == 7 / 3

_____________________________

1.0 / 2 + (4.5 - 1.5) - 7 / 2

_____________________________

2. Parameter Mystery At the bottom of the page, write the output produced by the following program, as it would appear on the console: public class ParameterMystery { public static void main(String[] args) { String butters = "kenny"; String friends = "butters"; String kenny = "friends"; String kyle = "stan"; String ike = "cartman"; stotch(kenny, friends, butters); stotch(ike, friends, kyle); stotch(kyle, ike, "ike"); stotch(friends, "kyle", kenny); } public static void stotch(String kenny, String butters, String friends) { System.out.println(butters + " is " + friends + " with " + kenny); } }

1 of 6


3. If/Else Simulation For each call below to the following method, write the output that is produced, as it would appear on the console:

public static void ifElseMystery(int a, int b) { if (a % 2 != 0) { a = a * 2; } if (a > 10) { b++; } else if (a < 10) { a--; b--; } System.out.println(a + " " + b); }

Method Call

Output

ifElseMystery(12, 12);

____________________________________________

ifElseMystery(7, 4);

____________________________________________

ifElseMystery(5, 8);

____________________________________________

ifElseMystery(3, 42);

____________________________________________

2 of 6


4. Assertions For each of the five points labeled by comments, identify each of the assertions in the table below as either being always true, never true, or sometimes true / sometimes false. (You may abbreviate them as A, N, or S.)

public static int funky(int a, int digit) { int count = 0; // Point A while (a != 0) { // Point B if (a % 10 == digit) { count++; // Point C } else if (count > 0) { count--; // Point D } a = a / 10; } // Point E return count; }

a == 0

a % 10 == digit

count > 0

Point A Point B Point C Point D Point E

3 of 6


5. Programming Write a method dominant that accepts three integers as parameters and returns true if any one of the three integers is larger than the sum of the other two integers. The integers might be passed in any order, so the largest value could be any of the three. If no value is larger than the sum of the other two, your method should return false. For example, the call of dominant(4, 9, 2) would return true because 9 is larger than 4 + 2. The call of dominant(5, 3, 7) would return false because none of those three numbers is larger than the sum of the others. You may assume that none of the numbers is negative.

4 of 6


6. Programming Write a method named invest that computes the interest earned on a financial investment. Once per year, the bank pays interest to the investor at a given fixed rate. As the investment earns interest, that interest is added to the investment and therefore the interest begins earning interest of its own ("compounding"). Your method should accept three parameters: the initial amount of the investment in dollars (as a real number such as 1500.0 for $1,500.00), the yearly interest rate (as a real number such as 3.5 for 3.5% interest) and the number of years for which to invest (as an integer such as 6 for 6 years). Your method should print the value of the investment after each year, as well as the total amount of interest earned over all years. For example, an investment of $100.00 at 10% interest for 5 years would lead to this call: invest(100.00, 10.0, 5);

// $100.00 at 10% interest for 5 years

The call would produce the following console output. Dollar amounts print with 2 digits after the decimal. After year 1: $110.00 After year 2: $121.00 After year 3: $133.10 After year 4: $146.41 After year 5: $161.05 Total interest earned: $61.05

Notice that we are not simply adding 10% of $100.00 (or $10.00) each year; that would lead to $50 of total interest earned. The first year adds 10% of $100.00, but the second year adds 10% of $110.00, or $11.00, leading to a total of $121.00. The third year adds 10% of $121.00, or $12.10, leading to a total of $133.10. The interest is cumulative. You may assume that all parameter values passed are non-negative.

5 of 6


7. Programming Write a method named lucky that accepts an integer parameter min and rolls a 6-sided die until it gets four consecutive rolls in a row that have values of min or less. As the method rolls the die it should print each value rolled, and then it should print a message at the end to indicate how many rolls were made. For example, the call of lucky(3); should print output such as the following (though the output would be different on every call because of randomness). Notice that the method stops after rolling 3, 2, 1, and 2 consecutively because these are all values of 3 or less: 5 2 4 6 1 3 5 5 3 2 1 2 Finished after 12 rolls.

A call of lucky(5); should print output such as the following. Notice that it continues rolling until it rolls four consecutive dice rolls produce a value of 5 or less. In this example, those values are 3, 5, 5, and 4. 1 3 6 3 5 5 4 Finished after 7 rolls.

You may assume that the parameter value passed will be between 1 and 6 inclusive.

6 of 6


Sample Midterm Exam #11 Key Also check out Practice-It to test solving these problems or to type in your own solution to see if it works! 1. Expressions Expression 8 - 2 * 3 + (5 - 1) 10 - 2 + "6" + 3 * 25 + (33 - 3) + 9 19 % 8 == 3 && 2 == 7 / 3 1.0 / 2 + (4.5 - 1.5) - 7 / 2

Value 6 "8675309" true 0.5

2. Parameter Mystery butters is kenny with friends butters is stan with cartman cartman is ike with stan kyle is friends with butters

3. If/Else Simulation Method Call ifElseMystery(12, 12); ifElseMystery(7, 4); ifElseMystery(5, 8); ifElseMystery(3, 42);

Output 12 13 14 5 10 8 5 43

4. Assertions

Point A Point B Point C Point D Point E

a == 0 SOMETIMES NEVER NEVER NEVER ALWAYS

a % 10 == digit SOMETIMES SOMETIMES ALWAYS NEVER SOMETIMES

count > 0 NEVER SOMETIMES ALWAYS SOMETIMES SOMETIMES


5. Programming There are many ways to solve any programming problem. Here are some common correct solutions we saw: public static boolean dominant(int a, int b, int c) { return a > b + c || b > a + c || c > a + b; } public static boolean dominant(int a, int b, int c) { if (a + b < c) { return true; } else if (a + c < b) { return true; } else if (b + c < a) { return true; } else { return false; } } public static boolean dominant(int a, int b, int c) { if (c > a + b) { return true; } if (b > a + c) { return true; } if (a > b + c) { return true; } return false; } public static boolean dominant(int a, int b, int c) { int max = Math.max(a, Math.max(b, c)); int min = Math.min(a, Math.min(b, c)); int mid = a + b + c - max - min; if (max > min + mid) { return true; } else { return false; } } public static boolean dominant(int a, int b, int c) { int sum = a + b + c; int max = Math.max(a, Math.max(b, c)); return sum - max < max; } public static boolean dominant(int a, int b, int c) { int big1 = Math.max(a, b); int big2 = Math.max(big1, c); int small1 = Math.min(a, b); int small2 = Math.min(big1, c); return big2 > small1 + small2; } public static boolean dominant(int a, int b, int c) { int max = Math.max(a, Math.max(b, c)); int min = Math.min(a, Math.min(b, c)); int sum = Math.min(Math.min(a+b, a+c), b+c); return a > sum || b > sum || c > sum; }


6. Programming public static void invest(double amount, double rate, int years) { double total = amount; for (int i = 1; i <= years; i++) { total += rate / 100.0 * total; System.out.printf("After year %d: $%.2f\n", i, total); } System.out.printf("Total interest earned: $%.2f\n", total - amount); } public static void invest(double amount, double rate, int years) { double totalInterest = 0.0; for (int i = 1; i <= years; i++) { double interest = rate / 100.0 * amount; amount = amount + interest; totalInterest = totalInterest + interest; System.out.printf("After year %d: $%.2f\n", i, amount); } System.out.printf("Total interest earned: $%.2f\n", totalInterest); }


7. Programming public static void lucky(int min) { Random r = new Random(); int count = 0; int total = 0; while (count < 4) { int die = r.nextInt(6) + 1; System.out.print(die + " "); if (die <= min) { count++; } else { count = 0; } total++; } System.out.println(); System.out.println("Finished after " + total + " rolls."); } public static void lucky(int min) { Random r = new Random(); int count = 0; int rolls = 0; do { rolls++; int die = r.nextInt(6) + 1; if (die <= min) { count++; } else { count = 0; } System.out.print(die + " "); } while (count != 4); System.out.println("\nFinished after " + rolls + " rolls."); }


Sample Midterm Exam #13

1. Expressions For each expression at left, indicate its value in the right column. List a value of appropriate type and capitalization. e.g., 7 for an int, 7.0 for a double, "hello" for a String, true or false for a boolean. Expression

Value

12 / 3 + 5 + 3 * -2

_____________________________

1 + 1 + "(1 + 1)" + 1 + 1

_____________________________

13 / 2 - 38 / 5 / 2.0 + (15 / 10.0)

_____________________________

11 < 3 + 4 || !(5 / 2 == 2)

_____________________________

20 % 6 + 6 % 20 + 6 % 6

_____________________________

2. Parameter Mystery At the bottom of the page, write the output produced by the following program, as it would appear on the console.

public class ParameterMystery { public static void main(String[] args) { int a = 5; int b = 1; int c = 3; int three = a; int one = b + 1; axiom(a, b, c); axiom(c, three, 10); axiom(b + c, one + three, a + one); a++; b = 0; axiom(three, 2, one); } public static void axiom(int c, int b, int a) { System.out.println(a + " + " + c + " = " + b); } }

1 of 8


3. If/Else Simulation For each call below to the following method, write the output that is produced, as it would appear on the console:

public static void ifElseMystery(int x, int y) { if (x == y) { x = x + 11; } else if (x > 2 * y) { x = 0; } if (x == 0 || y > x) { x = x + 2; y = y + 2; } System.out.println(x + " " + y); }

Method Call

Output

ifElseMystery(5, 5);

____________________________________________

ifElseMystery(18, 4);

____________________________________________

ifElseMystery(3, 6);

____________________________________________

2 of 8


4. While Loop Simulation For each call below to the following method, write the output that is produced, as it would appear on the console:

public static void whileMystery(int x, int y) { while (x > 0 && y > 0) { x = x - y; y--; System.out.print(x + " "); } System.out.println(y); } Method Call

Output

whileMystery(7, 5);

____________________________________________

whileMystery(20, 4);

____________________________________________

whileMystery(40, 10);

____________________________________________

3 of 8


5. Assertions For each of the five points labeled by comments, identify each of the assertions in the table below as either being always true, never true, or sometimes true / sometimes false. (You may abbreviate them as A, N, or S.)

public static int stuff(Random r, int m) { int c = 0; int t = 0; int d = r.nextInt(m); // Point A while (c <= 3) { // Point B d = r.nextInt(6) + 1; if (d <= m) { c++; // Point C } else { c = 0; // Point D } t++; } // Point E return t; } c > 3

d <= m

c == 0

Point A Point B Point C Point D Point E

4 of 8


6. Programming Write a static method named xo that accepts an integer size as a parameter and prints a square of size by size characters, where all characters are "o" except that an "x" pattern of "x" characters has been drawn from the corners of the square. In other words, on the first line, the first and last characters are "x"; on the second line, the second and second-from-last characters are "x"; and so on. If 0 or less is passed for the size, no output should be produced. The following table lists some calls to your method and their expected output: Call

xo(5);

xo(8);

xo(3);

xo(1);

xooox oxoxo ooxoo oxoxo xooox

xoooooox oxooooxo ooxooxoo oooxxooo oooxxooo ooxooxoo oxooooxo xoooooox

xox oxo xox

x

Example Output

xo(0);

xo(12);

xo(11);

xoooooooooox oxooooooooxo ooxooooooxoo oooxooooxooo ooooxooxoooo oooooxxooooo oooooxxooooo ooooxooxoooo oooxooooxooo ooxooooooxoo oxooooooooxo xoooooooooox

xooooooooox oxoooooooxo ooxoooooxoo oooxoooxooo ooooxoxoooo oooooxooooo ooooxoxoooo oooxoooxooo ooxoooooxoo oxoooooooxo xooooooooox

5 of 8


7. Programming Write a static method named anglePairs that accepts three angles (integers), measured in degrees, as parameters and returns whether or not there exists both complementary and supplementary angles amongst the three angles passed. Two angles are complementary if their sum is exactly 90 degrees; two angles are supplementary if their sum is exactly 180 degrees. Therefore, the method should return true if any two of the three angles add up to 90 degrees and also any two of the three angles add up to 180 degrees; otherwise the method should return false. You may assume that each angle passed is non-negative. Here are some example calls to the method and their resulting return values.

Call

Value Returned

anglePairs(0, 90, 180) anglePairs(45, 135, 45) anglePairs(177, 87, 3) anglePairs(120, 60, 30) anglePairs(35, 60, 30) anglePairs(120, 60, 45) anglePairs(45, 90, 45) anglePairs(180, 45, 45)

true true true true false false false false

6 of 8


8. Programming Write a static method named baseball that takes a Scanner representing the console as a parameter and plays an interactive baseball scoring game with the user, returning an integer representing which team won the game. Baseball is a sport where teams play a series of innings against each other. Each team scores a certain number of runs (points) in each inning. A baseball game ends when one of the following conditions is met:  

After 9 innings are finished, if one team has more total runs than the other, the team with more runs wins. After 9 innings are finished, if the teams are tied (if they have the same number of total runs), we keep playing one more full inning at a time until the teams are not tied any more.  After any inning, if one team is ahead by 10 or more runs, the game is called and the team with more runs wins. Your method should repeatedly prompt the user, once per inning, to enter the number of runs that each team scored during each inning. The user will type in the first team's runs for that inning, followed by the second team's runs for that inning, separated by whitespace. Your method should stop prompting once one or more of the above bulleted conditions are met, causing the game to end. At the end of the game, you should print the final score. You should also return an integer for which team won: return 1 if the first team won, and 2 if the second team won. You may assume that the user enters valid non-negative integers whenever prompted, and you may assume that the game will eventually end (it won't go on forever). Here are some example calls to the method and their resulting output and return values: Scanner console = new Scanner(System.in);

Call Example Output

Returns

// typical game baseball(console); Inning #1: 1 1 Inning #2: 0 0 Inning #3: 2 1 Inning #4: 0 2 Inning #5: 1 0 Inning #6: 1 1 Inning #7: 3 1 Inning #8: 0 0 Inning #9: 1 0 Final score: 9 - 6

// 10 run limit; game called baseball(console); Inning #1: 0 1 Inning #2: 1 2 Inning #3: 0 3 Inning #4: 1 1 Inning #5: 0 4 Inning #6: 1 2 Final score: 3 - 13

// extra innings baseball(console); Inning #1: 0 1 Inning #2: 1 0 Inning #3: 0 3 Inning #4: 1 0 Inning #5: 2 0 Inning #6: 1 2 Inning #7: 1 0 Inning #8: 0 0 Inning #9: 1 1 Inning #10: 0 0 Inning #11: 0 1 Final score: 7 - 8

1

2

2

(More writing space can be found on the next page.)

7 of 8


8. Programming (writing space)

8 of 8


CSE 142, Autumn 2010 Midterm Exam Key 1. Expressions Expression 12 / 3 + 5 + 3 * -2 1 + 1 + "(1 + 1)" + 1 + 1 13 / 2 - 38 / 5 / 2.0 + (15 / 10.0) 11 < 3 + 4 || !(5 / 2 == 2) 20 % 6 + 6 % 20 + 6 % 6

Value 3 "2(1 + 1)11" 4.0 false 8

2. Parameter Mystery 3 + 5 = 1 10 + 3 = 5 7 + 4 = 7 2 + 5 = 2

3. If/Else Simulation Method Call ifElseMystery(5, 5); ifElseMystery(18, 4); ifElseMystery(3, 6);

Output 16 5 2 6 5 8

4. While Loop Simulation Method Call whileMystery(7, 5); whileMystery(20, 4); whileMystery(40, 10);

Output 2 -2 3 16 13 11 10 0 30 21 13 6 0 5

5. Assertions

Point A Point B Point C Point D Point E

c > 3 NEVER NEVER SOMETIMES NEVER ALWAYS

d <= m ALWAYS SOMETIMES ALWAYS NEVER ALWAYS

c == 0 ALWAYS SOMETIMES NEVER ALWAYS NEVER


6. Programming There are many ways to solve any programming problem. Here are some common correct solutions we saw: public static void xo(int size) { for (int i = 1; i <= size; i++) { for (int j = 1; j <= size; j++) { if (j == i || j == size - (i - 1)) { System.out.print("x"); } else { System.out.print("o"); } } System.out.println(); } } public static void xo(int size) { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (j == i || j == size - 1 - i) { System.out.print("x"); } else { System.out.print("o"); } } System.out.println(); } } public static void xo(int size) { int x1 = 1; int x2 = size; for (int i = 1; i <= size; i++) { for (int j = 1; j <= size; j++) { if (x1 == j || x2 == j) { System.out.print("x"); } else { System.out.print("o"); } } System.out.println(); x1++; x2--; } }

// note the (i - 1), not i


public static void xo(int size) { for (int i = 0; i < size / 2; i++) { repeat("o", i); repeat("x", 1); repeat("o", size - 2*i - 2); repeat("x", 1); repeat("o", i); System.out.println(); }

// top half

if (size % 2 != 0) { // middle line (when odd size) repeat("o", size / 2); repeat("x", 1); repeat("o", size / 2); System.out.println(); } for (int i = size / 2 - 1; i >= 0; i--) { repeat("o", i); repeat("x", 1); repeat("o", size - 2*i - 2); repeat("x", 1); repeat("o", i); System.out.println(); } } public static void repeat(String s, int n) { for (int i = 0; i < n; i++) { System.out.print(s); } }

// bottom half


7. Programming // nested ifs with || solution public static boolean anglePairs(int a1, int a2, int a3) { if (a1 + a2 == 90 || a2 + a3 == 90 || a3 + a1 == 90) { if (a1 + a2 == 180 || a2 + a3 == 180 || a3 + a1 == 180) { return true; } else { return false; } } else { return false; } } // boolean zen solution public static boolean anglePairs(int a1, int a2, int a3) { return (a1 + a2 == 90 || a2 + a3 == 90 || a3 + a1 == 90) && (a1 + a2 == 180 || a2 + a3 == 180 || a3 + a1 == 180); } // eliminate false cases first solution public static boolean anglePairs(int a1, int a2, int a3) { if (a1 + a2 != 90 && a2 + a3 != 90 && a3 + a1 != 90) { return false; } if (a1 + a2 != 180 && a2 + a3 != 180 && a3 + a1 != 180) { return false; } return true; } // nest by which pair matches 90 vs. 180 public static boolean anglePairs(int a1, int a2, int a3) { if (a1 + a2 == 90) { if (a2 + a3 == 180 || a1 + a3 == 180) { return true; } else { return false; } } else if (a2 + a3 == 90) { if (a1 + a2 == 180 || a1 + a3 == 180) { return true; } else { return false; } } else if (a1 + a3 == 90) { if (a1 + a2 == 180 || a2 + a3 == 180) { return true; } else { return false; } } else { return false; } }


// nest by 90 check, zen version public static boolean anglePairs(int a1, int a2, int a3) { if (a1 + a2 == 90) { return a2 + a3 == 180 || a1 + a3 == 180; } else if (a2 + a3 == 90) { return a1 + a2 == 180 || a1 + a3 == 180; } else if (a1 + a3 == 90) { return a1 + a2 == 180 || a2 + a3 == 180; } return false; } // nest by 90 check, very zen version public static boolean anglePairs(int a1, int a2, int a3) { return (a1 + a2 == 90 && (a2 + a3 == 180 || a1 + a3 == 180)) || (a1 + a3 == 90 && (a1 + a2 == 180 || a2 + a3 == 180)) || (a1 + a3 == 90 && (a1 + a2 == 180 || a2 + a3 == 180)); } } // boolean flags version public static boolean anglePairs(int a, int b, int c) { boolean supp = false; boolean comp = false; if (a + b == 90 || a + c == 90 || b + c == 90) { comp = true; } if (a + b == 180 || a + c == 180 || b + c == 180) { supp = true; } return supp && comp; } // zenned out && pairs public static boolean anglePairs(int a1, int b, int c) { return a+b==90 && a+c==180 || a+b==90 && b+c==180 || a+c==90 && a+b==180 || a+c==90 && b+c==180 || b+c==90 && a+b==180 || b+c==90 && a+c==180; }


8. Programming public static int baseball(Scanner console) { int score1 = 0; int score2 = 0; int inning = 1; while ((inning <= 9 || score1 == score2) && Math.abs(score1 - score2) < 10) { System.out.print("Inning #" + inning + ": "); score1 += console.nextInt(); score2 += console.nextInt(); inning++; } System.out.println("Final score: " + score1 + " - " + score2); if (score1 > score2) { return 1; } else { return 2; } } public static int baseball (Scanner console) { int inning = 1; int team1 = 0; int team2 = 0; while (inning <= 9) { System.out.print("Inning #" + inning + ": "); team1 += console.nextInt(); team2 += console.nextInt(); if((team1-team2 >=10) || (team2 - team1 >= 10)) { System.out.println ("Final score: " + score1 + " - " + score2); if (team1 > team2) { return 1; } else { return 2; } } else { inning++; } } while (team2 == team1) { System.out.print ("Inning #" + inning + ": "); team1 += console.nextInt(); team2 += console.nextInt(); } System.out.println("Final score: " + score1 + " - " + score2); if (team1 > team2) { return 1; } else { return 2; } }


CSE 142, Autumn 2011 Midterm Exam: Friday, November 4, 2011

Name:

___________________________________________

Section:

___________________ TA: ___________________

Student ID #:

___________________

   

You have 50 minutes to complete this exam. You may receive a deduction if you keep working after the instructor calls for papers. This exam is open-book. You may not use any computing devices including calculators. Code will be graded on proper behavior/output and not on style, unless otherwise indicated. Do not abbreviate code, such as "ditto" marks or dot-dot-dot ... marks. The only abbreviations that are allowed for this exam are:  S.o.p for System.out.print,  S.o.pln for System.out.println, and  S.o.pf for System.out.printf.

  

You do not need to write import statements in your code. If you enter the room, you must turn in an exam before leaving the room. You must show your Student ID to a TA or instructor for your exam to be accepted. Good luck!

Score summary: (for grader only)

Problem Description 1 Expressions 2 Parameter Mystery 3 If/Else Simulation 4 While Loop Simulation 5 Assertions 6 Programming 7 Programming 8 Programming TOTAL Total Points

Earned

Max 10 15 10 10 15 15 15 10 100 1 of 8


1. Expressions For each expression at left, indicate its value in the right column. List a value of appropriate type and capitalization. e.g., 7 for an int, 7.0 for a double, "hello" for a String, true or false for a boolean. Expression

Value

5 + 2 * 4 / 3 + 5

_____________________________

5 + 5 + "23.0" + 5 + 2 * 5

_____________________________

!(5 > 2 && -2 > 2) || 5 / 2 == 0

_____________________________

15 % 9 % 4 + 4 % 6 % 3

_____________________________

12 / 5 / 2.0 + 2 * 4

_____________________________

2. Parameter Mystery At the bottom of the page, write the output produced by the following program, as it would appear on the console.

public class ParameterMystery { public static void main(String[] args) { String bril = "vorpal"; String gyre = "jubjub"; String slithy = "snack"; String tum = "mut"; String mut = tum + 1; mystery(bril, slithy, gyre); mystery(gyre, "gyre", mut); mystery(gyre + slithy, bril, tum); tum = "tumtum"; bril = "slithy"; mystery(tum, gyre, slithy); } public static void mystery(String gyre, String bril, String slithy) { System.out.println("Twas " + bril + " and the " + slithy + " toves did " + gyre); } }

2 of 8


3. If/Else Simulation For each call below to the following method, write the output that is produced, as it would appear on the console:

public static void ifElseMystery(int x, int y) { int z = 0; if (x >= y) { x = x / 2; z++; } if (x > z && y <= z) { z++; } else if (x > z) { y = y - 5; } System.out.println(x + " " + y + " " + z); } Method Call

Output

ifElseMystery(4, 1);

____________________________________________

ifElseMystery(-10, 100);

____________________________________________

ifElseMystery(18, 4);

____________________________________________

ifElseMystery(-12, 5);

____________________________________________

3 of 8


4. While Loop Simulation For each call below to the following method, write the output that is produced, as it would appear on the console:

public static void mystery(int x, int y) { int z = 1; while (x > 0) { System.out.print(y + ", "); y = y - z; z = z + y; x--; } System.out.println(y); }

Method Call

Output

mystery(2, 3);

____________________________________________

mystery(3, 5);

____________________________________________

mystery(4, 7);

____________________________________________

4 of 8


5. Assertions For each of the five points labeled by comments, identify each of the assertions in the table below as either being always true, never true, or sometimes true / sometimes false.

public static int mystery(Scanner console, int f) { int num = console.nextInt(); int h = 0; // Point A while (f < 5) { // Point B if (num == 0) { h = 0; f++; // Point C } else { // Point D h++; } num = console.nextInt(); } // Point E return f; }

Fill in each box below with one of ALWAYS, NEVER or SOMETIMES. (You may abbreviate them as A, N, or S.)

h == 0

f >= 5

num == 0

Point A Point B Point C Point D Point E

5 of 8


6. Programming Write a static method named twoConsecutive that accepts three integers as parameters and returns true if there is at least one pair of integers that differ by exactly 1. For example, the integers 3 and 4 differ by 1. The integers 12 and 11 also differ by 1. Your method should return false if there are no such consecutive values. The integers could be passed in any order; the two consecutive values could be any of the two values passed in. Here are some sample calls:

Call

Output

twoConsecutive(1, 2, 12) twoConsecutive(1, 12, 2) twoConsecutive(2, 12, 1) twoConsecutive(4, 5, 3) twoConsecutive(2, 4, 6) twoConsecutive(8, 8, 8)

true true true true false false

6 of 8


7. Programming Write a static method named stitching that accepts two integer parameters w and h and that prints a rectangle of dashes and numbers. Each of the h lines printed will contain w integers separated by dashes. The first number on each line is the line number. For example, the first line’s first number is 1 and the sixth line’s first number is 6. The lines alternate between starting with a dash and ending with a dash. For example, the first, third and fifth lines start with a dash and the second, fourth and sixth lines start with a number. You may assume that the value of each parameter is greater than or equal to 1. Your output must exactly match the format shown. Here are some example calls to the method and their resulting console output:

Call Output

stitching(6, 2); -1-2-3-4-5-6 2-3-4-5-6-7-

stitching(2, 3); -1-2 2-3-3-4

stitching(2, 6); -1-2 2-3-3-4 4-5-5-6 6-7-

stitching(1, 1); -1

7 of 8


8. Programming Write a static method named sameFlip that accepts a Random object as a parameter. Your method should flip a coin until the same result occurs twice in a row. In other words, if a head is flipped followed by another head or if a tail is flipped followed by another tail, your method should end. You should use the Random object to give an equal chance to a head or tail appearing. Each time the coin is flipped, print H for heads or T for tails. For example, if the following variable is initialized: Random r = new Random();

Here are some sample calls along with possible output:

Call

Output

sameFlip(r); sameFlip(r); sameFlip(r); sameFlip(r);

HTHH HTHTT TT THTHTHH

8 of 8


..................................................................... o \ o / _ o __| \ / |__ o _ \ o / o /|\ | /\ __\o \o | o/ o/__ /\ | /|\ / \ / \ | \ /) | ( \ /o\ / ) | (\ / | / \ / \ .....................................................................

Midterm Exam Syntax Reference for (initialization; test; update) { statement(s); ... }

while (condition) { statement(s); }

if (test) { statement(s); } else if (test) { statement(s); } else { statement(s); }

public static type name(parameters) { statement(s); ... return expression; }

Math Method Math.abs(value) Math.min(v1, v2) Math.max(v1, v2) Math.round(value) Math.sqrt(value) Math.pow(b, e)

Description absolute value smaller of two values larger of two values nearest whole number square root base to the exponent power

Scanner Method nextInt() next()

Random Method nextInt(max)

Description reads/returns input as int reads/returns input as String

Description random integer from 0 to max-1

String Method contains(str) endsWith(str), startsWith(str) equals(str) equalsIgnoreCase(str) indexOf(str) length() replace(str1, str2) substring(i, j) toLowerCase(), toUpperCase() charAt(i)

Description true if this string contains the other's characters inside it true if this string starts/ends with the other's characters true if this string is the same as str true if this string is the same as str, ignoring capitalization index in this string where given string begins (-1 if not found) number of characters in this string replace all occurrences in this string of str1 with str2 characters in this string from index i (inclusive) to j (exclusive) a new string with all lowercase or uppercase letters returns char at index i


Sample Final Exam #1 Key 1.

2.

3.

Call int[] a1 = {7}; arrayMystery(a1);

Final Contents of Array {7}

int[] a2 = {4, 3, 6}; arrayMystery(a2);

{4, 2, -2}

int[] a3 = {7, 4, 8, 6, 2}; arrayMystery(a3);

{7, 4, -2, -5, -3}

int[] a4 = {10, 2, 5, 10}; arrayMystery(a4);

{10, 9, 6, -1}

int[] a5 = {2, 4, -1, 6, -2, 8}; arrayMystery(a5);

{2, -1, 2, -1, 5, 2}

14 14 7 9 14 2 18 18 7 9 14 18

b c 1 a 2

c 1

b c 1 b 2

c 2

c c 1 c 2 b d 1 b 2

4.

b 2 c 2

c 2

public static void printStrings(Scanner input) { while (input.hasNextInt()) { int times = input.nextInt(); String word = input.next(); for (int i = 0; i < times; i++) { System.out.print(word); } System.out.println(); } }

1 of 3


5.

6.

public static void reverseLines(Scanner input) { while (input.hasNextLine()) { String text = input.nextLine(); for (int i = text.length() - 1; i >= 0; i--) { System.out.print(text.charAt(i)); } System.out.println(); } }

public static boolean isAllEven(int[] list) { for (int i = 0; i < list.length; i++) { if (list[i] % 2 != 0) { return false; } } return true; }

7. public static boolean isUnique(int[] list) { for (int i = 0; i < list.length; i++) { for (int j = i + 1; j < list.length; j++) { if (list[i] == list[j]) { return false; } } } return true; }

2 of 3


8.

import java.awt.*; import java.util.*;

// for Color // for Random

public class Ostrich extends Critter { private Random rand; private int steps; private boolean west; // true if going west; false if east private boolean hiding; public Ostrich() { rand = new Random(); hiding = true; steps = 0; west = rand.nextBoolean(); }

// or call nextInt(2) and map 0=false, 1=true

public Color getColor() { if (hiding) { return Color.CYAN; } else { return Color.WHITE; } } public Direction getMove() { if (steps == 10) { steps = 0; // Pick a new direction and re-set the steps counter hiding = !hiding; west = rand.nextBoolean(); }

}

}

steps++; if (hiding) { return Direction.CENTER; } else if (west) { return Direction.WEST; } else { return Direction.EAST; }

9. Two solutions are shown. public int compareTo(Date other) { if (month < other.month || (month == other.month && day < other.day)) { return -1; } else if (month == other.month && day == other.day) { return 0; } else { return 1; } } public int compareTo(Date other) { if (month == other.month) { return day - other.day; } else { return month - other.month; } }

3 of 3


Sample Final Exam #2 (Winter 2005; thanks to Stuart Reges)

1. Array Mystery Consider the following method: public static int arrayMystery(int[] array) { int x = 0; for (int i = 0; i < array.length - 1; i++) { if (array[i] > array[i + 1]) { x++; } } return x; }

In the left-hand column below are specific arrays of integers. Indicate in the right-hand column what value would be returned by method arrayMystery if the integer array in the left-hand column is passed as its parameter.

Original Contents of Array

Value Returned

int[] a1 = {8}; int result1 = arrayMystery(a1);

_____________________________

int[] a2 = {14, 7}; int result2 = arrayMystery(a2);

_____________________________

int[] a3 = {7, 1, 3, 2, 0, 4}; int result3 = arrayMystery(a3);

_____________________________

int[] a4 = {10, 8, 9, 5, 6}; int result4 = arrayMystery(a4);

_____________________________

int[] a5 = {8, 10, 8, 6, 4, 2}; int result5 = arrayMystery(a5);

_____________________________

1 of 9


2. Reference Semantics Mystery The following program produces 4 lines of output. Write the output below, as it would appear on the console. import java.util.*;

// for Arrays class

public class ReferenceMystery { public static void main(String[] args) { int y = 1; int x = 3; int[] a = new int[4]; mystery(a, y, x); System.out.println(x + " " + y + " " + Arrays.toString(a)); x = y - 1; mystery(a, y, x); System.out.println(x + " " + y + " " + Arrays.toString(a)); } public static void mystery(int[] a, int x, int y) { if (x < y) { x++; a[x] = 17; } else { a[y] = 17; } System.out.println(x + " " + y + " " + Arrays.toString(a)); } }

2 of 9


3. Inheritance Mystery Assume that the following classes have been defined: public class Pen extends Sock { public void method1() { System.out.print("pen 1 } } public class Lamp { public void method1() { System.out.print("lamp 1 } public void method2() { System.out.print("lamp 2 } public String toString() { return "lamp"; }

");

");

public class Book extends Sock { public void method2() { System.out.print("book 2 super.method2(); } } public class Sock extends Lamp { public void method1() { System.out.print("sock 1 method2(); }

");

");

"); public String toString() { return "sock"; } }

}

Given the classes above, what output is produced by the following code? Lamp[] elements = {new Book(), new Pen(), new Lamp(), new Sock()}; for (int i = 0; i < elements.length; i++) { System.out.println(elements[i]); elements[i].method1(); System.out.println(); elements[i].method2(); System.out.println(); System.out.println(); }

3 of 9


4. File Processing Write a static method named wordStats that accepts as its parameter a Scanner holding a sequence of words and that reports the total number of words (as an integer) and the average word length (as an un-rounded real number). For example, suppose the Scanner is scanning an input source that contains the following words: To be or not to be, that is the question.

For the purposes of this problem, we will use whitespace to separate words. That means that some words include punctuation, as in "be,". (This is the same definition that the Scanner uses for tokens.) For the input above, your method should produce exactly the following output: Total words = 10 Average length = 3.2

4 of 9


5. File Processing Write a static method named flipLines that accepts as its parameter a Scanner for an input file and that writes to the console the same file's contents with successive pairs of lines reversed in order. For example, if the input file contains the following text: Twas brillig and the slithy toves did gyre and gimble in the wabe. All mimsey were the borogroves, and the mome raths outgrabe. "Beware the Jabberwock, my son, the jaws that bite, the claws that catch, Beware the JubJub bird and shun the frumious bandersnatch."

The program should print the first pair of lines in reverse order, then the second pair in reverse order, then the third pair in reverse order, and so on. Therefore your method should produce the following output to the console: did gyre and gimble in the wabe. Twas brillig and the slithy toves and the mome raths outgrabe. All mimsey were the borogroves, "Beware the Jabberwock, my son, Beware the JubJub bird and shun the jaws that bite, the claws that catch, the frumious bandersnatch."

Notice that a line can be blank, as in the third pair. Also notice that an input file can have an odd number of lines, as in the one above, in which case the last line is printed in its original position. You may not make any assumptions about how many lines are in the Scanner.

5 of 9


6. Array Programming Write a static method named minGap that accepts an integer array as a parameter and returns the minimum 'gap' between adjacent values in the array. The gap between two adjacent values in a array is defined as the second value minus the first value. For example, suppose a variable called array is an array of integers that stores the following sequence of values. int[] array = {1, 3, 6, 7, 12};

The first gap is 2 (3 - 1), the second gap is 3 (6 - 3), the third gap is 1 (7 - 6) and the fourth gap is 5 (12 - 7). Thus, the call of minGap(array) should return 1 because that is the smallest gap in the array. Notice that the minimum gap could be a negative number. For example, if array stores the following sequence of values: (3, 5, 11, 4, 8)

The gaps would be computed as 2 (5 - 3), 6 (11 - 5), -7 (4 - 11), and 4 (8 - 4). Of these values, -7 is the smallest, so it would be returned. This gap information can be helpful for determining other properties of the array. For example, if the minimum gap is greater than or equal to 0, then you know the array is in sorted (nondecreasing) order. If the gap is greater than 0, then you know the array is both sorted and unique (strictly increasing). If you are passed an array with fewer than 2 elements, you should return 0.

6 of 9


7. Array Programming Write a static method named longestSortedSequence that accepts an array of integers as a parameter and that returns the length of the longest sorted (nondecreasing) sequence of integers in the array. For example, if a variable named array stores the following values: int[] array = {3, 8, 10, 1, 9, 14, -3, 0, 14, 207, 56, 98, 12};

then the call of longestSortedSequence(array) should return 4 because the longest sorted sequence in the array has four values in it (the sequence -3, 0, 14, 207). Notice that sorted means nondecreasing, which means that the sequence could contain duplicates. For example, if the array stores the following values: int[] array2 = {17, 42, 3, 5, 5, 5, 8, 2, 4, 6, 1, 19}

Then the method would return 5 for the length of the longest sequence (the sequence 3, 5, 5, 5, 8). Your method should return 0 if passed an empty array. Your method should return 1 if passed an array that is entirely in decreasing order or contains only one element.

7 of 9


8. Critters Write a class Bumblebee that extends the Critter class from the Critters assignment. A Bumblebee object should move in a "spiral" pattern from W to S to E to N, lengthening each time:         

one step west two steps south three steps east four steps north five steps west six steps south seven steps east eight steps north nine steps west ...

All other Bumblebee behavior uses the Critter defaults. You may add anything needed (fields, other methods) to implement this behavior appropriately.

8 of 9


9. Classes and Objects Suppose that you are provided with a pre-written class Rectangle as described at right. (The headings are shown, but not the method bodies, to save space.) Assume that the fields, constructor, and methods shown are already implemented. You may refer to them or use them in solving this problem if necessary. Write an instance method named union that will be placed inside the Rectangle class to become a part of each Rectangle object's behavior. The union method accepts another rectangle r as a parameter and turns this rectangle into the union of itself and r ; that is, modifies the fields so that they represent the smallest rectangular region that completely contains both this rectangle and r .

// A Rectangle stores an (x, y) // coordinate of its top/left // corner, a width and height. public class Rectangle { private int x; private int y; private int width; private int height; // Constructs a new Rectangle // with the given x,y,w,h. public Rectangle(int x, int y, int w, int h) // returns the field values public int getX() public int getY() public int getWidth() public int getHeight()

For example, if the following Rectangles are declared in client code:

// example: {(5, 12), 4x8} public String toString()

Rectangle rect1 = new Rectangle(5, 12, 4, 6); Rectangle rect2 = new Rectangle(6, 8, 5, 7); Rectangle rect3 = new Rectangle(14, 9, 3, 3); Rectangle rect4 = new Rectangle(10, 3, 5, 8);

// your method would go here }

The following calls to the union method would modify the objects' state as indicated in the comments. rect1.union(rect2); rect4.union(rect3);

// {(5, 8), 6x10} // {(10, 3), 7x9}

9 of 9


Sample Final Exam #2 Key 1. Call int[] a1 = {8}; int result1 = arrayMystery(a1);

Value Returned 0

int[] a2 = {14, 7}; int result2 = arrayMystery(a2);

1

int[] a3 = {7, 1, 3, 2, 0, 4}; int result3 = arrayMystery(a3);

3

int[] a4 = {10, 8, 9, 5, 6}; int result4 = arrayMystery(a4);

2

int[] a5 = {8, 10, 8, 6, 4, 2}; int result5 = arrayMystery(a5);

4

2. 2 3 [0, 0, 17, 0] 3 1 [0, 0, 17, 0] 1 0 [17, 0, 17, 0] 0 1 [17, 0, 17, 0]

3. sock sock 1 book 2

book 2 lamp 2

lamp 2

sock pen 1 lamp 2 lamp lamp 1 lamp 2 sock sock 1 lamp 2

lamp 2

1 of 3


4. public static void wordStats(Scanner input) { int count = 0; int sumLength = 0; while (input.hasNext()) { String next = input.next(); count++; sumLength += next.length(); }

}

double average = (double) sumLength / count; System.out.println("Total words = " + count); System.out.println("Average length = " + average);

5. public static void flipLines(Scanner input) { while (input.hasNextLine()) { String first = input.nextLine(); if (input.hasNextLine()) { String second = input.nextLine(); System.out.println(second); } System.out.println(first); } }

6. public static int minGap(int[] list) { if (list.length < 2) { return 0; } else { int min = list[1] - list[0]; for (int i = 2; i < list.length; i++) { int gap = list[i] - list[i - 1]; if (gap < min) { min = gap; } } return min; } }

7. public static int longestSortedSequence(int[] list) { if (list.length == 0) { return 0; } int max = 1; int count = 1; for (int i = 1; i < list.length; i++) { if (list[i] >= list[i - 1]) { count++; } else { count = 1; } if (count > max) { max = count; }

}

} return max;

2 of 3


8. public class Bumblebee extends Critter { private int steps; private int max; private int direction; // 0=west, 1=south, 2=east, 3=north public Bumblebee() { steps = 0; max = 1; direction = 0; } public Direction getMove() { steps++; if (steps > max) { // Pick a new direction and re-set the steps counter steps = 1; max++; direction = (direction + 1) % 4; }

}

9.

}

if (direction == 0) { return Direction.WEST; } else if (direction == 1) { return Direction.SOUTH; } else if (direction == 2) { return Direction.EAST; } else { // direction == 3 return Direction.NORTH; }

public void union(Rectangle r) { // find the union's bounds int left = Math.min(x, r.getX()); int top = Math.min(y, r.getY()); int right = Math.max(x + width, r.getX() + r.getWidth()); int bottom = Math.max(y + height, r.getY() + r.getHeight());

}

x = left; y = top; width = right - left; height = bottom - top;

3 of 3


Sample Final Exam #3 (Autumn 2007)

1. Array Mystery Consider the following method: public static void arrayMystery(int[] a) { for (int i = a.length - 2; i > 0; i--) { if (a[i + 1] <= a[i - 1]) { a[i]++; } } }

Indicate in the right-hand column what values would be stored in the array after the method arrayMystery executes if the integer array in the left-hand column is passed as a parameter to it.

Original Contents of Array

Final Contents of Array

int[] a1 = {42}; arrayMystery(a1);

_____________________________

int[] a2 = {1, 8, 3, 6}; arrayMystery(a2);

_____________________________

int[] a3 = {5, 5, 5, 5, 5}; arrayMystery(a3);

_____________________________

int[] a4 = {10, 7, 9, 6, 8, 5}; arrayMystery(a4);

_____________________________

int[] a5 = {1, 0, 1, 0, 0, 1, 0}; arrayMystery(a5);

_____________________________

1 of 9


2. Reference Semantics Mystery The following program produces 4 lines of output. Write the output below, as it would appear on the console. import java.util.*;

// for Arrays class

public class ReferenceMystery { public static void main(String[] args) { int x = 0; int[] a = new int[4]; x++; mystery(x, a); System.out.println(x + " " + Arrays.toString(a)); x++; mystery(x, a); System.out.println(x + " " + Arrays.toString(a)); } public static void mystery(int x, int[] a) { x++; a[x]++; System.out.println(x + " " + Arrays.toString(a)); } }

2 of 9


3. Inheritance Mystery Assume that the following classes have been defined: public class Vier extends Drei { public void method2() { super.method2(); System.out.print("Vier 2 }

");

public String toString() { return "Vier " + super.toString(); }

public class Drei extends Zwei { public void method1() { System.out.print("Drei 1 }

");

public String toString() { return "Drei"; } }

} public class Zwei extends Eins { public void method2() { System.out.print("Zwei 2 method1(); } }

public class Eins { public String toString() { return "Eins"; } "); public void method1() { System.out.print("Eins 1 }

");

public void method2() { System.out.print("Eins 2 }

");

}

Given the classes above, what output is produced by the following code? Eins[] elements = {new Zwei(), new Eins(), new Vier(), new Drei()}; for (int i = 0; i < elements.length; i++) { System.out.println(elements[i]); elements[i].method1(); System.out.println(); elements[i].method2(); System.out.println(); System.out.println(); }

3 of 9


4. File Processing Write a static method named coinFlip that accepts as its parameter a Scanner for an input file. Assume that the input file data represents results of sets of coin flips that are either heads (H) or tails (T) in either upper or lower case, separated by at least one space. Your method should consider each line to be a separate set of coin flips and should output to the console the number of heads and the percentage of heads in that line, rounded to the nearest tenth. If this percentage is more than 50%, you should print a "You win" message. For example, consider the following input file: H T H H T T t t T h h

H

For the input above, your method should produce the following output: 3 heads (60.0%) You win! 2 heads (33.3%) 1 heads (100.0%) You win!

The format of your output must exactly match that shown above. You may assume that the Scanner contains at least 1 line of input, that each line contains at least one token, and that no tokens other than h, H, t, or T will be in the lines.

4 of 9


5. File Processing Write a static method named findFirstMatch that accepts as its parameters a Scanner for an input file and an array of Strings keywords representing a list of keywords in a search. Your method will read lines from its input Scanner and should return the line number of the first line in the file that contains one or more words from keywords. If none of the keywords are found in the file, your method should return a -1. The search should be case-insensitive, so if a keyword was "banana", the line "yummy baNAna split" would be considered a line that contains the keyword. Your method should also match whole words only, so if the only keyword in the array was "ball", the line "football game" would not be considered a match. For example, consider the following input file saved in sidewalk.txt, consisting of 6 lines: Let us leave this place where the smoke blows black And the dark street winds and bends. Past the pits where the asphalt flowers grow We shall walk with a walk that is measured and slow, And watch where the chalk-white arrows go To the place where the sidewalk ends.

The following table shows some calls to your method and their expected results with the following Scanner: Scanner input = new Scanner(new File("sidewalk.txt"));

Array String[] k1 = {"place", "winds"}; String[] k2 = {"dinosaur", "PITS", "pots"}; String[] k3 = {"chalk", "row", "g", "ends"}; String[] k4 = {"to"};

Call / Returned Value findFirstMatch(input, k1) returns 1 findFirstMatch(input, k2) returns 3 findFirstMatch(input, k3) returns -1 findFirstMatch(input, k4) returns 6

You may assume that none of the words in the keywords array contain spaces, i.e. all keywords are single whole words, and the array contains at least one element. Do not modify the elements of the keywords array.

5 of 9


6. Array Programming Write a static method named range that takes an array of integers as a parameter and returns the range of values contained in the array. The range of an array is defined to be one more than the difference between its largest and smallest element. For example, if the largest element in the array is 15 and the smallest is 4, the range is 12. If the largest and smallest values are the same, the range is 1. The following table shows some calls to your method and their results (the largest and smallest values are underlined):

Array

Returned Value

int[] a1 = {8, 3, 5, 7, 2, 4}; int[] a2 = {15, 22, 8, 19, 31}; int[] a3 = {3, 10000000, 5, -29, 4}; int[] a4 = {100, 5}; int[] a5 = {32};

range(a1) returns 7 range(a2) returns 24 range(a3) returns 10000030 range(a4) returns 96 range(a5) returns 1

You may assume that the array contains at least one element (that its length is at least 1). You should not make any assumptions about the values of the particular elements in the array; they could be extremely large, very small, etc. You should not modify the contents of the array.

6 of 9


7. Array Programming Write a static method named zeroOut that accepts two arrays of integers a1 and a2 as parameters and replaces any occurrences of a2 in a1 with zeroes. The sequence of elements in a2 may appear anywhere in a1 but must appear consecutively and in the same order. For example, if variables called a1 and a2 store the following values: int[] a1 = {1, 2, 3, 4, 1, 2, 3, 4, 5}; int[] a2 = {2, 3, 4};

The call of zeroOut(a1, a2); should modify a1's contents to be {1, 0, 0, 0, 1, 0, 0, 0, 5}. Note that the pattern can occur many times, even consecutively. For the following two arrays a3 and a4: int[] a3 = {5, 5, 5, 18, 5, 42, 5, 5, 5, 5}; int[] a4 = {5, 5};

The call of zeroOut(a3, a4); should modify a3's contents to be {0, 0, 5, 18, 5, 42, 0, 0, 0, 0}. You may assume that both arrays passed to your method will have lengths of at least 1. If a2 is not found in a1, or if a1's length is shorter than a2's, then a1 is not modified by the call to your method. Please note that a1's contents are being modified in place; you are not supposed to return a new array. Do not modify the contents of a2.

7 of 9


8. Critters Write a class Dragonfly that extends the Critter class from the Critters assignment. Whenever a Dragonfly encounters food, it eats it. Eating affects the Dragonfly's movement. Dragonfly objects move in a N/E/S/E sequence, initially going east once between going north and south, but going east an additional time for each time the Dragonfly has eaten.

   

If the Dragonfly has never eaten: If the Dragonfly has eaten once: If the Dragonfly has eaten twice: ...

NORTH, EAST, SOUTH, EAST, and repeat NORTH, EAST, EAST, SOUTH, EAST, EAST, and repeat. NORTH, EAST, EAST, EAST, SOUTH, EAST, EAST, EAST, and repeat.

We will be somewhat flexible about what should happen if a Dragonfly eats in the middle of a movement sequence. Either it should take effect immediately, lengthening the rest of that sequence and all subsequent ones; or it can take effect at the beginning of the next overall N/E/S/E movement sequence, lengthening it and all subsequent sequences. You may add anything needed (fields, constructors, etc.) to implement this behavior appropriately.

8 of 9


9. Classes and Objects Suppose that you are provided with a pre-written class BankAccount as described at right. (The headings are shown, but not the method bodies, to save space.) Assume that the fields, constructor, and methods shown are already implemented. You may refer to them or use them in solving this problem if necessary.

// A BankAccount keeps track of a // user's money balance and ID, // and counts how many transactions // (deposits/withdrawals) are made. public class BankAccount { private String id; private double balance; private int transactions;

Write an instance method named transactionFee that will be placed inside the BankAccount class to become a part of each BankAccount object's behavior. The transactionFee method accepts a fee amount (a real number) as a parameter, and applies that fee to the user's past transactions. The fee is applied once for the first transaction, twice for the second transaction, three times for the third, and so on. These fees are subtracted out from the user's overall balance. If the user's balance is large enough to afford all of the fees with greater than $0.00 remaining, the method returns true. If the balance cannot afford all of the fees, the balance is left as 0.0 and the method returns false.

// Constructs a BankAccount // object with the given id, and // 0 balance and transactions. public BankAccount(String id) // returns the field values public double getBalance() public String getID() // Adds the amount to the balance // if it is between 0-500. // Also counts as 1 transaction. public void deposit(double amount) // Subtracts the amount from // the balance if the user has // enough money. // Also counts as 1 transaction. public void withdraw(double amount)

For example, given the following BankAccount object: BankAccount savings = new BankAccount("Jimmy"); savings.deposit(10.00); savings.deposit(50.00); savings.deposit(10.00); savings.deposit(70.00);

// your method would go here }

The account at that point has a balance of $140.00. If the following call were made: savings.transactionFee(5.00)

Then the account would be deducted $5 + $10 + $15 + $20 for the four transactions, leaving a final balance of $90.00. The method would return true. If a second call were made, savings.transactionFee(10.00)

Then the account would be deducted $10 + $20 + $30 + $40 for the four transactions, leaving a final balance of $0.00. The method would return false.

9 of 9


Sample Final Exam #3 Key 1. Array Mystery Call int[] a1 = {42}; arrayMystery(a1);

Final Contents of Array [42]

int[] a2 = {1, 8, 3, 6}; arrayMystery(a2);

[1, 8, 4, 6]

int[] a3 = {5, 5, 5, 5, 5}; arrayMystery(a3);

[5, 6, 5, 6, 5]

int[] a4 = {10, 7, 9, 6, 8, 5}; arrayMystery(a4);

[10, 8, 10, 7, 9, 5]

int[] a5 = {1, 0, 1, 0, 0, 1, 0}; arrayMystery(a5);

[1, 1, 1, 1, 0, 2, 0]

2. Reference Semantics Mystery 2 [0, 0, 1, 0] 1 [0, 0, 1, 0] 3 [0, 0, 1, 1] 2 [0, 0, 1, 1]

3. Inheritance Mystery Eins Eins 1 Zwei 2

Eins 1

Eins Eins 1 Eins 2 Vier Drei Drei 1 Zwei 2 Drei 1 Drei Drei 1 Zwei 2

Vier 2

Drei 1

1 of 6


4. File Processing (three solutions shown)

public static void coinFlip(Scanner input) { while (input.hasNextLine()) { Scanner lineScan = new Scanner(input.nextLine().toUpperCase()); int heads = 0; int total = 0; while (lineScan.hasNext()) { total++; if (lineScan.next().equals("H")) { heads++; } }

}

}

double percent = 100.0 * heads / total; System.out.printf("%d heads (%.1f%%)\n", heads, percent); if (percent > 50) { System.out.println("You win!"); } System.out.println();

public static void coinFlip(Scanner input) { while (input.hasNextLine()) { String line = input.nextLine(); Scanner lineScan = new Scanner(line); int heads = 0; int tails = 0; while (lineScan.hasNext()) { String flip = lineScan.next(); if (flip.equalsIgnoreCase("H")) { heads++; } else { tails++; } }

}

}

double percent = 100.0 * heads / (heads + tails); System.out.printf("%d heads (%.1f%%)\n", heads, percent); if (percent > 50) { System.out.println("You win!"); } System.out.println();

public static void coinFlip(Scanner input) { while (input.hasNextLine()) { String line = input.nextLine().toLowerCase(); int heads = 0; int tails = 0; for (int i = 0; i < line.length(); i++) { if (line.charAt(i) == 'h') { heads++; } else if (line.charAt(i) == 't') { tails++; } }

}

}

double percent = 100.0 * heads / (heads + tails); System.out.printf("%d heads (%.1f%%)\n", heads, percent); if (percent > 50) { System.out.println("You win!"); } System.out.println();

2 of 6


5. File Processing (two solutions shown) public static int findFirstMatch(Scanner input, String[] keywords) { int lineNum = 0; while (input.hasNextLine()) { String line = input.nextLine(); Scanner lineScan = new Scanner(line); lineNum++; while (lineScan.hasNext()) { String word = lineScan.next(); for (int i = 0; i < keywords.length; i++) { if (keywords[i].equalsIgnoreCase(word)) { return lineNum; } } } } return -1; } public static int findFirstMatch(Scanner s, String[] k) { String[] sorted = Arrays.copyOf(k, k.length); for (int i = 0; i < sorted.length; i++) { sorted[i] = sorted[i].toLowerCase(); } Arrays.sort(sorted); for (int line = 1; s.hasNextLine(); line++) { Scanner words = new Scanner(s.nextLine()); while (words.hasNext()) { if (Arrays.binarySearch(sorted, words.next().toLowerCase()) >= 0) { return line; } } } return -1; }

3 of 6


6. Array Programming (four solutions shown) public static int range(int[] a) { int min = 0; int max = 0; for (int i = 0; i < a.length; i++) { if (i == 0 || a[i] < min) { min = a[i]; } if (i == 0 || a[i] > max) { max = a[i]; } }

}

int valueRange = max - min + 1; return valueRange;

public static int range(int[] a) { int min = a[0]; int max = a[0]; for (int i = 1; i < a.length; i++) { min = Math.min(min, a[i]); max = Math.max(max, a[i]); } return max - min + 1; } public static int range(int[] a) { int[] copy = new int[a.length]; for (int i = 0; i < a.length; i++) { copy[i] = a[i]; } Arrays.sort(copy); return copy[copy.length - 1] - copy[0] + 1; } public static int range(int[] a) { int range = 1; for (int i = 0; i < a.length; i++) { for (int j = 0; j < a.length; j++) { int difference = Math.abs(a[i] - a[j]) + 1; if (difference > range) { range = difference; } } } }

return range;

4 of 6


7. Array Programming (three solutions shown) public static void zeroOut(int[] a1, int[] a2) { for (int i = 0; i <= a1.length - a2.length; i++) { int count = 0; for (int j = 0; j < a2.length; j++) { if (a1[i + j] == a2[j]) { count++; } } if (count == a2.length) { // found it for (int j = 0; j < a2.length; j++) { a1[i + j] = 0; } } } } public static void zeroOut(int[] a1, int[] a2) { int i2 = 0; for (int i1 = 0; i1 < a1.length; i1++) { if (a1[i1] == a2[i2]) { i2++; if (i2 == a2.length) { // found it for (int i = 0; i < a2.length; i++) { a1[i1 - i] = 0; } i2 = 0; } } else { i2 = 0; } } } public static void zeroOut(int[] a1, int[] a2) { int i1 = 0; int i2 = 0; while (i1 < a1.length) { if (a1[i1] == a2[i2]) { i2++; if (i2 == a2.length) { // found it while (i2 > 0) { a1[i1 - i2 + 1] = 0; i2--; } } } else { i2 = 0; } i1++; } }

5 of 6


8. Critters (two solutions shown) public class Dragonfly extends Critter { private int moves; private int right; private int maxRight; private boolean up; public Dragonfly() { moves = 0; right = 0; maxRight = 1; up = false; } public boolean eat() { maxRight++; return true; }

}

public Direction getMove() { moves++; if (right > 0) { right--; return Direction.EAST; } else { right = maxRight; up = !up; if (up) { return Direction.NORTH; } else { return Direction.SOUTH; } } }

public class Dragonfly extends Critter { private int moves = 0; private int east = 1; public boolean eat() { east++; return true; }

}

public Direction getMove() { moves++; if (moves > 2 * east + 2) { moves = 1; } if (moves == 1) { return Direction.NORTH; } else if (moves == east + 2) { return Direction.SOUTH; } else { return Direction.EAST; } }

9. Objects (two solutions shown) public boolean transactionFee(double amount) { for (int i = 1; i <= transactions; i++) { balance -= amount * i; }

}

if (balance > 0.0) { return true; } else { balance = 0.0; return false; }

public boolean transactionFee(double amount) { for (int i = 1; i <= transactions; i++) { balance = Math.max(0.0, balance - amount * i); } return balance > 0.0; }

6 of 6


Sample Final Exam #4 (Winter 2008)

1. Array Mystery Consider the following method: public static void arrayMystery(int[] a) { for (int i = a.length - 1; i >= 0; i--) { if (a[i] == a[a.length - i - 1]) { a[i]++; a[a.length - i - 1]++; } } }

Indicate in the right-hand column what values would be stored in the array after the method arrayMystery executes if the integer array in the left-hand column is passed as a parameter to it.

Original Contents of Array

Final Contents of Array

int[] a1 = {1, 8, 3, 8, 7}; arrayMystery(a1);

_____________________________

int[] a2 = {4, 0, 0, 4, 0, 0, 4, 0}; arrayMystery(a2);

_____________________________

int[] a3 = {9, 8, 7, 6, 4, 6, 2, 9, 9}; arrayMystery(a3);

_____________________________

int[] a4 = {42}; arrayMystery(a4);

_____________________________

int[] a5 = {5, 5, 5, 6, 5, 5, 5}; arrayMystery(a5);

_____________________________

1 of 9


2. Reference Semantics Mystery The following program produces 4 lines of output. Write the output below, as it would appear on the console. import java.util.*;

// for Arrays class

public class ReferenceMystery { public static void main(String[] args) { int x = 0; int[] a = new int[2]; mystery(x, a); System.out.println(x + " " + Arrays.toString(a)); x++; a[1] = a.length; mystery(x, a); System.out.println(x + " " + Arrays.toString(a)); } public static void mystery(int x, int[] list) { list[x]--; x++; System.out.println(x + " " + Arrays.toString(list)); } }

2 of 9


3. Inheritance Mystery Assume that the following classes have been defined: public class Brian extends Lois { public void b() { a(); System.out.print("Brian b }

");

public class Meg { public void a() { System.out.print("Meg a } public void b() { System.out.print("Meg b }

public String toString() { return "Brian"; } }

");

");

public String toString() { return "Meg"; }

public class Lois extends Meg { public void a() { System.out.print("Lois a super.a(); }

");

public void b() { System.out.print("Lois b }

");

} public class Stewie extends Brian { public void a() { super.a(); System.out.print("Stewie a }

}

");

public String toString() { return super.toString() + " Stewie"; } }

Given the classes above, what output is produced by the following code? Meg[] elements = {new Lois(), new Stewie(), new Meg(), new Brian()}; for (int i = 0; i < elements.length; i++) { elements[i].a(); System.out.println(); elements[i].b(); System.out.println(); System.out.println(elements[i]); System.out.println(); }

3 of 9


4. File Processing Write a static method named tokenStats that accepts as a parameter a Scanner containing a series of tokens. It should print out the sum of all the tokens that are legal integers, the sum of all the tokens that are legal doubles but not integers, and the total number of tokens of any kind. For example, if a Scanner called data contains the following tokens: 3 3.14 10 squid 10.x 6.0

Then the call of tokenStats(data); should print the following output: integers: 13 real numbers: 9.14 total tokens: 6

If the Scanner has no tokens, the method should print: integers: 0 real numbers: 0.0 total tokens: 0

4 of 9


5. File Processing Write a static method named pizza that accepts as its parameter a Scanner for an input file. Imagine that a college dorm room contains several boxes of leftover pizza. A complete pizza has 8 slices. The pizza boxes left in the room each contain either an entire pizza, half a pizza (4 slices), or a single slice. Your method's task is to figure out the fewest boxes needed to store all leftover pizza, if all the partial pizzas were consolidated together as much as possible. Your pizza method will read lines from its input Scanner where each line of data represents the contents of the pizza boxes in one dorm room. These contents are written as "whole", "half", or "slice" in either upper or lower case, separated by at least one space. You should print to the console the number of pizza boxes necessary to store all the slices of pizza out of the total. You must use a whole number of boxes. For example, if there are 10 total slices of pizza in a dorm room, 2 pizza boxes are needed: one for the first whole pizza, and one for the final 2 slices. Note that some lines might be blank, meaning that the dorm room contains no pizzas; output for such a case is shown below. For example, consider the following input file representing 5 dorm rooms (note that the fourth is blank): slice half slice whole whole half half half whole HALF WhoLE half WHOLE WhOlE Slice half sLICe halF WHOLE slice WHOLE SLICE whole SLICE whole slice WHOLE half slice

For the input above, your method should produce the following output: 5 / 8 pizza boxes used 7 / 10 pizza boxes used 6 / 10 pizza boxes used 0 / 0 pizza boxes used 1 / 1 pizza boxes used

The format of your output must exactly match that shown above. Assume the Scanner contains at least 1 line of input, and that no line will contain tokens other than whole/half/slice.

5 of 9


6. Array Programming Write a static method named sweep that accepts an array of integers as a parameter and performs a single "sweep" over the array from lowest to highest index, comparing adjacent elements. If a pair of adjacent elements are out of order (if the element at the lower index has a greater value than the element at the higher index), your method should swap them. For example, in an array of 6 elements, your method first examines elements at indexes 0-1, then 1-2, then 2-3, 3-4, and 4-5, swapping if they are out of order. One side effect of this method is that the single element with the largest value will be moved into the final index of the array. (Repeated "sweeping" can be used to sort an array.) If your method ends up swapping any elements, it should return true to indicate that the array was changed. Otherwise (if the array was already in ascending order before the sweep), it should return false. The table below shows calls to your method and the array contents after the method is finished executing:

Array / Call int[] a1 = {1, 6, 2, 7, 3, 6, 4}; sweep(a1); int[] a2 = {9, 4, 2, 1, 3, 12, 14, 6, 8}; sweep(a2); int[] a3 = {3, 4, 8, 2, 1, 8, 8, 4, 12}; sweep(a3); int[] a4 = {-1, -4, 17, 4, -1}; sweep(a4); int[] a5 = {2, 3, 5, 7, 11, 13}; sweep(a5); int[] a6 = {42}; sweep(a6);

Contents of Array After Call

Value Returned

{1, 2, 6, 3, 6, 4, 7}

true

{4, 2, 1, 3, 9, 12, 6, 8, 14}

true

{3, 4, 2, 1, 8, 8, 4, 8, 12}

true

{-4, -1, 4, -1, 17}

true

{2, 3, 5, 7, 11, 13}

false

{42}

false

You may assume that the array contains at least one element (its length is at least 1). Do not make assumptions about the values of the elements in the array; they could be very large or small, etc.

6 of 9


7. Array Programming Write a static method named hasMirrorTwice that accepts two arrays of integers a1 and a2 as parameters and returns true if a1 contains all the elements of a2 in reverse order at least twice (and false otherwise). For example, if a2 stores the elements {1, 2, 3} and a1 stores the elements {6, 3, 2, 1, 4, 1, 3, 2, 1, 5}, your method would return true. Assume that both arrays passed to your method will have a length of at least 1. This means that the shortest possible mirror will be of length 1, representing a single element (which is its own mirror). A sequence that is a palindrome (the same forwards as backwards) is considered its own mirror and should be included in your computations. For example, if a1 is {6, 1, 2, 1, 4, 1, 2, 1, 5} and a2 is {1, 2, 1}, your method should return true. The two occurrences of the mirror might overlap, as shown in the fourth sample call below. The following table shows some calls to your method and their expected results:

Array

Returned Value

int[] a1 = {6, 1, 2, 1, 3, 1, 3, 2, 1, 5}; int[] a2 = {1, 2}; int[] a3 = {5, 8, 4, 18, 5, 42, 4, 8, 5, 5}; int[] a4 = {4, 8, 5}; int[] a5 = {6, 3, 42, 18, 12, 5, 3, 42, 3, 42}; int[] a6 = {42, 3}; int[] a7 = {6, 1, 2, 4, 2, 1, 2, 4, 2, 1, 5}; int[] a8 = {1, 2, 4, 2, 1}; int[] a9 = {0, 0}; int[] aa = {0}; int[] ab = {8, 9, 2, 1}; int[] ac = {5, 7, 1, 2, 9, 8};

hasMirrorTwice(a1, a2) returns true hasMirrorTwice(a3, a4) returns false hasMirrorTwice(a5, a6) returns true hasMirrorTwice(a7, a8) returns true hasMirrorTwice(a9, aa) returns true hasMirrorTwice(ab, ac) returns false

Do not modify the contents of the arrays passed to your method as parameters.

7 of 9


8. Critters Write a class Crab that extends the Critter class from the Critters assignment, along with its movement behavior. Crab objects move in the following repeating pattern:        

west 1 time, east 2 times west 3 times, east 4 times west 5 times, east 6 times west 7 times, east 8 times west 7 times, east 6 times west 5 times, east 4 times west 3 times, east 2 times (entire pattern repeats)

Write your complete Crab class below. All other aspects of Crab besides movement use the default critter behavior. You may add anything needed to your class (fields, constructors, etc.) to implement this behavior appropriately. Note: You will receive a maximum of only 5 points if you "hard-code" the entire set of movements (by simply keeping a move counter and using an extremely long chain of if or if/else statements) rather than recognizing the crab's overall movement pattern.

8 of 9


9. Classes and Objects Suppose that you are provided with a pre-written class Date as described at right. (The headings are shown, but not the method bodies, to save space.) Assume that the fields, constructor, and methods shown are already implemented. You may refer to them or use them in solving this problem if necessary.

// Each Date object stores a single // month/day such as September 19. // This class ignores leap years. public class Date { private int month; private int day; // Constructs a date with // the given month and day. public Date(int m, int d)

Write a method named daysTillXmas that will be placed inside the Date class to become a part of each Date object's behavior. The daysTillXmas method returns how many days away the Date object is from Christmas, December 25, in the same year. For example:   

// Returns the date's day. public int getDay() // Returns the date's month. public int getMonth() // Returns the number of days // in this date's month. public int daysInMonth()

Dec. 12 is 13 days away from Christmas. Nov. 22 is 33 days away (the 8 remaining days in November, and 25 more to reach 12/25). Sep. 3 is 113 days away (the 27 remaining days in September, the 61 days in October and November, and 25 more to reach 12/25).

// Modifies this date's state // so that it has moved forward // in time by 1 day, wrapping // around into the next month // or year if necessary. // example: 9/19 -> 9/20 // example: 9/30 -> 10/1 // example: 12/31 -> 1/1

Here is an example call of your method that would print 113: Date d = new Date(9, 3); System.out.println(d.daysTillXmas());

Here are more dates and the values that the method should return when called on Date objects representing them. 12/25 is 0 days away from itself, and days after 12/25 return a negative value.     

public void nextDay()

// 113

// your method would go here }

Dec. 25 is 0 days away from Christmas. Dec. 26 is -1 days away from Christmas. Dec. 31 is -6 days away from Christmas. Jan. 1 is 358 days away from Christmas. Feb. 14 is 314 days away from Christmas.

Your method should not modify the Date object's state, such as by changing its day or month field values. You will not receive full credit if your solution uses 12 if/else statements or explicitly enumerates the days in each month.

9 of 9


Sample Final Exam #4 Key 1. Array Mystery Expression int[] a1 = {1, 8, 3, 8, 7}; arrayMystery(a1);

Final Contents of Array [1, 10, 5, 10, 7]

int[] a2 = {4, 0, 0, 4, 0, 0, 4, 0}; arrayMystery(a2);

[4, 0, 2, 4, 0, 2, 4, 0]

int[] a3 = {9, 8, 7, 6, 4, 6, 2, 9, 9}; arrayMystery(a3);

[11, 8, 7, 8, 6, 8, 2, 9, 11]

int[] a4 = {42}; arrayMystery(a4);

[44]

int[] a5 = {5, 5, 5, 6, 5, 5, 5}; arrayMystery(a5);

[7, 7, 7, 8, 7, 7, 7]

2. Reference Semantics Mystery 1 [-1, 0] 0 [-1, 0] 2 [-1, 1] 1 [-1, 1]

3. Inheritance Mystery Lois a Lois b Meg

Meg a

Lois a Meg a Lois a Meg a Brian Stewie

Stewie a Stewie a

Brian b

Meg a Meg b Meg Lois a Lois a Brian

Meg a Meg a

Brian b

1 of 5


4. File Processing (four solutions shown) public static void tokenStats(Scanner s) { int ints = 0; double doubles = 0.0; int total = 0; while (s.hasNext()) { if (s.hasNextInt()) { ints += s.nextInt(); } else if (s.hasNextDouble()) { doubles += s.nextDouble(); } else { s.next(); } total++; }

}

System.out.println("integers: " + ints); System.out.println("real numbers: " + doubles); System.out.println("total tokens: " + total);

5. File Processing (four solutions shown) public static void pizza(Scanner input) { while (input.hasNextLine()) { String line = input.nextLine(); Scanner lineScan = new Scanner(line.toLowerCase()); double boxes = 0.0; int totalBoxes = 0; while (lineScan.hasNext()) { totalBoxes++; String box = lineScan.next(); if (box.equals("whole")) { boxes++; // 1 } else if (box.equals("half")) { boxes += 0.5; // 1/2 } else { // "slice" boxes += 0.125; // 1/8 } } System.out.println((int) Math.ceil(boxes) + " / " + totalBoxes + " pizza boxes used"); } } public static void pizza(Scanner input) { while (input.hasNextLine()) { Scanner lineScan = new Scanner(input.nextLine().toLowerCase()); int slices = 0; int totalBoxes = 0; while (lineScan.hasNext()) { totalBoxes++; String box = lineScan.next(); if (box.equals("whole")) { slices += 8; } else if (box.equals("half")) { slices += 4; } else { slices++; } }

}

}

int boxes = slices / 8; // round up to an even box if (slices % 8 != 0) { boxes++; } System.out.println(boxes + " / " + totalBoxes + " pizza boxes used");

2 of 5


public static void pizza(Scanner input) { while (input.hasNextLine()) { Scanner lineScan = new Scanner(input.nextLine().toLowerCase()); int slices = 0; int totalBoxes = 0; while (lineScan.hasNext()) { totalBoxes++; String box = lineScan.next(); if (box.equals("whole")) { slices += 8; } else if (box.equals("half")) { slices += 4; } else { slices++; } }

}

}

if (slices % 8 != 0) { // round up to an even box slices += (8 - slices % 8); } System.out.println(slices / 8 + " / " + totalBoxes + " pizza boxes used");

public static void pizza(Scanner input) { while (input.hasNextLine()) { Scanner lineScan = new Scanner(input.nextLine().toLowerCase()); int slices = 0; int halves = 0; int wholes = 0; int totalBoxes = 0; while (lineScan.hasNext()) { totalBoxes++; String box = lineScan.next(); if (box.equals("whole")) { wholes++; } else if (box.equals("half")) { halves++; } else { slices++; } }

}

}

int boxes = (int) Math.ceil((8*wholes + 4*halves + slices) / 8.0); System.out.println(boxes + " / " + totalBoxes + " pizza boxes used");

6. Array Programming (two solutions shown) public static boolean sweep(int[] a) { boolean changed = false; for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; changed = true; } } return changed; } public static boolean sweep(int[] a) { int count = 0; for (int i = 1; i < a.length; i++) { int temp1 = a[i]; int temp2 = a[i - 1];

}

}

if (a[i - 1] > a[i]) { a[i - 1] = temp1; a[i] = temp2; count++; }

if (count > 0) { return true; } else { return false; }

3 of 5


7. Array Programming (four solutions shown) public static boolean hasMirrorTwice(int[] a1, int[] a2) { int mirrorCount = 0; for (int i = 0; i <= a1.length - a2.length; i++) { int count = 0; for (int j = 0; j < a2.length; j++) { if (a1[i + j] == a2[a2.length - 1 - j]) { count++; } } if (count >= a2.length) { mirrorCount++; } } }

return mirrorCount >= 2;

public static boolean hasMirrorTwice(int[] a1, int[] a2) { int mirrorCount = 0; for (int i = a2.length - 1; i < a1.length; i++) { int count = 0; for (int j = 0; j < a2.length; j++) { if (a1[i - j] == a2[j]) { count++; } } if (count >= a2.length) { mirrorCount++; } } }

return mirrorCount >= 2;

public static boolean hasMirrorTwice(int[] a1, int[] a2) { // copy/reverse a2 into a3 int[] a3 = new int[a2.length]; for (int i = 0; i < a2.length; i++) { a3[i] = a2[a2.length - 1 - i]; } int mirrorCount = 0; for (int i = 0; i <= a1.length - a3.length; i++) { int count = 0; for (int j = 0; j < a3.length; j++) { if (a1[i + j] == a3[j]) { count++; } } if (count >= a3.length) { mirrorCount++; } }

}

if (mirrorCount >= 2) { return true; } else { return false; }

public static boolean hasMirrorTwice(int[] a1, int[] a2) { int mirrorCount = 0; for (int i = a1.length - 1; i >= 0; i--) { int count = 0; for (int j = 0; j < a2.length; j++) { if (i + j < a1.length && a1[i + j] == a2[a2.length - 1 - j]) { count++; } } if (count >= a2.length) { mirrorCount++; } } }

return mirrorCount >= 2;

4 of 5


8. Critters (two solutions shown) public class Crab extends Critter { private int max = 1; private int moves = 0; private boolean wider = true; public Direction getMove() { if (moves == max) { moves = 0; if (wider) { max++; } else { max--; } if (max == 8 || max == 1) { wider = !wider; } }

}

}

moves++; if (max % 2 == 0) { return Direction.EAST; } else { return Direction.WEST; }

public class Crab extends Critter { private int moves = 0; public Direction getMove() { moves++; if (moves == 64) { // 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36 moves = 1; // 36 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 64 } int sum = 0; for (int i = 1; i <= 8; i++) { if (moves >= sum && moves <= sum + i) { if (i % 2 == 0) { return Direction.EAST; } else { return Direction.WEST; } } sum += i; }

}

}

for (int i = 7; i >= 2; i--) { if (moves >= sum && moves <= sum + i) { if (i % 2 == 0) { return Direction.EAST; } else { return Direction.WEST; } } sum += i; } return Direction.CENTER; // it will never reach here

9. Objects (two solutions shown)

public int daysTillXmas() { int days = 0; Date copy = new Date(month, day); while (copy.month < 12) { // get to December days += copy.daysInMonth(); copy.month++; } return days + 25 - day; } public int daysTillXmas() { if (month == 12) { return 25 - day; } else { int days = 0; Date copy = new Date(month, day); while (copy.month != 12 || copy.day != 25) { // get to December copy.nextDay(); days++; } return days; } }

5 of 5


Sample Final Exam #5 (Autumn 2006; thanks to Ruth Anderson)

1. Array Mystery Consider the following method: public static void arrayMystery(int[] array) { for (int i = 0; i < array.length - 1; i++) { if (array[i] < array[i + 1]) { array[i] = array[i + 1]; } } }

Indicate in the right-hand column what values would be stored in the array after the method mystery executes if the integer array in the left-hand column is passed as a parameter to mystery. Original Contents of Array

Final Contents of Array

int[] a1 = {2, 4}; arrayMystery(a1);

_____________________________

int[] a2 = {1, 3, 6}; arrayMystery(a2);

_____________________________

int[] a3 = {7, 2, 8, 4}; arrayMystery(a3);

_____________________________

int[] a4 = {5, 2, 7, 2, 4}; arrayMystery(a4);

_____________________________

int[] a5 = {2, 4, 6, 3, 7, 9}; arrayMystery(a5);

_____________________________

1 of 9


2. Reference Semantics Mystery The following program produces 4 lines of output. Write the output below, as it would appear on the console. import java.util.*;

// for Arrays class

public class Mystery { public static void main(String[] args) { int x = 1; int[] a = new int[4]; x = x * 2; mystery(x, a); System.out.println(x + " " + Arrays.toString(a)); x = x * 2; mystery(x, a); System.out.println(x + " " + Arrays.toString(a)); } public static void mystery(int x, int[] a) { x = x * 2; if (x > 6) { a[2] = 14; a[1] = 9; } else { a[0] = 9; a[3] = 14; } System.out.println(x + " " + Arrays.toString(a)); } }

2 of 9


3. Inheritance Mystery Assume that the following classes have been defined: public class Ice extends Fire { public void method1() { System.out.print("Ice 1 } }

");

public class Fire { public String toString() { return "Fire"; } public void method1() { method2(); System.out.print("Fire 1 }

public class Rain extends Fire { public String toString() { return "Rain"; } public void method1() { super.method1(); System.out.print("Rain 1 } }

");

");

public void method2() { System.out.print("Fire 2 }

");

public class Snow extends Rain { public void method2() { System.out.print("Snow 2 } }

");

}

Given the classes above, what output is produced by the following code? Fire[] elements = {new Fire(), new Snow(), new Rain(), new Ice()}; for (int i = 0; i < elements.length; i++) { System.out.println(elements[i]); elements[i].method1(); System.out.println(); elements[i].method2(); System.out.println(); System.out.println(); }

3 of 9


4. File Processing Write a static method named halfCaps that accepts as its parameter a Scanner holding a sequence of words and outputs to the console the same sequence of words with alternating casing (lowercase, uppercase, lowercase, uppercase, etc). The first word, third word, fifth word, and all other "odd" words should be in lowercase letters, whereas the second word, fourth word, sixth word, and all other "even" words should be in uppercase letters. For example, suppose the Scanner contains the following words. The QUick brown foX jumPED over the Sleepy student

For the purposes of this problem, we will use whitespace to separate words. You can assume that the sequence of words will not contain any numbers or punctuation and that each word will be separated by one space. For the input above, your method should produce the following output: the QUICK brown FOX jumped OVER the SLEEPY student

Your output should separate each word by a single space. The output may end with a space if you like. Note that the Scanner may contain no words or may contain an even or odd number of words.

4 of 9


5. File Processing Write a static method named countWords that accepts as its parameter a Scanner for an input file, and that outputs to the console the total number of lines and words found in the file as well as the average number of words per line. For example, consider the following input file: You must show: your Student ID card to 1) a TA or 2) the instructor before leaving the room.

For the purposes of this problem, we will use whitespace to separate words. That means that some words might include punctuation, as in "show:" and "1)". (This is the same definition that the Scanner uses for tokens.) For the input above, your method should produce the following output: Total lines = 6 Total words = 19 Average words per line = 3.167

The format of your output must exactly match that shown above, including rounding the words per line to 3 decimal places. Notice that input lines can be blank. You may assume that the Scanner contains at least 1 line of input.

5 of 9


6. Array Programming Write a static method named mode that takes an array of integers as a parameter and that returns the value that occurs most frequently in the array. Assume that the integers in the array appear in sorted order. For example, if a variable called list stores the following values: int[] list = {-3, 1, 4, 4, 4, 6, 7, 8, 8, 8, 8, 9, 11, 11, 11, 12, 14, 14};

Then the call of mode(list) should return 8 because 8 is the most frequently occurring value in the array, appearing four times. If two or more values tie for the most occurrences, return the one with the lowest value. For example, if the array stores the following values, the call of mode(list) should return 2 despite the fact that there are also three 9s: int[] list = {1, 2, 2, 2, 5, 7, 9, 9, 9};

If the array's elements are unique, every value occurs exactly once, so the first element value should be returned. You may assume that the array's length is at least 1. If the array contains only one element, that element's value is considered the mode.

6 of 9


7. Array Programming Write a static method named contains that accepts two arrays of integers a1 and a2 as parameters and that returns a boolean value indicating whether or not a2's sequence of elements appears in a1 (true for yes, false for no). The sequence of elements in a2 may appear anywhere in a1 but must appear consecutively and in the same order. For example, if variables called list1 and list2 store the following values: int[] list1 = {1, 6, 2, 1, 4, 1, 2, 1, 8}; int[] list2 = {1, 2, 1};

Then the call of contains(list1, list2) should return true because list2's sequence of values {1, 2, 1} is contained in list1 starting at index 5. If list2 had stored the values {2, 1, 2}, the call of contains(list1, list2) would return false because list1 does not contain that sequence of values. Any two lists with identical elements are considered to contain each other, so a call such as contains(list1, list1) should return true. You may assume that both arrays passed to your method will have lengths of at least 1. You may not use any Strings to help you solve this problem, nor methods that produce Strings such as Arrays.toString.

7 of 9


8. Critters Write a class Shark that extends the Critter class from Homework 8. Shark objects should alternate between moving to the north and south as follows: first move 1 step north, then 2 steps south, then 3 steps north, then 4 steps south, then 5 steps north, then 6 steps south, and so on, each time moving one farther than previously. You may add anything needed (fields, other methods, constructors, etc.) to implement this behavior appropriately.

8 of 9


9. Classes and Objects Suppose that you are provided with a pre-written class ClockTime as described at right. (The headings are shown, but not the method bodies, to save space.) Assume that the fields, constructor, and methods shown are already implemented. You may refer to them or use them in solving this problem if necessary. Write an instance method named advance that will be placed inside the ClockTime class to become a part of each ClockTime object's behavior. The advance method accepts a number of minutes as its parameter and moves the ClockTime object forward in time by that amount of minutes. The minutes passed could be any non-negative number, even a large number such as 500 or 1000000. If necessary, your object might wrap into the next hour or day, or it might wrap from the morning ("AM") to the evening ("PM") or vice versa. A ClockTime object doesn't care about what day it is; if you advance by 1 minute from 11:59 PM, it becomes 12:00 AM.

// A ClockTime object represents // an hour:minute time during // the day or night, such as // 10:45 AM or 6:27 PM. public class ClockTime { private int hour; private int minute; private String amPm;

For example, if the following object is declared in client code: ClockTime time = new ClockTime(6, 27, "PM");

// Constructs a new time for // the given hour/minute public ClockTime(int h, int m, String ap) // returns the field values public int getHour() public int getMinute() public String getAmPm() // returns String for time; // example: "6:27 PM" public String toString() // your method would go here

The following calls to your method would modify the object's state as } indicated in the comments. time.advance(1); time.advance(30); time.advance(5); time.advance(60); time.advance(128); time.advance(180); time.advance(1440); time.advance(21075);

// 6:28 PM // 6:58 PM // 7:03 PM // 8:03 PM // 10:11 PM // 1:11 AM // 1:11 AM // 4:26 PM

(1 day later) (2 weeks later)

Assume that the state of the ClockTime object is valid at the start of the call and that the amPm field stores either "AM" or "PM".

9 of 9


Sample Final Exam #5 Key 1.

Array Final contents --------------------------------------------------------{2, 4} {4, 4} {1, 3, 6} {3, 6, 6} {7, 2, 8, 4} {7, 8, 8, 4} {5, 2, 7, 2, 4} {5, 7, 7, 4, 4} {2, 4, 6, 3, 7, 9} {4, 6, 6, 7, 9, 9}

2.

4 [9, 0, 0, 14] 2 [9, 0, 0, 14] 8 [9, 9, 14, 14] 4 [9, 9, 14, 14]

3.

Fire Fire 2 Fire 2

Fire 1

Rain Snow 2 Snow 2

Fire 1

Rain 1

Rain Fire 2 Fire 2

Fire 1

Rain 1

Fire Ice 1 Fire 2

4. Three solutions are shown. public static void halfCaps(Scanner input) { boolean odd = true; while (input.hasNext()) { String next = input.next(); if (odd) { System.out.print(next.toLowerCase() + " "); } else { System.out.print(next.toUpperCase() + " "); } odd = !odd; } } public static void halfCaps(Scanner input) { int count = 0; while (input.hasNext()) { if (count % 2 == 0) { System.out.print(input.next().toLowerCase() + " "); } else { System.out.print(input.next().toUpperCase() + " "); } count++; } } public static void halfCaps(Scanner input) { while (input.hasNext()) { System.out.print(input.next().toLowerCase() + " "); if (input.hasNext()) { System.out.print(input.next().toUpperCase() + " "); } } }

5.

public static void countWords(Scanner input) { int lineCount = 0; int wordCount = 0; while (input.hasNextLine()) { String line = input.nextLine(); lineCount++; Scanner lineScan = new Scanner(line); while (lineScan.hasNext()) { String next = lineScan.next(); wordCount++; } }

}

double averageWords = (double) wordCount / lineCount; System.out.println("Total lines = " + lineCount); System.out.println("Total words = " + wordCount); System.out.printf("Average words per line = %.3f\n", averageWords);

1 of 3


6. public static int mode(int[] a) { int count = 1; int maxCount = 1; int modeValue = a[0]; for (int i = 0; i < a.length - 1; i++) { if (a[i] == a[i + 1]) { count++; if (count > maxCount) { modeValue = a[i]; maxCount = count; } } else { count = 1; } } }

return modeValue;

7. Four solutions are shown. public static boolean contains(int[] a1, int[] a2) { for (int i = 0; i <= a1.length - a2.length; i++) { boolean found = true; for (int j = 0; j < a2.length; j++) { if (a1[i + j] != a2[j]) { found = false; } } if (found) { return true; } } return false; } // varation of first solution that uses count instead of boolean public static boolean contains(int[] a1, int[] a2) { for (int i = 0; i <= a1.length - a2.length; i++) { int count = 0; for (int j = 0; j < a2.length; j++) { if (a1[i + j] == a2[j]) count++; } if (count == a2.length) return true; } return false; } public static boolean contains(int[] a1, int[] a2) { int i1 = 0; int i2 = 0; while (i1 < a1.length && i2 < a2.length) { if (a1[i1] != a2[i2]) { // doesn't match; start over i2 = 0; } if (a1[i1] == a2[i2]) { i2++; } i1++; } }

return i2 >= a2.length;

public static boolean contains(int[] a1, int[] a2) { for (int i = 0; i < a1.length; i++) { int j = 0; while (j < a2.length && i + j < a1.length && a1[i + j] == a2[j]) j++; if (j == a2.length) return true; } return false; }

2 of 3


8. Two solutions are shown. public class Shark extends Critter { private int count; private int max; private Direction direction; public Shark() { count = 0; max = 1; direction = Direction.NORTH; }

}

public Direction getMove() { count++; if (count > max) { count = 1; max++; if (direction == Direction.NORTH) { direction = Direction.SOUTH; } else { direction = Direction.NORTH; } } return direction; }

public class Shark extends Critter { private int count = 0; private int max = 1;

}

public Direction getMove() { count++; if (count > max) { count = 1; max++; } if (max % 2 == 0) { return Direction.SOUTH; } else { return Direction.NORTH; } }

9. Two solutions are shown. public void advance(int mins) { minute += mins; // add into 'minute' field, then pull hours out 1 at a time while (minute >= 60) { minute -= 60; hour++; if (hour == 12) { if (amPm.equals("AM")) { amPm = "PM"; } else { amPm = "AM"; } } else if (hour > 12) { hour = 1; } } } public void advance(int mins) { int totalMinutes = hour % 12 * 60 + minute; // convert into absolute minutes representation if (amPm.equals("PM")) { totalMinutes += 12 * 60; // add 12 hours for PM } totalMinutes = (totalMinutes + mins) % (24 * 60); // move forward; throw away extra days hour = totalMinutes / 60; // convert back to hour/minute/amPm minute = totalMinutes % 60; if (hour >= 12) { amPm = "PM"; } else { amPm = "AM"; } if (hour == 0) { hour = 12; } else { hour = hour % 12; } }

3 of 3


Sample Final Exam #6 (Summer 2008; thanks to Hélène Martin)

1. Array Mystery Consider the following method: public static void arrayMystery(String[] a) { for (int i = 0; i < a.length; i++) { a[i] = a[i] + a[a.length - 1 - i]; } }

Indicate in the right-hand column what values would be stored in the array after the method arrayMystery executes if the array in the left-hand column is passed as a parameter to it.

Original Contents of Array

Final Contents of Array

String[] a1 = {"a", "b", "c"}; arrayMystery(a1);

_____________________________

String[] a2 = {"a", "bb", "c", "dd"}; arrayMystery(a2);

_____________________________

String[] a3 = {"z", "y", "142", "w", "xx"}; arrayMystery(a3);

_____________________________

1 of 9


2. Reference Semantics Mystery The following program produces 4 lines of output. Write the output below, as it would appear on the console. public class Pokemon { int level; public Pokemon(int level) { this.level = level; } } public class ReferenceMystery { public static void main(String[] args) { int hp = 10; Pokemon squirtle = new Pokemon(5); battle(squirtle, hp); System.out.println("Level " + squirtle.level + ", " + hp + " hp"); hp = hp + squirtle.level; battle(squirtle, hp + 1); System.out.println("Level " + squirtle.level + ", " + hp + " hp"); } public static void battle(Pokemon poke, int hp) { poke.level++; hp -= 5; System.out.println("Level " + poke.level + ", " + hp + " hp"); } }

2 of 9


3. Inheritance Mystery Assume that the following classes have been defined: public class Dog extends Cat { public void m1() { m2(); System.out.print("dog 1 } } public class Lion extends Dog { public void m2() { System.out.print("lion 2 super.m2(); }

");

public class Cat { public void m1() { System.out.print("cat 1 } public void m2() { System.out.print("cat 2 }

");

");

");

public String toString() { return "cat"; } }

public String toString() { return "lion"; } }

Given the classes above, what output is produced by the following code? Cat[] elements = {new Dog(), new Cat(), new Lion()}; for (int i = 0; i < elements.length; i++) { elements[i].m1(); System.out.println(); elements[i].m2(); System.out.println(); System.out.println(elements[i]); System.out.println(); }

3 of 9


4. File Processing Write a static method evaluate that accepts as a parameter a Scanner containing a series of tokens representing a numeric expression involving addition and subtraction and that returns the value of the expression. For example, if a Scanner called data contains the following tokens: 4.2 + 3.4 - 4.1

The call of evaluate(data); should evaluate the result as (4.2+3.4-4.1) = (7.6-4.1) = 3.5 and should return this value as its result. Every expression will begin with a real number and then will have a series of operator/number pairs that follow. The operators will be either + (addition) or - (subtraction). As in the example above, there will be spaces separating numbers and operators. You may assume the expression is legal. Your program should evaluate operators sequentially from left to right. For example, for this expression: 7.3 - 4.1 - 2.0

your method should evaluate the operators as follows: 7.3 - 4.1 - 2.0 = (7.3 - 4.1) - 2.0 = 3.2 - 2.0 = 1.2

The Scanner might contain just a number, in which case your method should return that number as its result.

4 of 9


5. File Processing Write a static method blackjack that accepts as its parameter a Scanner for an input file containing a hand of playing cards, and returns the point value of the hand in the card game Blackjack. A card has a rank and a suit. There are 13 ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, and King. There are 4 suits: Clubs, Diamonds, Hearts, and Spades. A Blackjack hand's point value is the sum of its cards' point values. A card's point value comes from its rank; the suit is irrelevant. In this problem, cards are worth the following points: Rank 2-10 Jack (J), Queen (Q), King (K) Ace (A)

Point Value The card's rank (for example, a 7 is worth 7 points) 10 points each 11 points (for this problem; simplified compared to real Blackjack)

The input file contains a single hand of cards, each represented by a pair of "<rank> <suit>" tokens. For example: 5 Diamonds Q Spades 2 Spades 3 Hearts

Given the above input, your method should return 20, since the cards' point values are 5 + 10 + 2 + 3 = 20. The input can be in mixed casing, have odd spacing between tokens, and can be split across lines. For example: 2 Hearts j SPADES 2 ClUbS A hearts

a

Diamonds

Given the above input, your method should return 36, since the cards' point values are 2 + 10 + 11 + 2 + 11 = 36. You may assume that the Scanner contains at least 1 card (two tokens) of input, and that no line will contain any tokens other than valid card data. The real game of Blackjack has many other rules that you should ignore for this problem, such as the notion of going "bust" once you exceed a score of 21.

5 of 9


6. Array Programming Write a static method named allPlural that accepts an array of strings as a parameter and returns true only if every string in the array is a plural word, and false otherwise. For this problem a plural word is defined as any string that ends with the letter S, case-insensitively. The empty string "" is not considered a plural word, but the single-letter string "s" or "S" is. Your method should return true if passed an empty array (one with 0 elements). The table below shows calls to your method and the expected values returned:

Array String[] a1 = {"snails", "DOGS", "Cats"}; String[] a2 = {"builds", "Is", "S", "THRILLs", "CS"}; String[] a3 = {}; String[] a4 = {"She", "sells", "sea", "SHELLS"}; String[] a5 = {"HANDS", "feet", "toes", "OxEn"}; String[] a6 = {"shoes", "", "socks"};

Call and Value Returned allPlural(a1) returns true allPlural(a2) returns true allPlural(a3) returns true allPlural(a4) returns false allPlural(a5) returns false allPlural(a6) returns false

For full credit, your method should not modify the array's elements.

6 of 9


7. Array Programming Write a static method named reverseChunks that accepts two parameters, an array of integers a and an integer "chunk" size s, and reverses every s elements of a. For example, if s is 2 and array a stores {1, 2, 3, 4, 5, 6}, a is rearranged to store {2, 1, 4, 3, 6, 5}. With an s of 3 and the same elements {1, 2, 3, 4, 5, 6}, array a is rearranged to store {3, 2, 1, 6, 5, 4}. The chunks on this page are underlined for convenience. If a's length is not evenly divisible by s, the remaining elements are untouched. For example, if s is 4 and array a stores {5, 4, 9, 2, 1, 7, 8, 6, 2, 10}, a is rearranged to store {2, 9, 4, 5, 6, 8, 7, 1, 2, 10}. It is also possible that s is larger than a's entire length, in which case the array is not modified at all. You may assume that s is 1 or greater (an s of 1 would not modify the array). If array a is empty, its contents should remain unchanged. The following table shows some calls to your method and their expected results:

Array and Call int[] a1 = {20, 10, 30, 60, 50, 40}; reverseChunks(a1, 2); int[] a2 = {2, 4, 6, 8, 10, 12, 14, 16}; reverseChunks(a2, 3); int[] a3 = {7, 1, 3, 5, 9, 8, 2, 6, 4, 10, 0, 12}; reverseChunks(a3, 5); int[] a4 = {1, 2, 3, 4, 5, 6}; reverseChunks(a4, 8); int[] a5 = {}; reverseChunks(a5, 2);

Array Contents After Call {10, 20, 60, 30, 40, 50} {6, 4, 2, 12, 10, 8, 14, 16} {9, 5, 3, 1, 7, 10, 4, 6, 2, 8, 0, 12} {1, 2, 3, 4, 5, 6} {}

7 of 9


8. Critters Write a class Minnow that extends Critter from HW8, along with its movement and eating behavior. All other aspects of Minnow use the defaults. Add fields, constructors, etc. as necessary to your class. Minnow objects initially move in a S/E/S/E/... pattern. However, when a Minnow encounters food (when its eat

method is called), it should do all of the following:  

Do not eat the food. Start the movement cycle over. In other words, the next move after eat is called should always be South.

Lengthen and reverse the horizontal portion of the movement cycle pattern. The Minnow should reverse its horizontal direction and increase its horizontal movement distance by 1 for subsequent cycles. For example, if the Minnow had been moving S/E/S/E, it will now move S/W/W/S/W/W. If it hits a second piece of food, it will move S/E/E/E/S/E/E/E, and a third, S/W/W/W/W/S/W/W/W/W, and so on.

The following is an example timeline of a particular Minnow object's movement. The timeline below is also drawn in the diagram at right. Underlined occurrences mark squares where the Minnow found food.     

S, E, S, E (hits food) S, W, W, S, W, W, S (hits food) S, E, E, E, S, E, E, E, S, E (hits food) S (hits food) S, E, E, E, E, E, S, E, E, E, E, E, ...

? ?? ?? ??? ??? ? ???? ???? ?? ? ??????

8 of 9


9. Classes and Objects Suppose that you are provided with a pre-written class Date as described at right. (The headings are shown, but not the method bodies, to save space.) Assume that the fields, constructor, and methods shown are already implemented. You may refer to them or use them in solving this problem if necessary. Write an instance method named bound that will be placed inside the Date class to become a part of each Date object's behavior. The bound method constrains a Date to within a given range of dates. It accepts two other Date objects d1 and d2 as parameters; d1's date is guaranteed to represent a date that comes no later in the year than d2's date.

// Each Date object stores a single // month/day such as September 19. // This class ignores leap years. public class Date { private int month; private int day; // Constructs a date with // the given month and day. public Date(int m, int d) // Returns the date's day. public int getDay()

The bound method makes sure that this Date object is between d1's and d2's dates, inclusive. If this Date object is not between those dates inclusive, it is adjusted to the nearest date in the acceptable range. The method returns a result of true if this Date was within the acceptable range, or false if it was shifted.

// Returns the date's month. public int getMonth() // Returns the number of days // in this date's month. public int daysInMonth()

For example, given the following Date objects: Date date1 = new Date(7, 12); Date date2 = new Date(10, 31); Date date3 = new Date(9, 19); Date bound1 = new Date(8, 4); Date bound2 = new Date(9, 26); Date bound3 = new Date(12, 25);

// Modifies this date's state // so that it has moved forward // in time by 1 day, wrapping // around into the next month // or year if necessary. // example: 9/19 -> 9/20 // example: 9/30 -> 10/1 // example: 12/31 -> 1/1

The following calls to your method should adjust the given Date objects to represent the following dates and should return the following results:

call date1.bound(bound1, bound2) date2.bound(bound1, bound2) date3.bound(bound1, bound3) date2.bound(bound3, bound3)

public void nextDay()

date becomes returns 8/4 9/26 9/19 12/25

false false true false

// your method would go here }

9 of 9


Sample Final Exam #6 Key 1. Array Mystery Call String[] a1 = {"a", "b", "c"}; arrayMystery(a1);

Final Contents of Array ["ac", "bb", "cac"]

String[] a2 = {"a", "bb", "c", "dd"}; arrayMystery(a2);

["add", "bbc", "cbbc", "ddadd"]

String[] a3 = {"z", "y", "142", "w", "xx"}; arrayMystery(a3);

["zxx", "yw", "142142", "wyw", "xxzxx"]

2. Reference Semantics Mystery Level 6, 5 hp Level 6, 10 hp Level 7, 12 hp Level 7, 16 hp

3. Inheritance Mystery cat 2 cat 2 cat

dog 1

cat 1 cat 2 cat lion 2 lion 2 lion

cat 2 cat 2

dog 1

4. File Processing public static double evaluate(Scanner input) { double result = input.nextDouble(); while (input.hasNext()) { String operator = input.next(); double num = input.nextDouble(); if (operator.equals("+")) { result += num; } else { // operator.equals("-") result -= num; } } return result; }

1 of 5


5. File Processing (three solutions shown)

public static int blackjack(Scanner input) { int total = 0; while (input.hasNext()) { if (input.hasNextInt()) { total += input.nextInt(); } else { String token = input.next().toLowerCase(); if (token.equals("j") || token.equals("q") || token.equals("k")) { total += 10; // jack/queen/king } else { total += 11; // ace } } input.next(); // suit } }

return total;

public static int blackjack(Scanner input) { int total = 0; while (input.hasNext()) { if (input.hasNextInt()) { total += input.nextInt(); } else { String token = input.next().toLowerCase(); if (token.equals("a")) { total += 11; } else if (token.equals("j") || token.equals("q") || token.equals("k")) { total += 10; // jack/queen/king } } } return total; } public static int blackjack(Scanner input) { int total = 0; while (input.hasNext()) { if (input.hasNextInt()) { total += input.nextInt(); } else { String token = input.next().toLowerCase(); if (token.equals("a")) { total += 11; } else { total += 10; // jack/queen/king } } input.next(); // suit } }

return total;

2 of 5


6. Array Programming (three solutions shown)

public static boolean allPlural(String[] a) { for (int i = 0; i < a.length; i++) { if (a[i].length() == 0) { return false; } char c = a[i].charAt(a[i].length() - 1); if (c != 's' && c != 'S') { return false; } } }

return true;

public static boolean allPlural(String[] a) { int count = 0; for (int i = 0; i < a.length; i++) { if (a[i].endsWith("s") || a[i].endsWith("S")) { count++; } }

}

if (count == a.length) { return true; } else { return false; }

public static boolean allPlural(String[] a) { for (int i = 0; i < a.length; i++) { if (!a[i].toLowerCase().endsWith("s")) { return false; } } return true; }

3 of 5


7. Array Programming (six solutions shown) public static void reverseChunks(int[] a, int size) { for (int i = 0; i + size - 1 < a.length; i += size) { int left = i; int right = i + size - 1; while (left < right) { int temp = a[left]; a[left] = a[right]; a[right] = temp; left++; right--; } } } public static void reverseChunks(int[] a, int size) { for (int i = 0; i < a.length; i++) { if (i % size == 0 && i <= a.length - size) { for (int j = 0; j < size / 2; j++) { int temp = a[i + j]; a[i + j] = a[i + size - j - 1]; a[i + size - j - 1] = temp; } } } } public static void reverseChunks(int[] a, int size) { if (size <= a.length) { for (int i = 0; i < a.length; i++) { int j = (i - i % size) + size - 1 - i % size; if (j > i && j < a.length) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } } } } public static void reverseChunks(int[] a, int s) { for (int i = 0; i < a.length / s; i++) { for (int j = 0; j < s / 2; j++) { int temp = a[i * s + j]; a[i * s + j] = a[(i + 1) * s - 1 - j]; a[(i + 1) * s - 1 - j] = temp; } } } public static void reverseChunks(int[] a, int s) { for (int i = 0; i < a.length / s; i++) { int[] b = new int[s]; for (int j = 0; j < s; j++) { b[s - 1 - j] = a[i * s + j]; }

}

}

for (int j = 0; j < s; j++) { a[i * s + j] = b[j]; }

public static void reverseChunks(int[] a, int size) { for (int i = 0; i <= a.length - size; i += size) { for (int j = 0; j < size / 2; j++) { int temp = a[i + j]; a[i + j] = a[i + size - j - 1]; a[i + size - j - 1] = temp; } } }

4 of 5


8. Critters (two solutions shown)

public class Minnow extends Critter { private int cycleLength; private int cycleStep; public Minnow() { cycleLength = 1; cycleStep = 0; } public boolean eat() { cycleLength++; cycleStep = 0; return false; } public Direction getMove() { if (cycleStep == 0) { cycleStep++; return Direction.SOUTH; } else if (cycleStep < cycleLength) { cycleStep++; } else { cycleStep = 0; }

}

}

if (cycleLength % 2 == 1) { return Direction.EAST; } else { return Direction.WEST; }

public class Minnow extends Critter { private Direction currHoriz; private int cycleLength; private int cycleStep; public Minnow() { currHoriz = Direction.EAST; cycleLength = 1; cycleStep = 0; } public boolean eat() { cycleLength++; cycleStep = 0; if (currHoriz == Direction.EAST) { currHoriz = Direction.WEST; } else { currHoriz = Direction.EAST; } return false; } public Direction getMove() { if (cycleStep == 0) { cycleStep++;

}

}

return Direction.SOUTH; } else if (cycleStep < cycleLength) { cycleStep++; return currHoriz; } else { cycleStep = 0; return currHoriz; }

9. Classes and Objects

public boolean bound(Date d1, Date d2) { if (month < d1.month || (month == d1.month && day < d1.day)) { month = d1.month; day = d1.day; return false; } else if (month > d2.month || (month == d2.month && day > d2.day)) { month = d2.month; day = d2.day; return false; } else { return true; } }

5 of 5


Sample Final Exam #7 (Autumn 2008)

1. Array Mystery Consider the following method: public static void arrayMystery(int[] a) { for (int i = a.length - 2; i > 0; i--) { if (a[i - 1] < a[i + 1]) { a[i] += a[i - 1]; } else { a[i] += a[i + 1]; } } }

Indicate in the right-hand column what values would be stored in the array after the method arrayMystery executes if the integer array in the left-hand column is passed as a parameter to it.

Original Contents of Array

Final Contents of Array

int[] a1 = {1, 2, 3}; arrayMystery(a1);

_____________________________

int[] a2 = {8, 2, 3, 1, 6}; arrayMystery(a2);

_____________________________

int[] a3 = {1, 1, 1, 1, 1, 1}; arrayMystery(a3);

_____________________________

int[] a4 = {40, 10, 25, 5, 10, 30}; arrayMystery(a4);

_____________________________

int[] a5 = {15, 6, -1, 4, 8, -2, 7, 4}; arrayMystery(a5);

_____________________________

1 of 9


2. Reference Semantics Mystery The following program produces 4 lines of output. Write the output below, as it would appear on the console. public class ReferenceMystery { public static void main(String[] args) { int x = 1; int[] a = new int[4]; x++; a[x - 1] = 3; mystery(x, a); System.out.println(x + " " + Arrays.toString(a)); x++; a[x - 1] = 2; mystery(x, a); System.out.println(x + " " + Arrays.toString(a)); } public static void mystery(int x, int[] a) { a[x]++; x--; a[x - 1] = a[x + 1]; System.out.println(x + " " + Arrays.toString(a)); } }

2 of 9


3. Inheritance Mystery Assume that the following classes have been defined: public class McCain extends Biden { public void republican() { System.out.print("mccain-R } } public class Palin { public void republican() { System.out.print("palin-R } public void democrat() { republican(); System.out.print("palin-D } public String toString() { return "palin"; }

");

");

public class Obama extends Palin { public void republican() { super.republican(); System.out.print("obama-R } }

");

public class Biden extends Palin { public String toString() { return "biden"; } public void democrat() { System.out.print("biden-D super.democrat(); }

");

");

}

}

Given the classes above, what output is produced by the following code? Palin[] politicians = {new Biden(), new Palin(), new McCain(), new Obama()}; for (int i = 0; i < politicians.length; i++) { System.out.println(politicians[i]); politicians[i].republican(); System.out.println(); politicians[i].democrat(); System.out.println(); System.out.println(); }

3 of 9


4. File Processing Write a static method named reportBlankLines that accepts a Scanner containing an input file as a parameter and that outputs the line numbers of any blank lines and that reports the total number of blank lines in the file. For example, given the following input file: Remember that a file can have blank lines like the one below: A blank line: is read as a String of length 0 by Scanner

Your method should print the following output: line 4 is blank line 6 is blank line 9 is blank total blank lines = 3

Notice that each blank line produces a line of output and that there is a final line of output reporting the total number of blank lines. Also notice that lines are numbered starting with 1 (first line is line 1, second line is line 2, and so on).

4 of 9


5. File Processing Write a static method named printDuplicates that accepts as its parameter a Scanner for an input file containing a series of lines. Your method should examine each line looking for consecutive occurrences of the same token on the same line, and print each duplicated token along with how many times it appears consecutively. Non-repeated tokens are not printed. Repetition across multiple lines (such as if a line ends with a given token and the next line starts with the same token) is not considered in this problem. For example, if the input file contains the following text (sequences of duplicated tokens are underlined for emphasis): hello how how are you you you you I I I am Jack's Jack's smirking smirking smirking smirking smirking revenge bow wow wow yippee yippee yo yippee yippee yay yay yay one fish two fish red fish blue fish It's the Muppet Show, wakka wakka wakka

Your method would produce the following output for the preceding input file: how*2 you*4 I*3 Jack's*2 smirking*5 wow*2 yippee*2 yippee*2 yay*3 wakka*3

Your code prints only the repeated tokens; the ones that appear only once in a row are not shown. Your code should place a single space between each reported duplicate token and should respect the line breaks in the original file. This is why a blank line appears in the expected output, corresponding to the fourth line of the file that did not contain any consecutively duplicated tokens. You may assume that each line of the file contains at least 1 token of input.

5 of 9


6. Array Programming Write a static method named arraySum that accepts two arrays of real numbers a1 and a2 as parameters and returns a new array a3 such that each element of a3 at each index i is the sum of the elements at that same index i in a1 and a2. For example, if a1 stores {4.5, 5.0, 6.6} and a2 stores {1.1, 3.4, 0.5}, your method should return {5.6, 8.4, 7.1}, which is obtained by adding 4.5 + 1.1, 5.0 + 3.4, and 6.6 + 0.5. If the arrays a1 and a2 are not the same length, the result returned by your method should have as many elements as the larger of the two arrays. If a given index i is in bounds of a1 but not a2 (or vice versa), your result array's element at index i should be equal to the value of the element at index i in the longer of a1 or a2. For example, if a1 stores {1.8, 2.9, 9.4, 5.5} and a2 stores {2.4, 5.0}, your method should return {4.2, 7.9, 9.4, 5.5}. The table below shows some additional calls to your method and the expected values returned: Arrays

Call and Value Returned

double[] a1 = {4.5, 2.8, 3.4, 0.8}; double[] a2 = {1.4, 8.9, -1.0, 2.3}; double[] ax = {2.4, 3.8}; double[] ay = {0.2, 9.2, 4.3, 2.8, 1.4}; double[] aa = {1.0, 2.0, 3.0}; double[] ab = {4.0, 5.0}; double[] ai = {}; double[] aj = {42.0};

arraySum(a1, a2) returns {5.9, 11.7, 2.4, 3.1} arraySum(ax, ay) returns {2.6, 13.0, 4.3, 2.8, 1.4} arraySum(aa, ab) returns {5.0, 7.0, 3.0} arraySum(ai, aj) returns {42.0}

For full credit, you should not modify the elements of a1 or a2. You may not use a String to solve this problem.

6 of 9


7. Array Programming Write a static method named partition that accepts an array of integers a and an integer element value v as its parameters, and rearranges ("partitions") the array's elements so that all its elements of a that are less than v occur before all elements that are greater than v. The exact order of the elements is unimportant so long as all elements less than v appear before all elements greater than v. For example, if your method were passed the following array: int[] a = {15, 1, 6, 12, -3, 4, 8, -7, 21, 2, 30, -1, 9}; partition(a, 5);

One acceptable ordering of the elements after the call would be: (elements < 5 and > 5 are underlined for emphasis) {-1, 1, 2, -7, -3, 4, 8, 12, 21, 6, 30, 15, 9}

Hint: Your method will need to rearrange the elements of the array, which will involve swapping various elements from less desirable indexes to more desirable ones. You may assume that the array contains no duplicates and does not contain the element value v itself. You may not use Arrays.sort, Collections.sort, or any other pre-defined sorting algorithm from the Java Class Libraries or textbook to solve this problem. You also may not use a String to solve this problem.

7 of 9


8. Critters Write a class Hyena that extends the Critter class, along with its movement and eating behavior. All unspecified aspects of Hyena use the default behavior. Write the complete class with any fields, constructors, etc. necessary. Hyena objects move in a rectangular pattern looking for food, walking NORTH, then EAST, then SOUTH, then

WEST. Each time the Hyena walks an entire rectangle or eats food, it starts the rectangle pattern over again but with a rectangle 1 step wider than before. The general pattern is as follows, if the Hyena doesn't find any food:

N, E, S, W, N, E, E, S, W, W, N, E, E, E, S, W, W, W, N, E, E, E, E, S, W, W, W, W, ...

If the Hyena encounters food at any point during its movement pattern, it eats the food and starts the pattern over, lengthening the rectangular pattern by 1 in the process. For example:

N, E, S, W, N, E, E (eats food), N, E, E, E, S, W, W (eats food), N, E, E, E, E, S, W, W, W, W, N, E, E, E, E, E, S (eats food), N, E, E, E, E, E, E, S, W, W, ...

The following diagrams summarize this behavior, the left without food and the right when food is encountered:

8 of 9


9. Classes and Objects Suppose that you are provided with a pre-written class Date as described at right. (The headings are shown, but not the method bodies, to save space.) Assume that the fields, constructor, and methods shown are already implemented. You may refer to them or use them in solving this problem if necessary.

// Each Date object stores a single // month/day such as September 19. // This class ignores leap years. public class Date { private int month; private int day;

Write an instance method named absoluteDay that will be placed inside the Date class to become a part of each Date object's behavior. The absoluteDay method should return the "absolute day of the year" between 1 and 365 represented by the Date object. January 1 is absolute day #1, January 2 is day #2, ..., and December 31st is absolute day #365. For example, calling this method on a date representing February 13th should return 44, and calling it on a Date representing September 19th should return 262.

// Constructs a date with // the given month and day. public Date(int m, int d) // Returns the date's day. public int getDay() // Returns the date's month. public int getMonth() // Returns the number of days // in this date's month. public int daysInMonth()

Suppose the following dates have been declared: Date jan1 = new Date(1, 1); Date jan4 = new Date(1, 4); Date feb1 = new Date(2, 1); Date mar10 = new Date(3, 10); Date sep19 = new Date(9, 19); Date dec31 = new Date(12, 31);

// Modifies this date's state // so that it has moved forward // in time by 1 day, wrapping // around into the next month // or year if necessary. // example: 9/19 -> 9/20 // example: 9/30 -> 10/1 // example: 12/31 -> 1/1

The results of calling your method on the above objects are: Call jan1.absoluteDay() jan4.absoluteDay() feb1.absoluteDay() mar10.absoluteDay() sep19.absoluteDay() dec31.absoluteDay()

Returns 1 4 32 69 262 365

public void nextDay() // your method would go here }

You should not solve this problem by writing 12 if statements, one for each month; this is redundant and poor style. If you solve the problem that way, you will receive at most half credit. Also, your method should not have the side effect of modifying the Date object on which it was called. In other words, when your method is done executing, the values of the fields of the Date object on which it was called should be unchanged. A solution that does so will receive at most half credit. (It's okay for you to modify the object's state temporarily if it helps you solve this problem, but when your method is done executing, the state should be the same as when you started.) Recall that your method is allowed to call other methods on Date objects or construct other objects if you like.

9 of 9


Sample Final Exam #7 Key 1. Array Mystery Expression int[] a1 = {1, 2, 3}; arrayMystery(a1);

Final Contents of Array {1, 3, 3}

int[] a2 = {8, 2, 3, 1, 6}; arrayMystery(a2);

{8, 7, 5, 4, 6}

int[] a3 = {1, 1, 1, 1, 1, 1}; arrayMystery(a3);

{1, 2, 2, 2, 2, 1}

int[] a4 = {40, 10, 25, 5, 10, 30}; arrayMystery(a4);

{40, 45, 35, 20, 15, 30}

int[] a5 = {15, 6, -1, 4, 8, -2, 7, 4}; arrayMystery(a5);

{15, 8, 2, 3, 11, 3, 5, 4}

2. Reference Semantics Mystery 1 [1, 3, 1, 0] 2 [1, 3, 1, 0] 2 [1, 1, 2, 1] 3 [1, 1, 2, 1]

3. Inheritance Mystery biden palin-R biden-D

palin-R

palin palin-R palin-R

palin-D

biden mccain-R biden-D

mccain-R

palin-D

palin palin-R palin-R

obama-R obama-R

palin-D

palin-D

1 of 8


4. File Processing

public static void listBlankLines(Scanner input) { int line = 0; int count = 0; while (input.hasNextLine()) { String text = input.nextLine(); line++; if (text.length() == 0) { System.out.println("line " + line + " is blank"); count++; } } System.out.println("total blank lines = " + count); }

5. File Processing (two solutions shown)

public static void printDuplicates(Scanner input) { while (input.hasNextLine()) { String line = input.nextLine(); Scanner lineScan = new Scanner(line); String token = lineScan.next(); int count = 1; while (lineScan.hasNext()) { String token2 = lineScan.next(); if (token2.equals(token)) { count++; } else { if (count > 1) { System.out.print(token + "*" + count + " "); } token = token2; count = 1; } }

}

}

if (count > 1) { System.out.print(token + "*" + count); } System.out.println();

public static void printDuplicates(Scanner input) { while (input.hasNextLine()) { String line = input.nextLine(); Scanner lineScan = new Scanner(line); String token = lineScan.next(); int count = 1; while (lineScan.hasNext()) { String token2 = lineScan.next(); if (token2.equals(token)) { count++; }

}

}

}

if (count > 1 && (!lineScan.hasNext() || !token2.equals(token))) { System.out.print(token + "*" + count + " "); count = 1; } token = token2;

System.out.println();

2 of 8


6. Array Programming (five solutions shown)

public static double[] arraySum(double[] a1, double[] a2) { double[] a3 = new double[Math.max(a1.length, a2.length)]; for (int i = 0; i < a3.length; i++) { if (i >= a1.length) { // done with a1; take from a2 a3[i] = a2[i]; } else if (i >= a2.length) { // done with a2; take from a1 a3[i] = a1[i]; } else { a3[i] = a1[i] + a2[i]; // take sum of a1 and a2 } } return a3; } public static double[] arraySum(double[] a1, double[] a2) { double[] a3 = new double[Math.max(a1.length, a2.length)]; for (int i = 0; i < a1.length; i++) { // add a1 into result a3[i] += a1[i]; } for (int i = 0; i < a2.length; i++) { // add a2 into result a3[i] += a2[i]; } return a3; } public static double[] arraySum(double[] a1, double[] a2) { double[] a3; // create result array if (a1.length > a2.length) { a3 = new double[a1.length]; } else { a3 = new double[a2.length]; } for (int i = 0; i < a1.length; i++) { // add a1 into result a3[i] += a1[i]; } for (int i = 0; i < a2.length; i++) { // add a2 into result a3[i] += a2[i]; } return a3; } public static double[] arraySum(double[] a1, double[] a2) { int minLength = Math.min(a1.length, a2.length); int maxLength = Math.max(a1.length, a2.length); double[] a3 = new double[maxLength]; // create result array

}

for (int i = 0; i < minLength; i++) { a3[i] = a1[i] + a2[i]; } for (int i = minLength; i < maxLength; i++) { if (a1.length > a2.length) { a3[i] = a1[i]; } else { a3[i] = a2[i]; } } return a3;

// add a1,a2 into result

public static double[] arraySum(double[] a1, double[] a2) { double[] shorter = a1; double[] longer = a2; if (a1.length > a2.length) { shorter = a2; longer = a1; } double[] a3 = new double[longer.length]; for (int i = 0; i < shorter.length; i++) { a3[i] = shorter[i] + longer[i]; } for (int i = shorter.length; i < longer.length; i++) { a3[i] += longer[i]; } }

return a3;

3 of 8


7. Array Programming (six solutions shown)

public static void partition(int[] a, int v) { int i2 = a.length - 1; for (int i1 = 0; i1 < i2; i1++) { while (i2 > i1 && a[i2] >= v) { i2--; } int temp = a[i1]; a[i1] = a[i2]; a[i2] = temp; } } public static void partition(int[] a, int v) { int i1 = 0; int i2 = a.length - 1; while (true) { while (i2 > i1 && a[i2] >= v) { i2--; } while (i2 > i1 && a[i1] <= v) { i1++; } if (i1 >= i2) { break; }

}

}

int temp = a[i1]; a[i1] = a[i2]; a[i2] = temp;

public static void partition(int[] a, int v) { int[] copy = new int[a.length]; int target = 0; for (int i = 0; i < a.length; i++) { if (a[i] < v) { copy[target] = a[i]; target++; } } for (int i = 0; i < a.length; i++) { if (a[i] > v) { copy[target] = a[i]; target++; } }

}

for (int i = 0; i < a.length; i++) { a[i] = copy[i]; }

public static void partition(int[] a, int v) { for (int i = 0; i < a.length; i++) { for (int j = 0; j < a.length - 1; j++) { if (a[j] > a[j + 1]) { int temp = a[j]; a[j + 1] = a[j]; a[j] = temp; } } } }

4 of 8


public static void partition(int[] a, int v) { for (int i = 0; i < a.length; i++) { int smallest = i; for (int j = i + 1; j < a.length; j++) { if (a[j] < a[smallest]) { smallest = j; } } int temp = a[i]; a[i] = a[smallest]; a[smallest] = temp; } } public static void partition(int[] a, int v) { for (int i = 0; i < a.length; i++) { if (a[i] > a[i + 1]) { int temp = a[i]; a[i + 1] = a[i]; a[i] = temp; partition(a, v); } } }

5 of 8


8. Critters (two solutions shown)

public class Hyena extends Critter { private int moves; private int width; public Hyena() { moves = 0; width = 1; } public boolean eat() { moves = 0; width++; return true; } public Direction getMove() { moves++; if (moves > 2 * width + 2) { moves = 1; width++; }

}

}

if (moves == 1) { return Direction.NORTH; } else if (moves <= width + 1) { return Direction.EAST; } else if (moves == width + 2) { return Direction.SOUTH; } else { return Direction.WEST; }

public class Hyena extends Critter { private int moves = 0; private int max = 1; private boolean ate = false; public boolean eat() { ate = true; return true; } public Direction getMove() { moves++; if (ate || moves == 2 * max + 3) { ate = false; moves = 1; max++; }

}

}

if (moves == 1) { return Direction.NORTH; } else if (moves <= max + 1) { return Direction.EAST; } else if (moves == max + 2) { return Direction.SOUTH; } else { return Direction.WEST; }

6 of 8


9. Classes and Objects (nine solutions shown)

public int absoluteDay() { int myMonth = month; int myDay = day; month = 1; day = 1; int count = 1; while (month != myMonth || day != myDay) { count++; nextDay(); } return count; } public int absoluteDay() { Date temp = new Date(1, 1); int count = 1; while (day != temp.day || month != temp.month) { count++; temp.nextDay(); } return count; } public int absoluteDay() { int count = day; Date temp = new Date(1, 1); for (int i = 1; i < month; i++) { count += temp.daysInMonth(); temp.month++; } return count; } public int absoluteDay() { int count = 0; for (int i = 1; i <= month - 1; i++) { if (i == 4 || i == 6 || i == 9 || i == 11) { count += 30; } else if (i == 2) { count += 28; } else { count += 31; } } count += day; return count; } public int absoluteDay() { int[] dayCount = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int count = 0; for (int i = 1; i <= month - 1; i++) { count += dayCount[i - 1]; } return count + day; } public int absoluteDay() { Date copy = new Date(month, day); int count = 365; while (copy.getMonth() != 12 || copy.getDay() != 31) { copy.nextDay(); count--; } return count; }

7 of 8


public int absoluteDay() { int oldMonth = month; int oldDay = day; int count = 0; while (month != 12 || day != 31) { nextDay(); count++; } month = oldMonth; day = oldDay; return 365 - count; } public int absoluteDay() { int oldMonth = month; month = 0; int count = 0; for (int i = 1; i < oldMonth; i++) { month = i; count += daysInMonth(); } count += day; return count; } public int absoluteDay() { int oldMonth = month; int count = 0; for (int i = month; i > 1; i--) { month--; count += daysInMonth(); } count += day; month = oldMonth; return count; }

8 of 8


Sample Final Exam #8 (Summer 2009; thanks to Victoria Kirst)

1. Array Mystery Consider the following method: public static void arrayMystery(int[] a) { for (int i = 1; i < a.length - 1; i++) { a[i] = a[i + 1] + a[i - 1]; } }

Indicate in the right-hand column what values would be stored in the array after the method arrayMystery executes if the integer array in the left-hand column is passed as a parameter to it.

Original Contents of Array

Final Contents of Array

int[] a1 = {3, 7}; arrayMystery(a1);

_____________________________

int[] a2 = {4, 7, 4, 2, 10, 9}; arrayMystery(a2);

_____________________________

int[] a3 = {1, 5, 0, 0, 5, 0}; arrayMystery(a3);

_____________________________

int[] a4 = {13, 0, -4, -2, 0, -1}; arrayMystery(a4);

_____________________________

int[] a5 = {2, 4, 6, 8, 16}; arrayMystery(a5);

_____________________________

1 of 8


2. Reference Semantics Mystery (Missing; we didn't give this type of question that quarter.)

3. Inheritance Mystery Assume that the following classes have been defined: public class Denny extends John { public void method1() { System.out.print("denny 1 }

");

public String toString() { return "denny " + super.toString(); } } public class Cass { public void method1() { System.out.print("cass 1 } public void method2() { System.out.print("cass 2 }

public class Michelle extends John { public void method1() { System.out.print("michelle 1 "); } } public class John extends Cass { public void method2() { method1(); System.out.print("john 2 }

");

");

public String toString() { return "john"; } }

");

public String toString() { return "cass"; } }

Given the classes above, what output is produced by the following code? Cass[] elements = {new Cass(), new Denny(), new John(), new Michelle()}; for (int i = 0; i < elements.length; i++) { elements[i].method1(); System.out.println(); elements[i].method2(); System.out.println(); System.out.println(elements[i]); System.out.println(); }

2 of 8


4. File Processing Write a static method called runningSum that accepts as a parameter a Scanner holding a sequence of real numbers and that outputs the running sum of the numbers followed by the maximum running sum. In other words, the nth number that you report should be the sum of the first n numbers in the Scanner and the maximum that you report should be the largest such value that you report. For example if the Scanner contains the following data: 3.25 4.5 -8.25 7.25 3.5 4.25 -6.5 5.25

your method should produce the following output: running sum = 3.25 7.75 -0.5 6.75 10.25 14.5 8.0 13.25 max sum = 14.5

The first number reported is the same as the first number in the Scanner (3.25). The second number reported is the sum of the first two numbers in the Scanner (3.25 + 4.5). The third number reported is the sum of the first three numbers in the Scanner (3.25 + 4.5 + -8.25). And so on. The maximum of these values is 14.5, which is reported on the second line of output. You may assume that there is at least one number to read.

3 of 8


5. File Processing Write a static method named plusScores that accepts as a parameter a Scanner containing a series of lines that represent student records. Each student record takes up two lines of input. The first line has the student's name and the second line has a series of plus and minus characters. Below is a sample input: Kane, Erica --+-+ Chandler, Adam ++-+ Martin, Jake +++++++ Dillon, Amanda ++-++-+-

The number of plus/minus characters will vary, but you may assume that at least one such character appears and that no other characters appear on the second line of each pair. For each student you should produce a line of output with the student's name followed by a colon followed by the percent of plus characters. For example, if the input above is stored in a Scanner called input, the call of plusScores(input); should produce the following output: Kane, Erica: 40.0% plus Chandler, Adam: 75.0% plus Martin, Jake: 100.0% plus Dillon, Amanda: 62.5% plus

4 of 8


6. Array Programming Write a method priceIsRight that accepts an array of integers bids and an integer price as parameters. The method returns the element in the bids array that is closest in value to price without being larger than price. For example, if bids stores the elements {200, 300, 250, 999, 40}, then priceIsRight(bids, 280) should return 250, since 250 is the bid closest to 280 without going over 280. If all bids are larger than price, then your method should return -1. The following table shows some calls to your method and their expected results:

Arrays int[] a1 = {900, 885, 989, 1}; int[] a2 = {200}; int[] a3 = {500, 300, 241, 99, 501}; int[] a2 = {200};

Returned Value priceIsRight(a1, 880) returns 1 priceIsRight(a2, 320) returns 200 priceIsRight(a3, 50) returns -1 priceIsRight(a2, 120) returns -1

You may assume there is at least 1 element in the array, and you may assume that the price and the values in bids will all be greater than or equal to 1. Do not modify the contents of the array passed to your method as a parameter.

5 of 8


7. Array Programming Write a static method named compress that accepts an array of integers a1 as a parameter and returns a new array that contains only the unique values of a1. The values in the new array should be ordered in the same order they originally appeared in. For example, if a1 stores the elements {10, 10, 9, 4, 10, 4, 9, 17}, then compress(a1) should return a new array with elements {10, 9, 4, 17}. The following table shows some calls to your method and their expected results:

Array int[] a1 = {5, 2, 5, 3, 2, 5}; int[] a2 = {-2, -12, 8, 8, 2, 12}; int[] a3 = {4, 17, 0, 32, -3, 0, 0}; int[] a4 = {-2, -5, 0, 5, -92, -2, 0, 43}; int[] a5 = {1, 2, 3, 4, 5}; int[] a6 = {5, 5, 5, 5, 5, 5}; int[] a7 = {};

Returned Value compress(a1) returns {5, 2, 3} compress(a2) returns {-2, -12, 8, 2, 12} compress(a3) returns {4, 17, 0, 32, -3} compress(a4) returns {-2, -5, 0, 5, -92, 43} compress(a5) returns {1, 2, 3, 4, 5} compress(a6) returns {5} compress(a7) returns {}

Do not modify the contents of the array passed to your method as a parameter.

6 of 8


8. Critters Write a class Caterpillar that extends the Critter class from our assignment, along with its movement behavior. Caterpillars move in an increasing NESW square pattern: 1 move north, 1 move east, 1 move west, 1 move south, then 2 moves north, 2 moves east, etc., the square pattern growing larger and larger indefinitely. If a Caterpillar runs into a piece of food, the Caterpillar eats the food and immediately restarts the NESW pattern. The size of the Caterpillar’s movement is also reset back to 1 move in each direction again, and the increasing square pattern

continues as before until another piece of food is encountered. Here is a sample movement pattern of a Caterpillar:

           

north 1 time, east 1 time, south 1 time, west 1 time north 2 times, east 2 times, south 2 times, west 2 times north 3 times, east 3 times, south 3 times, west 3 times (runs into food) north 1 time, east 1 time, south 1 time, west 1 time north 2 times, east 1 time (runs into food) north 1 time (runs into food) north 1 time, east 1 time, south 1 time, west 1 time north 2 times, east 2 times, south 2 times, west 2 times (etc.)

Write your complete Caterpillar class below. All other aspects of Caterpillar besides eating and movement behavior use the default critter behavior. You may add anything needed to your class (fields, constructors, etc.) to implement this behavior appropriately.

7 of 8


9. Classes and Objects Suppose that you are provided with a pre-written class Date as described at right. (The headings are shown, but not the method bodies, to save space.) Assume that the fields, constructor, and methods shown are already implemented. You may refer to them or use them in solving this problem if necessary. Write an instance method named subtractWeeks that will be placed inside the Date class to become a part of each Date object's behavior. The subtractWeeks method accepts an integer as a parameter and shifts the date represented by the Date object backward by that many weeks. A week is considered to be exactly 7 days. You may assume the value passed is nonnegative. Note that subtracting weeks might cause the date to wrap into previous months or years.

// Each Date object stores a single // month/day such as September 19. // This class ignores leap years. public class Date { private int month; private int day; // Constructs a date with // the given month and day. public Date(int m, int d) // Returns the date's day. public int getDay() // Returns the date's month. public int getMonth()

For example, if the following Date is declared in client code: Date d = new Date(9, 19);

// Returns the number of days // in this date's month. public int daysInMonth()

The following calls to the subtractWeeks method would modify the Date object's state as indicated in the comments. Remember that Date objects do not store the year. The date before January 1st is December 31st. Date objects also ignore leap years.

// Modifies this date's state // so that it has moved forward // in time by 1 day, wrapping // around into the next month // or year if necessary. // example: 9/19 -> 9/20 // example: 9/30 -> 10/1 // example: 12/31 -> 1/1

Date d = new Date(9, 19); d.subtractWeeks(1); // d is now 9/12 d.subtractWeeks(2); // d is now 8/29 d.subtractWeeks(5); // d is now 7/25 d.subtractWeeks(20); // d is now 3/7 d.subtractWeeks(110); // d is now 1/26 // (2 years prior)

public void nextDay() // your method would go here }

8 of 8


CSE 142 Sample Final Exam #8 (based on Summer 2009's final; thanks to Victoria Kirst)

1. Array Mystery Consider the following method: public static void arrayMystery(int[] a) { for (int i = 1; i < a.length - 1; i++) { a[i] = a[i + 1] + a[i - 1]; } }

Indicate in the right-hand column what values would be stored in the array after the method arrayMystery executes if the integer array in the left-hand column is passed as a parameter to it.

Original Contents of Array

Final Contents of Array

int[] a1 = {3, 7}; arrayMystery(a1);

_____________________________

int[] a2 = {4, 7, 4, 2, 10, 9}; arrayMystery(a2);

_____________________________

int[] a3 = {1, 5, 0, 0, 5, 0}; arrayMystery(a3);

_____________________________

int[] a4 = {13, 0, -4, -2, 0, -1}; arrayMystery(a4);

_____________________________

int[] a5 = {2, 4, 6, 8, 16}; arrayMystery(a5);

_____________________________

1 of 12


2. Reference Semantics Mystery (Missing; we didn't give this type of question that quarter.)

3. Inheritance Mystery Assume that the following classes have been defined: public class Denny extends John { public void method1() { System.out.print("denny 1 }

");

public String toString() { return "denny " + super.toString(); } } public class Cass { public void method1() { System.out.print("cass 1 } public void method2() { System.out.print("cass 2 }

public class Michelle extends John { public void method1() { System.out.print("michelle 1 "); } } public class John extends Cass { public void method2() { method1(); System.out.print("john 2 }

");

");

public String toString() { return "john"; } }

");

public String toString() { return "cass"; } }

Given the classes above, what output is produced by the following code? Cass[] elements = {new Cass(), new Denny(), new John(), new Michelle()}; for (int i = 0; i < elements.length; i++) { elements[i].method1(); System.out.println(); elements[i].method2(); System.out.println(); System.out.println(elements[i]); System.out.println(); }

2 of 12


4. File Processing Write a static method called runningSum that accepts as a parameter a Scanner holding a sequence of real numbers and that outputs the running sum of the numbers followed by the maximum running sum. In other words, the nth number that you report should be the sum of the first n numbers in the Scanner and the maximum that you report should be the largest such value that you report. For example if the Scanner contains the following data: 3.25 4.5 -8.25 7.25 3.5 4.25 -6.5 5.25

your method should produce the following output: running sum = 3.25 7.75 -0.5 6.75 10.25 14.5 8.0 13.25 max sum = 14.5

The first number reported is the same as the first number in the Scanner (3.25). The second number reported is the sum of the first two numbers in the Scanner (3.25 + 4.5). The third number reported is the sum of the first three numbers in the Scanner (3.25 + 4.5 + -8.25). And so on. The maximum of these values is 14.5, which is reported on the second line of output. You may assume that there is at least one number to read.

3 of 12


5. File Processing Write a static method named plusScores that accepts as a parameter a Scanner containing a series of lines that represent student records. Each student record takes up two lines of input. The first line has the student's name and the second line has a series of plus and minus characters. Below is a sample input: Kane, Erica --+-+ Chandler, Adam ++-+ Martin, Jake +++++++ Dillon, Amanda ++-++-+-

The number of plus/minus characters will vary, but you may assume that at least one such character appears and that no other characters appear on the second line of each pair. For each student you should produce a line of output with the student's name followed by a colon followed by the percent of plus characters. For example, if the input above is stored in a Scanner called input, the call of plusScores(input); should produce the following output: Kane, Erica: 40.0% plus Chandler, Adam: 75.0% plus Martin, Jake: 100.0% plus Dillon, Amanda: 62.5% plus

4 of 12


6. Array Programming Write a method priceIsRight that accepts an array of integers bids and an integer price as parameters. The method returns the element in the bids array that is closest in value to price without being larger than price. For example, if bids stores the elements {200, 300, 250, 999, 40}, then priceIsRight(bids, 280) should return 250, since 250 is the bid closest to 280 without going over 280. If all bids are larger than price, then your method should return -1. The following table shows some calls to your method and their expected results:

Arrays int[] a1 = {900, 885, 989, 1}; int[] a2 = {200}; int[] a3 = {500, 300, 241, 99, 501}; int[] a2 = {200};

Returned Value priceIsRight(a1, 880) returns 1 priceIsRight(a2, 320) returns 200 priceIsRight(a3, 50) returns -1 priceIsRight(a2, 120) returns -1

You may assume there is at least 1 element in the array, and you may assume that the price and the values in bids will all be greater than or equal to 1. Do not modify the contents of the array passed to your method as a parameter.

5 of 12


7. Array Programming Write a static method named compress that accepts an array of integers a1 as a parameter and returns a new array that contains only the unique values of a1. The values in the new array should be ordered in the same order they originally appeared in. For example, if a1 stores the elements {10, 10, 9, 4, 10, 4, 9, 17}, then compress(a1) should return a new array with elements {10, 9, 4, 17}. The following table shows some calls to your method and their expected results:

Array int[] a1 = {5, 2, 5, 3, 2, 5}; int[] a2 = {-2, -12, 8, 8, 2, 12}; int[] a3 = {4, 17, 0, 32, -3, 0, 0}; int[] a4 = {-2, -5, 0, 5, -92, -2, 0, 43}; int[] a5 = {1, 2, 3, 4, 5}; int[] a6 = {5, 5, 5, 5, 5, 5}; int[] a7 = {};

Returned Value compress(a1) returns {5, 2, 3} compress(a2) returns {-2, -12, 8, 2, 12} compress(a3) returns {4, 17, 0, 32, -3} compress(a4) returns {-2, -5, 0, 5, -92, 43} compress(a5) returns {1, 2, 3, 4, 5} compress(a6) returns {5} compress(a7) returns {}

Do not modify the contents of the array passed to your method as a parameter.

6 of 12


8. Critters Write a class Caterpillar that extends the Critter class from our assignment, along with its movement behavior. Caterpillars move in an increasing NESW square pattern: 1 move north, 1 move east, 1 move west, 1 move south, then 2 moves north, 2 moves east, etc., the square pattern growing larger and larger indefinitely. If a Caterpillar runs into a piece of food, the Caterpillar eats the food and immediately restarts the NESW pattern. The size of the Caterpillar’s movement is also reset back to 1 move in each direction again, and the increasing square pattern

continues as before until another piece of food is encountered. Here is a sample movement pattern of a Caterpillar:

           

north 1 time, east 1 time, south 1 time, west 1 time north 2 times, east 2 times, south 2 times, west 2 times north 3 times, east 3 times, south 3 times, west 3 times (runs into food) north 1 time, east 1 time, south 1 time, west 1 time north 2 times, east 1 time (runs into food) north 1 time (runs into food) north 1 time, east 1 time, south 1 time, west 1 time north 2 times, east 2 times, south 2 times, west 2 times (etc.)

Write your complete Caterpillar class below. All other aspects of Caterpillar besides eating and movement behavior use the default critter behavior. You may add anything needed to your class (fields, constructors, etc.) to implement this behavior appropriately.

7 of 12


9. Classes and Objects Suppose that you are provided with a pre-written class Date as described at right. (The headings are shown, but not the method bodies, to save space.) Assume that the fields, constructor, and methods shown are already implemented. You may refer to them or use them in solving this problem if necessary. Write an instance method named subtractWeeks that will be placed inside the Date class to become a part of each Date object's behavior. The subtractWeeks method accepts an integer as a parameter and shifts the date represented by the Date object backward by that many weeks. A week is considered to be exactly 7 days. You may assume the value passed is nonnegative. Note that subtracting weeks might cause the date to wrap into previous months or years.

// Each Date object stores a single // month/day such as September 19. // This class ignores leap years. public class Date { private int month; private int day; // Constructs a date with // the given month and day. public Date(int m, int d) // Returns the date's day. public int getDay() // Returns the date's month. public int getMonth()

For example, if the following Date is declared in client code: Date d = new Date(9, 19);

// Returns the number of days // in this date's month. public int daysInMonth()

The following calls to the subtractWeeks method would modify the Date object's state as indicated in the comments. Remember that Date objects do not store the year. The date before January 1st is December 31st. Date objects also ignore leap years.

// Modifies this date's state // so that it has moved forward // in time by 1 day, wrapping // around into the next month // or year if necessary. // example: 9/19 -> 9/20 // example: 9/30 -> 10/1 // example: 12/31 -> 1/1

Date d = new Date(9, 19); d.subtractWeeks(1); // d is now 9/12 d.subtractWeeks(2); // d is now 8/29 d.subtractWeeks(5); // d is now 7/25 d.subtractWeeks(20); // d is now 3/7 d.subtractWeeks(110); // d is now 1/26 // (2 years prior)

public void nextDay() // your method would go here }

8 of 12


Solutions 1. Array Mystery Expression int[] a1 = {3, 7}; arrayMystery(a1);

Final Contents of Array [3, 7]

int[] a2 = {4, 7, 4, 2, 10, 9}; arrayMystery(a2);

[4, 8, 10, 20, 29, 9]

int[] a3 = {1, 5, 0, 0, 5, 0}; arrayMystery(a3);

[1, 1, 1, 6, 6, 0]

int[] a4 = {13, 0, -4, -2, 0, -1}; arrayMystery(a4);

[13, 9, 7, 7, 6, -1]

int[] a5 = {2, 4, 6, 8, 16}; arrayMystery(a5);

[2, 8, 16, 32, 16]

2. Reference Semantics Mystery (missing)

3. Inheritance Mystery cass 1 cass 2 cass

denny 1 denny 1 john 2 denny john cass 1 cass 1 john

john 2

michelle 1 michelle 1 john 2 john

9 of 12


4. File Processing (two solutions shown) public static void runningSum(Scanner input) { double sum = input.nextDouble(); double max = sum; System.out.print("running sum = " + sum); while (input.hasNextDouble()) { sum += input.nextDouble(); System.out.print(" " + sum); if (sum > max) { max = sum; } } System.out.println(); System.out.println("max sum = " + max); } public static void runningSum(Scanner input) { double sum = 0; double max = 0; System.out.print("running sum ="); while (input.hasNext()) { sum += input.nextDouble(); System.out.print(" " + sum); max = Math.max(max, sum); } System.out.println("\nmax sum = " + max); }

5. File Processing (two solutions shown) public static void plusScores(Scanner input) { while (input.hasNextLine()) { String name = input.nextLine(); String data = input.nextLine(); int plus = 0; int count = 0; for (int i = 0; i < data.length(); i++) { count++; if (data.charAt(i) == '+') { plus++; } }

}

}

double percent = 100.0 * plus / count; System.out.println(name + ": " + percent + "% plus");

public static void plusScores(Scanner s) { while (s.hasNextLine()) { System.out.print(s.nextLine() + ": "); String p = s.nextLine(); System.out.print(100.0 * p.replace("-", "").length() / p.length() + "% plus"); } }

10 of 12


6. Array Programming (three solutions shown) public static int priceIsRight(int[] bids, int price) { int bestPrice = -1; for (int i = 0; i < bids.length; i++) { if (bids[i] <= price && bids[i] > bestPrice) { bestPrice = bids[i]; } } return bestPrice; } public static int priceIsRight(int[] bids, int price) { int[] difference = new int[bids.length]; int bestAnswer = Integer.MIN_VALUE; for (int i = 0; i < difference.length; i++) { difference[i] = bids[i] - price; } for (int i = 0; i < difference.length; i++) { if (difference[i] <= 0) { bestAnswer = (int) Math.max(difference[i], bestAnswer); } } if (bestAnswer == Integer.MIN_VALUE) { return -1; } else { return bestAnswer + price; } } public static int priceIsRight(int[] prices, int price) { int bestPrice = prices[0]; for (int i = 1; i < prices.length; i++) { if (prices[i] <= price && prices[i] > bestPrice) { bestPrice = prices[i]; } }

}

if (bestPrice <= price) { return bestPrice; } else { return -1; }

7. Array Programming public static int[] compress(int[] a1) { int[] unique = new int[a1.length]; int numUnique = 0; for (int i = 0; i < a1.length; i++) { int count = 0; for (int j = 0; j < numUnique; j++) { if (a1[i] == unique[j]) { count++; } } if (count == 0) { unique[numUnique++] = a1[i]; } } return Arrays.copyOf(unique, numUnique); }

11 of 12


8. Critters

public class Caterpillar extends Critter { private int stepLength = 1; private int steps = 0; public boolean eat() { steps = 0; stepLength = 1; return true; } public Direction getMove() { steps++; if (steps > 4 * stepLength) { stepLength++; steps = 1; }

}

}

if (steps <= stepLength) { return Direction.NORTH; } else if (steps <= 2 * stepLength) { return Direction.EAST; } else if (steps <= 3 * stepLength) { return Direction.SOUTH; } else { return Direction.WEST; }

9. Objects

public void subtractWeeks(int weeks) { for (int i = 1; i <= weeks; i++) { day -= 7; if (day <= 0) { month--; if (month == 0) { month = 12; } day += daysInMonth(); } } } public void subtractWeeks(int weeks) { int days = 7 * weeks; for (int i = 1; i <= days; i++) { day--; if (day == 0) { month--; if (month == 0) { month = 12; } day = daysInMonth(); } } } public void subtractWeeks(int weeks) { day -= 7 * weeks; while (day <= 0) { month--; if (month == 0) { month = 12; } day += daysInMonth(); } } public void subtractWeeks(int weeks) { int days = weeks * 7 % 365; for (int i = 1; i <= 365 - days; i++) { nextDay(); } }

12 of 12


Sample Final Exam #9 (Autumn 2009)

1. Array Mystery Consider the following method: public static void arrayMystery(int[] a) { for (int i = 1; i < a.length - 1; i++) { a[i] = a[i - 1] - a[i] + a[i + 1]; } }

Indicate in the right-hand column what values would be stored in the array after the method arrayMystery executes if the array in the left-hand column is passed as its parameter.

Original Contents of Array

Final Contents of Array

int[] a1 = {42, 42}; arrayMystery(a1);

_____________________________________

int[] a2 = {6, 2, 4}; arrayMystery(a2);

_____________________________________

int[] a3 = {7, 7, 3, 8, 2}; arrayMystery(a3);

_____________________________________

int[] a4 = {4, 2, 3, 1, 2, 5}; arrayMystery(a4);

_____________________________________

int[] a5 = {6, 0, -1, 3, 5, 0, -3}; arrayMystery(a5);

_____________________________________

1 of 9


2. Reference Semantics Mystery The following program produces 4 lines of output. Write the output below, as it would appear on the console. import java.util.*;

// for Arrays class

public class BasicPoint { int x; int y; public BasicPoint(int x, int y) { this.x = x; this.y = y; } } public class ReferenceMystery { public static void main(String[] args) { int n = 10; int[] a = {20}; // an array with just one element BasicPoint p = new BasicPoint(30, 40); mystery(n, a, p); System.out.println(n + " " + Arrays.toString(a) + " " + p.x + "," + p.y); a[0]++; p.x++; mystery(n, a, p); System.out.println(n + " " + Arrays.toString(a) + " " + p.x + "," + p.y); } public static int mystery(int n, int[] a, BasicPoint p) { n++; a[0]++; p.y++; System.out.println(n + " " + Arrays.toString(a) + " " + p.x + "," + p.y); return n; } }

2 of 9


3. Inheritance Mystery Assume that the following four classes have been defined: public class Biggie extends JayZ { public void a() { System.out.print("Biggie a super.a(); }

");

public String toString() { return "Biggie"; }

public class FiftyCent extends Biggie { public void b() { System.out.print("FiftyCent b "); } } public class Tupac { public void a() { System.out.print("Tupac a "); }

} public class JayZ extends Tupac { public void a() { System.out.print("JayZ a b(); } }

public void b() { System.out.print("Tupac b }

");

"); public String toString() { return "Tupac"; } }

Given the classes above, what output is produced by the following code? Tupac[] elements = {new Biggie(), new Tupac(), new JayZ(), new FiftyCent()}; for (int i = 0; i < elements.length; i++) { elements[i].a(); System.out.println(); elements[i].b(); System.out.println(); System.out.println(elements[i]); System.out.println(); }

3 of 9


4. File Processing Write a static method named countCoins that accepts as its parameter a Scanner for an input file whose data represents a person's money grouped into stacks of coins. Your method should add up the cash values of all the coins and print the total money at the end. The input consists of a series of pairs of tokens, where each pair begins with an integer and is followed by the type of coin, which will be either "pennies" (1 cent each), "nickels" (5 cents each), "dimes" (10 cents each), or "quarters" (25 cents each), case-insensitively. A given coin might appear more than once on the same line. For example, if the input file contains the following text: 3 pennies 2 quarters 1 pennies 3 nickels 4 dimes

3 pennies are worth 3 cents, and 2 quarters are worth 50 cents, and 1 penny is worth 1 cent, and 3 nickels are worth 15 cents, and 4 dimes are worth 40 cents. The total of these is 1 dollar and 9 cents, therefore your method would produce the following output if passed this input data. Notice that it says 09 for 9 cents. Total money: $1.09

Here is a second example. Suppose the input file contains the following text. Notice the capitalization and spacing: 12 QUARTERS PeNnIeS 10

1

Pennies

33

niCKELs

Then your method would produce the following output: Total money: $3.84

You may assume that the file contains at least 1 pair of tokens. You may also assume that the input is valid; that the input has an even number of tokens, that every other token is an integer, and that the others are valid coin types.

4 of 9


5. File Processing Write a static method named matchIndex that accepts as its parameter a Scanner for an input file. Your method should compare each neighboring pair of lines (the first and second lines, then the third and fourth lines, and so on) looking for places where the character at a given 0-based index from the two lines is the same. For example, in the strings "hello" and "belt", the characters at indexes 1 ('e') and 2 ('l') match. Your code should be case-sensitive; for example, "J" does not match "j". For each pair of lines, your method should print output showing the character indexes that match, separated by spaces in the format shown below. If no characters match, print "none" instead as shown below. For example, suppose the input file contains the following text. (Line numbers and character indexes are shown around the input and matching characters are shown in bold, but these markings do not appear in the actual file.) 1 2 3 4 5 6 7 8 9 10

0123456789012345678901234567890123456789 The quick brown fox Those achy down socks Wheels on the school bus go round The wipers go swish swish swish His name is Robert Paulson So long 'n thanks for all the fish Humpty Dumpty sat on a wall And then he also had a great fall booyakasha Bruno Ali G Borat

When passed the above file, your method would produce the following output: lines 1 and 2: 0 1 7 12 13 14 15 17 lines 3 and 4: 1 2 13 14 23 lines 5 and 6: none lines 7 and 8: 4 14 20 21 22 lines 9 and 10: none

Notice that lines are not generally the same length. You may assume that the file contains an even number of lines.

5 of 9


6. Array Programming Write a static method named longer that accepts two arrays of strings a1 and a2 as parameters and returns a new array a3 such that each element of a3 at each index i stores whichever string has greater length (more characters) between the elements at that same index i in arrays a1 and a2. If there is a tie, take the element from a1. For example, if a1 and a2 store the following elements: String[] a1 = {"star", "pie", "jelly bean", "car"}; String[] a2 = {"cookie", "fig", "banana", "soda"};

Then your method should return the new array {"cookie", "pie", "jelly bean", "soda"}. If the arrays a1 and a2 are not the same length, the result returned by your method should have as many elements as the larger of the two arrays. If a given index i is in bounds of a1 but not a2 (or vice versa), there are not two elements to compare, so your result array's element at index i should store the value "oops". For example, if a1 and a2 store the following elements: String[] a1 = {"Splinter", "Leo", "April", "Don", "Raph"}; String[] a2 = {"Krang", "Shredder", "Bebop"};

Then your method should return the new array {"Splinter", "Shredder", "April", "oops", "oops"}. For full credit, do not modify the elements of a1 or a2. Do not make any assumptions about the length of a1 or a2 or the length of the strings. You may assume that neither array is null and no element of either array is null.

6 of 9


7. Array Programming Write a static method named evenBeforeOdd that accepts an array of integers as a parameter and rearranges its elements so that all even values appear before all odds. For example, if the following array is passed to your method: int[] numbers = {5, 2, 4, 9, 3, 6, 2, 1, 11, 1, 10, 4, 7, 3};

Then after the method has been called, one acceptable ordering of the elements would be: {4, 2, 4, 10, 2, 6, 3, 1, 11, 1, 9, 5, 7, 3}

The exact order of the elements does not matter, so long as all even values appear before all odd values. For example, the following would also be an acceptable ordering: {2, 2, 4, 4, 6, 10, 1, 1, 3, 3, 5, 7, 9, 11}

Do not make any assumptions about the length of the array or the range of values it might contain. For example, the array might contain no even elements or no odd elements. You may assume that the array is not null. You may not use any temporary arrays to help you solve this problem. (But you may declare as many simple variables as you like, such as ints.) You also may not use any other data structures or complex types such as Strings, or other data structures that were not taught in CSE 142 such as the ArrayList class from Chapter 10. You will lose points if you use Arrays.sort in your solution. Hint: Look for elements that are at inappropriate places in the array and move them to better locations.

7 of 9


8. Critters Write a critter class Tigger along with its movement and eating behavior. All unspecified aspects of Tigger use the default behavior. Write the complete class with any fields, constructors, etc. necessary to implement the behavior. Bouncing is what Tiggers do best! The Tigger's movement is to bounce up and down to increasingly large heights. A Tigger object is passed an integer when it is constructed that represents his initial bounce height. (You may assume that the bounce height is at least 1.) Whatever bounce height is passed, he will move that many steps NORTH, then that many steps SOUTH, then repeat for a bounce height 1 larger. For example, a new Tigger(4) will move NORTH 4 times, then SOUTH 4 times, then NORTH 5 times, then SOUTH 5 times, then NORTH 6 times, then SOUTH 6 times, and so on. When a Tigger finds food, he eats it and completely starts over his bouncing behavior. That is, he starts over on a bounce whose height is equal to the initial bounce height with which the Tigger was constructed. For example, the following would be a sequence of moves for a new Tigger(2) . Notice how he starts over every time he eats:

N,N, S,S, N,N,N, S,S,S, N,N,N,N, S,S,S,S, N (eats food), N,N, S,S, N,N,N, S,S,S, N,N,N,N, ...

8 of 9


9. Classes and Objects Suppose that you are provided with a pre-written class ClockTime as described at right. (This was shown on one of our practice exams, except with the advance method from that exam added.) Assume that the fields, constructor, and methods shown are implemented. You may refer to them or use them in solving this problem. Write an instance method named isWorkTime that will be placed inside the ClockTime class to become a part of each ClockTime object's behavior. The isWorkTime method returns true if the ClockTime object represents a time during the normal "work day" from 9:00 AM to 5:00 PM, inclusive. Any times outside that range would cause the method to return a result of false.

// A ClockTime object represents // an hour:minute time during // the day or night, such as // 10:45 AM or 6:27 PM. public class ClockTime { private int hour; private int minute; private String amPm; // Constructs a new time for // the given hour/minute public ClockTime(int h, int m, String ap) // returns the field values public int getHour() public int getMinute() public String getAmPm()

For example, if the following object is declared in client code: ClockTime t1 = new ClockTime(3, 27, "PM");

// returns String for time; // example: "6:27 PM" public String toString()

The following call to your method would return true: if (t1.isWorkTime()) {

// true

// advances this ClockTime // by the given # of minutes public void advance(int m)

Here are some other objects. Their results when used with your method are shown at right in comments: ClockTime t2 = new ClockTime(12, 45, "AM"); //false ClockTime t3 = new ClockTime( 6, 02, "AM"); //false ClockTime t4 = new ClockTime( 8, 59, "AM"); //false ClockTime t5 = new ClockTime( 9, 00, "AM"); //true ClockTime t6 = new ClockTime(11, 38, "AM"); //true ClockTime t7 = new ClockTime(12, 53, "PM"); //true ClockTime t8 = new ClockTime( 3, 15, "PM"); //true ClockTime t9 = new ClockTime( 4, 59, "PM"); //true ClockTime ta = new ClockTime( 5, 00, "PM"); //true ClockTime tb = new ClockTime( 5, 01, "PM"); //false ClockTime tc = new ClockTime( 8, 30, "PM"); //false ClockTime td = new ClockTime(11, 59, "PM"); //false

// your method would go here }

Your method should not modify the state of the ClockTime object. Assume that the state of the ClockTime object is valid at the start of the call and that the amPm field stores either "AM" or "PM".

9 of 9


Sample Final Exam #9 Key 1. Array Mystery Expression int[] a1 = {42, 42}; arrayMystery(a1);

Final Contents of Array {42, 42}

int[] a2 = {6, 2, 4}; arrayMystery(a2);

{6, 8, 4}

int[] a3 = {7, 7, 3, 8, 2}; arrayMystery(a3);

{7, 3, 8, 2, 2}

int[] a4 = {4, 2, 3, 1, 2, 5}; arrayMystery(a4);

{4, 5, 3, 4, 7, 5}

int[] a5 = {6, 0, -1, 3, 5, 0, -3}; arrayMystery(a5);

{6, 5, 9, 11, 6, 3, -3}

3. Reference Semantics Mystery 11 [21] 30,41 10 [21] 30,41 11 [23] 31,42 10 [23] 31,42

3. Inheritance Mystery Biggie a Tupac b Biggie

JayZ a

Tupac b

Tupac a Tupac b Tupac JayZ a Tupac b Tupac

Tupac b

Biggie a JayZ a FiftyCent b Biggie

FiftyCent b

1 of 10


4. File Processing (3 solutions shown) // count up money as a double of dollars/cents; use printf at end public static void countCoins(Scanner input) { double total = 0.0; while (input.hasNext()) { int count = input.nextInt(); String coin = input.next().toLowerCase(); if (coin.equals("nickels")) { count = count * 5; } else if (coin.equals("dimes")) { count = count * 10; } else if (coin.equals("quarters")) { count = count * 25; } total = total + (double) count / 100; } System.out.printf("Total money: $%.2f\n", total); } // count up money as a total number of cents; use / and % at end public static void countCoins(Scanner input) { int totalCents = 0; while (input.hasNext()) { int count = input.nextInt(); String coin = input.next().toLowerCase(); if (coin.equals("nickels")) { totalCents += count * 5; } else if (coin.equals("dimes")) { totalCents += count * 10; } else if (coin.equals("quarters")) { totalCents += count * 25; } } int dollars = totalCents / 100; int cents = totalCents % 100;

}

System.out.print("Total money: $" + dollars + "."); if (cents < 10) { System.out.print("0"); } System.out.println(cents);

// implicit /100 in the multipliers public static void countCoins(Scanner input) { double total = 0.0; while (input.hasNext()) { double count = input.nextInt(); String coin = input.next().toLowerCase(); if (coin.equals("pennies")) { count *= 0.01; } else if (coin.equals("nickels")) { count *= 0.05; } else if (coin.equals("dimes")) { count *= 0.10; } else { count *= 0.25; } total += count;

}

} System.out.printf("Total money: $%.2f\n", total);

2 of 10


5. File Processing public static void matchIndex(Scanner input) { int lines = 0; while (input.hasNextLine()) { String line1 = input.nextLine(); String line2 = input.nextLine(); lines += 2; System.out.print("lines " + (lines - 1) + " and " + lines + ":"); // print any matches found boolean matchedAny = false; int length = Math.min(line1.length(), line2.length()); for (int i = 0; i < length; i++) { if (line1.charAt(i) == line2.charAt(i)) { matchedAny = true; System.out.print(" " + i); } }

}

}

if (!matchedAny) { System.out.print(" none"); } System.out.println();

3 of 10


6. Array Programming (3 solutions shown) // concise solution w/Math.max public static String[] longer(String[] a1, String[] a2) { String[] a3 = new String[Math.max(a1.length, a2.length)]; for (int i = 0; i < a3.length; i++) { if (i >= a1.length || i >= a2.length) { // out of bounds case; must check this before accessing a1[i] or a2[i] a3[i] = "oops"; } else if (a1[i].length() >= a2[i].length()) { a3[i] = a1[i]; } else { a3[i] = a2[i]; } } }

return a3;

// longer solution with if/else, altered test order public static String[] longer(String[] a1, String[] a2) { int len = 0; if (a1.length >= a2.length) { len = a1.length; } else { len = a2.length; } String[] a3 = new String[len]; for (int i = 0; i < len; i++) { if (i < a1.length && i < a2.length) { if (a1[i].length() >= a2[i].length()) { a3[i] = a1[i]; } else { a3[i] = a2[i]; } } else { a3[i] = "oops"; } } }

return a3;

// "fill with oops" solution public static String[] longer(String[] a1, String[] a2) { String[] a3 = new String[Math.max(a1.length, a2.length)]; Arrays.fill(a3, "oops"); for (int i = 0; i < Math.min(a1.length, a2.length); i++) { if (a1[i].length() >= a2[i].length()) { a3[i] = a1[i]; } else { a3[i] = a2[i]; } } return a3; }

4 of 10


7. Array Programming (9 solutions shown) // swap evens to beginning public static void evenBeforeOdd(int[] a) { int fixed = 0; for (int i = 0; i < a.length; i++) { if (a[i] % 2 == 0) { int temp = a[fixed]; // swap a[fixed] = a[i]; a[i] = temp; fixed++; } } } // walk j counter from back to i public static void evenBeforeOdd(int[] a) { int j = a.length - 1; for (int i = 0; i < j; i++) { while (i < j && a[j] % 2 != 0) { j--; }

}

}

int temp = a[j]; a[j] = a[i]; a[i] = temp;

// swap

// invent bubble sort public static void evenBeforeOdd(int[] a) { for (int i = 0; i < a.length; i++) { for (int j = 0; j < a.length - 1; j++) { if (a[j] % 2 != 0 && a[j + 1] % 2 == 0) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } } // modified selection sort public static void evenBeforeOdd(int[] a) { for (int i = 0; i < a.length; i++) { for (int j = i + 1; j < a.length; j++) { if (a[i] % 2 != 0 && a[j] % 2 == 0) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } } } } // selection sort #2 public static void evenBeforeOdd(int[] a) { for (int i = 0; i < a.length; i++) { if (a[i] % 2 != 0) { // then i is out of place; look for another index // k that represents the 2nd index to swap i with int k = -1; for (int j = i + 1; j < a.length; j++) { if (a[j] % 2 == 0) { k = j; } }

}

}

}

if (k >= 0) { int temp = a[i]; a[i] = a[k]; a[k] = temp; }

5 of 10


// partition (invent partial quicksort) public static void evenBeforeOdd(int[] a) { int even = 0; int odd = a.length - 1; while (even < odd) { while (even < a.length && a[even] % 2 == 0) { even++; } while (odd >= 0 && a[odd] % 2 != 0) { odd--; }

}

}

if (even < odd) { int temp = a[even]; a[even] = a[odd]; a[odd] = temp; }

// swap

// shift evens to front public static void evenBeforeOdd(int[] a) { for (int i = 0; i < a.length; i++) { if (a[i] % 2 == 0) { int even = a[i];

}

}

}

// found an even; shift others over and put at index 0 for (int j = i; j > 0; j--) { a[j] = a[j - 1]; } a[0] = even;

// walk from ends and swap public static void evenBeforeOdd(int[] a) { for (int i = a.length - 1; i >= 0; i--) { if (a[i] % 2 == 0) { // found an even; look for an odd and swap for (int j = 0; j < i; j++) { if (a[j] % 2 != 0) { int temp = a[i]; // swap a[i] = a[j]; a[j] = temp; } } } } } // evil scanner/string solution (should have been banned) public static void evenBeforeOdd(int[] a) { String evens = ""; String odds = ""; for (int i = a.length - 1; i >= 0; i--) { if (a[i] % 2 == 0) { evens += a[i] + " "; } else { odds += a[i] + " "; } }

}

int i = 0; Scanner evenScan = new Scanner(evens); while (evenScan.hasNextInt()) { a[i] = evenScan.nextInt(); i++; } Scanner oddScan = new Scanner(odds); while (oddScan.hasNextInt()) { a[i] = oddScan.nextInt(); i++; }

6 of 10


8. Critters (4 solutions shown) public class Tigger extends Critter { private int moves; private int max; private int initialMax;

// all-ints solution with one move counter

public Tigger(int initialMax) { this.initialMax = initialMax; max = initialMax; moves = 0; } public boolean eat() { max = initialMax; moves = 0; return true; } public Direction getMove() { moves++; if (moves > 2 * max) { moves = 1; max++; }

}

}

if (moves <= max) { return Direction.NORTH; } else { return Direction.SOUTH; }

// reset movement

// reached bottom of bounce; start next bounce

// on the way up // on the way down

// boolean flag for movement solution public class Tigger extends Critter { private int moves; private int max; private int initialMax; private boolean goingUp; public Tigger(int x) { this.initialMax = x; eat(); // to initialize the other fields } public boolean eat() { max = initialMax; moves = 0; goingUp = true; return true; } public Direction getMove() { moves++; if (moves > max) { moves = 1; if (!goingUp) { max++; } goingUp = !goingUp; }

}

}

if (goingUp) { return Direction.NORTH; } else { return Direction.SOUTH; }

7 of 10


// all-ints solution with two move counters public class Tigger extends Critter { private int northMoves; // initialized to 0 private int southMoves; // initialized to 0 private int max; private int initialMax; public Tigger(int initialMax) { this.initialMax = initialMax; max = initialMax; } public boolean eat() { max = initialMax; northMoves = 0; southMoves = 0; return true; }

}

// reset movement

public Direction getMove() { if (northMoves < max) { northMoves++; return Direction.NORTH; // on the way up } else if (southMoves < max) { southMoves++; return Direction.SOUTH; // on the way down } else { northMoves = 1; southMoves = 0; max++; return Direction.NORTH; // start the next bounce } }

// boolean flag for eating solution public class Tigger extends Critter { private int moves; private int max; private int initialMax; private boolean ate; public Tigger(int initialMax) { this.initialMax = initialMax; max = initialMax; moves = 0; ate = false; } public boolean eat() { ate = true; return true; } public Direction getMove() { if (ate == true) { max = initialMax; moves = 0; } moves++; if (moves > 2 * max) { moves = 1; max++; }

}

}

if (moves <= max) { return Direction.NORTH; } else { return Direction.SOUTH; }

// reset movement

// reached bottom of bounce; start next bounce

// on the way up // on the way down

8 of 10


9. Objects (8 solutions shown) // AM/PM based zen-like solution public boolean isWorkTime() { if (amPm.equals("AM")) { return hour >= 9 && hour <= 11; } else { // PM return (1 <= hour && hour <= 4) || hour == 12 || (hour == 5 && minute == 0); } } // separate out the false cases first public boolean isWorkTime() { if ((1 <= hour && hour <= 8 || hour == 12) && amPm.equals("AM")) { return false; // too early in the morning } else if ((hour == 5 && minute > 0 || 6 <= hour && hour <= 11) && amPm.equals("PM")) { return false; // too late in the evening } else { return true; } } // separate out the true cases public boolean isWorkTime() { if (amPm.equals("AM") && hour >= 9 && hour <= 11) { return true; // 9:00 AM - 11:59 AM } else if (amPm.equals("PM") && hour == 12) { return true; // 12:00 PM - 12:59 PM } else if (amPm.equals("PM") && hour <= 4) { return true; // 1:00 PM - 4:59 PM } else if (amPm.equals("PM") && hour == 5 && minute == 0) { return true; // 5:00 PM } else { return false; } } // ugly style (not very "zen") but it works public boolean isWorkTime() { if (hour == 1 || hour == 2 || hour == 3 || hour == 4) { if (amPm.equals("PM")) { return true; } else { return false; } } else if (hour == 5) { if (minute == 0 && amPm.equals("PM")) { return true; } else { return false; } } else if (hour == 6 || hour == 7 || hour == 8) { return false; } else if (hour == 9 || hour == 10 || hour == 11) { if (amPm.equals("AM")) { return true; } else { return false; } } else { // hour == 12 if (amPm.equals("PM")) { return true; } else { return false; } } } // more "zen-like" version of previous solution public boolean isWorkTime() { if (hour <= 4) { return amPm.equals("PM"); } else if (hour == 5) { return minute == 0 && amPm.equals("PM"); } else if (hour <= 8) { return false; } else if (hour <= 11) { return amPm.equals("AM"); } else { // hour == 12 return amPm.equals("PM"); } }

9 of 10


// "absolute time" solution #1 public boolean isWorkTime() { int totalMins = hour % 12 * 60 + minute; if (amPm.equals("PM")) { totalMins += 12 * 60; } return 9 * 60 <= totalMins && totalMins <= 17 * 60; } // absolute minutes solution #2 public boolean isWorkTime() { int absTime = getMinute(); if (getHour() < 12) { absTime += getHour() * 60; }

}

if (getAmPm().equals("AM")) { return absTime >= 540; // 9:00 == 9 * 60 == 540 } else { return absTime <= 300; // 5:00 == 5 * 60 == 300 }

// take advantage of a temporary ClockTime object public boolean isWorkTime() { ClockTime temp = new ClockTime(9, 00, "AM"); int mins = 0; while (hour != temp.hour || minute != temp.minute || !amPm.equals(temp.getAmPm())) { temp.advance(1); mins++; } return mins <= 60 * 8; // 9-5 is an 8-hour day }

10 of 10


Sample Final Exam #10 (Spring 2010)

1. Array Mystery Consider the following method: public static void arrayMystery(int[] a) { for (int i = 1; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { a[i] = a[i + 1] + a[i - 1]; } } }

Indicate in the right-hand column what values would be stored in the array after the method arrayMystery executes if the array in the left-hand column is passed as its parameter.

Original Contents of Array

Final Contents of Array

int[] a1 = {42, 99, 42}; arrayMystery(a1);

_____________________________________

int[] a2 = {6, 8, 4, 2}; arrayMystery(a2);

_____________________________________

int[] a3 = {7, 7, 20, 8, 1}; arrayMystery(a3);

_____________________________________

int[] a4 = {4, 5, 3, 2, 1, 0}; arrayMystery(a4);

_____________________________________

int[] a5 = {6, 0, -1, 80, 5, 0, -3}; arrayMystery(a5);

_____________________________________

1 of 9


2. Reference Semantics Mystery Write the output of the following program, as it would appear on the console. import java.util.*;

// for Arrays class

public class BasicPoint { int x; int y; public BasicPoint(int initialX, int initialY) { x = initialX; y = initialY; } } public class ReferenceMystery { public static void main(String[] args) { BasicPoint p = new BasicPoint(11, 22); int[] a = {33, 44}; int n = 55; System.out.println(p.x + "," + p.y + " " + Arrays.toString(a) + " " + n); mystery(p, a, n); System.out.println(p.x + "," + p.y + " " + Arrays.toString(a) + " " + n); a[0] = a[1]; p.x = p.y; mystery(p, a, n); System.out.println(p.x + "," + p.y + " " + Arrays.toString(a) + " " + n); } public static int mystery(BasicPoint p, int[] a, int n) { n = 0; a[0] = a[0] + 11; a[1] = 77; p.x = p.x + 33; System.out.println(p.x + "," + p.y + " " + Arrays.toString(a) + " " + n); return n; } }

2 of 9


3. Inheritance Mystery Assume that the following four classes have been defined: public class Leela extends Fry { public void method1() { System.out.print("Leela1 "); } public void method2() { System.out.print("Leela2 "); super.method2(); } }

public class Fry extends Bender { public void method2() { System.out.print("Fry2 "); super.method2(); } } public class Bender { public void method1() { System.out.print("Bender1 "); }

public class Farnsworth extends Bender { public void method1() { System.out.print("Farnsworth1 "); }

public void method2() { System.out.print("Bender2 "); method1(); }

public String toString() { return "Good news everyone!"; }

public String toString() { return "We're doomed!"; }

} }

Given the classes above, what output is produced by the following code? Bender[] rodriguez = {new Leela(), new Bender(), new Farnsworth(), new Fry()}; for (int i = 0; i < rodriguez.length; i++) { rodriguez[i].method2(); System.out.println(); System.out.println(rodriguez[i]); rodriguez[i].method1(); System.out.println(); System.out.println(); }

3 of 9


4. File Processing Write a static method named mostCommonNames that accepts as its parameter a Scanner for an input file whose data is a sequence of lines, where each line contains a set of first names separated by spaces. Your method should print the name that occurs the most frequently in each line of the file. The method should also return the total number of names that were seen in the file. You may assume that no name appears on more than one line of the file. Each line should be considered separately from the others. On a given line, some names are repeated; all occurrences of a given name will appear consecutively in the file. If two or more names occur the same number of times, return the one that appears earlier in the file. If every single name on a given line is different, every name will have 1 occurrence, so you should just return the first name in the file. For example, if the input file contains the following text: Benson Eric Eric Marty Kim Kim Kim Jenny Nancy Nancy Nancy Paul Paul Stuart Stuart Stuart Ethan Alyssa Alyssa Helene Jessica Jessica Jessica Jessica Jared Alisa Yuki Catriona Cody Coral Trent Kevin Ben Stefanie Kenneth

On the first line, there is one occurrence of the name Benson, two occurrences of Eric, one occurrence of Marty, three occurrences of Kim, one of Jenny, three of Nancy, and two of Paul. Kim and Nancy appear the most times (3), and Kim appears first in the file. So for that line, your method should print that the most common is Kim. The complete output would be the following. The method would also return 23, since there are 23 unique names in the entire file. Most common: Kim Most common: Jessica Most common: Jared

You may assume that there is at least one line of data in the file and that each line will contain at least one name.

4 of 9


5. Array Programming Write a static method named swapPairs that accepts an array of strings as a parameter and switches the order of values in a pairwise fashion. Your method should switch the order of the first two values, then switch the order of the next two, switch the order of the next two, and so on. For example, if the array initially stores these values: String[] a = {"four", "score", "and", "seven", "years", "ago"}; swapPairs(a);

Your method should switch the first pair ("four", "score"), the second pair ("and", "seven") and the third pair ("years", "ago"), to yield this array: {"score", "four", "seven", "and", "ago", "years"}

If there are an odd number of values, the final element is not moved. For example, if the original list had been: {"to", "be", "or", "not", "to", "be", "hamlet"}

It would again switch pairs of values, but the final value ("hamlet") would not be moved, yielding this list: {"be", "to", "not", "or", "be", "to", "hamlet"}

You may assume that the array is not null and that no element of the array is null.

5 of 9


6. Array Programming Write a static method named banish that accepts two arrays of integers a1 and a2 as parameters and removes all occurrences of a2's values from a1. An element is "removed" by shifting all subsequent elements one index to the left to cover it up, placing a 0 into the last index. The original relative ordering of a1's elements should be retained. For example, suppose the following two arrays are declared and the following call is made: int[] a1 = {42, 3, 9, 42, 42, 0, 42, 9, 42, 42, 17, 8, 2222, 4, 9, 0, 1}; int[] a2 = {42, 2222, 9}; banish(a1, a2);

After the call has finished, the contents of a1 should become: {3, 0, 17, 8, 4, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}

Notice that all occurrences of the values 42, 2222, and 9 have been removed and replaced by 0s at the end of the array, and the remaining values have shifted left to compensate. Do not make any assumptions about the length of the arrays or the ranges of values each might contain. For example, each array might contain no elements or just one element, or very many elements. (If a2 is an empty array that contains no elements, a1 should not be modified by the call to your method.) You may assume that the arrays passed are not null. You may assume that the values stored in a2 are unique and that a2 does not contain the value 0. You may not use any temporary arrays to help you solve this problem. (But you may declare as many simple variables as you like, such as ints.) You also may not use any other data structures or complex types such as Strings, or other data structures that were not taught in CSE 142 such as the ArrayList class from Chapter 10.

6 of 9


7. Critters Write a critter class Raptor along with its movement and eating behavior. All unspecified aspects of Raptor use the default behavior. Write the complete class with any fields, constructors, etc. necessary to implement the behavior. In the absence of food, Raptors move horizontally. When a Raptor is constructed, he is passed a boolean value that indicates whether he will initially walk west (false) or east (true). The Raptor should remember this value and should continue walking in that direction until he finds food. If a Raptor finds food, he should eat it, and then "stomp" up and down 10 times by moving north-south 10 times. In other words, his next twenty moves after finding food should be N,S,N,S,N,S,N,S,N,S,N,S,N,S,N,S,N,S,N,S. After finishing his ten "stomps" the Raptor should resume moving horizontally, but reverse the direction from west to east or vice versa. For example, if the Raptor had been moving west and then finds food, he will move east once he is done stomping. (If a Raptor finds another food while stomping, he will start over his stomp behavior with another 10 N/S moves.) The following would be a possible sequence of moves for a new Raptor(false) :

W,W,W,W,W,W (eats food), N,S,N,S,N,S,N,S,N,S,N,S,N,S,N,S,N,S,N,S E, E, E, (eats food), N,S,...

The following would be a possible sequence of moves for a new Raptor(true) :

E,E,E,E,E,E,E,E,E,E,E,E (eats food), N,S,N,S,N,S,N,S,N,S,N,S,N,S,N,S,N,S,N,S, W,W,W,W,W,W,W,W (eats food), N,S,N,S,N,S,N,S,N,S,N,S,N,S,N,S,N,S, E, E, E, ...

7 of 9


8. Classes and Objects Suppose that you are provided with a pre-written class BankAccount as described at right. (The headings are shown, but not the method bodies, to save space.) Assume that the fields, constructor, and methods shown are already implemented. You may refer to them or use them in solving this problem if necessary. Write an instance method named transfer that will be placed inside the BankAccount class to become a part of each BankAccount object's behavior. The transfer method moves money from this bank account to another account. The method accepts two parameters: a second BankAccount to accept the money, and a real number for the amount of money to transfer.

// A BankAccount keeps track of a // user's money balance and ID (name), // and counts how many transactions // (deposits/withdrawals) are made. public class BankAccount { private String id; private double balance; private int transactions; // Constructs a BankAccount // object with the given id, and // $0 balance and 0 transactions. public BankAccount(String id) // returns the field values public double getBalance() public String getID() public int getTransactions()

There is a $5.00 fee for transferring money, so this much must be deducted from the current account's balance before any transfer.

// Adds the amount to the balance // Also counts as 1 transaction. public void deposit(double amount)

The method should modify the two BankAccount objects such that "this" current object has its balance decreased by the given amount plus the $5 fee, and the other BankAccount object's balance is increased by the given amount. A transfer also counts as a transaction on both accounts. If this account object does not have enough money to make the full transfer, transfer whatever money is left after the $5 fee is deducted. If this account has under $5 or the amount is 0 or less, no transfer should occur and neither account's state should be modified. }

// Subtracts the amount from // the balance if the user has // enough money. // Also counts as 1 transaction. public void withdraw(double amount) // your method would go here

For example, given the following BankAccount objects: BankAccount benson = new BankAccount("Benson"); benson.deposit(90.00); BankAccount martin = new BankAccount("Marty"); martin.deposit(25.00);

Assuming that the following calls were made, the balances afterward are shown in comments to the right of each call: benson.transfer(martin, 20.00); benson.transfer(martin, 10.00); benson.transfer(martin, -1); martin.transfer(benson, 39.00); martin.transfer(benson, 50.00); martin.transfer(benson, 1.00); benson.transfer(martin, 88.00); benson.transfer(martin, 1.00);

// B $65, M $45 // B $50, M $55 // B $50, M $55 // B $89, M $11 // B $95, M $ 0 // B $95, M $ 0 // B $ 2, M $88 // B $ 2, M $88

(B loses $25, M gains $20) (B loses $15, M gains $10) (no effect; negative amount) (M loses $44, B gains $39) (M loses $11, B gains $ 6) (no effect; no money in acct) (B loses $93, M gains $88) (no effect; can't afford fee)

Write your answer on the next page.

8 of 9


Problem 8 additional writing space

9 of 9


Sample Final Exam #10 Key 1. Array Mystery Expression int[] a1 = {42, 99, 42}; arrayMystery(a1);

Final Contents of Array {42, 84, 42}

int[] a2 = {6, 8, 4, 2}; arrayMystery(a2);

{6, 10, 12, 2}

int[] a3 = {7, 7, 20, 8, 1}; arrayMystery(a3);

{7, 7, 15, 16, 1}

int[] a4 = {4, 5, 3, 2, 1, 0}; arrayMystery(a4);

{4, 7, 9, 10, 10, 0}

int[] a5 = {6, 0, -1, 80, 5, 0, -3}; arrayMystery(a5);

{6, 5, -1, 4, 4, 1, -3}

3. Reference Semantics Mystery 11,22 [33, 44] 55 44,22 [44, 77] 0 44,22 [44, 77] 55 55,22 [88, 77] 0 55,22 [88, 77] 55

3. Inheritance Mystery Leela2 Fry2 Bender2 Leela1 We're doomed! Leela1 Bender2 Bender1 We're doomed! Bender1 Bender2 Farnsworth1 Good news everyone! Farnsworth1 Fry2 Bender2 Bender1 We're doomed! Bender1

1 of 6


4. File Processing // fencepost solution (a bit long) public static int mostCommonNames(Scanner input) { int totalCount = 0; while (input.hasNextLine()) { String line = input.nextLine(); Scanner words = new Scanner(line); String mostCommon = words.next(); totalCount++; int mostCount = 1; String current = mostCommon; int currentCount = 1; while (words.hasNext()) { String next = words.next(); if (next.equals(current)) { currentCount++; if (currentCount > mostCount) { mostCount = currentCount; mostCommon = current; } } else { current = next; currentCount = 1; totalCount++; }

} System.out.println("Most common: " + mostCommon);

}

} return totalCount;

// non-fencepost solution public static int mostCommonNames(Scanner input) { int total = 0; while (input.hasNextLine()) { Scanner words = new Scanner(input.nextLine()); String most = ""; String prev = ""; int max = 0; int count = 0; while (words.hasNext()) { String next = words.next(); if (prev.length() == 0 || next.equals(prev)) { count++; } else { count = 1; total++; } if (count > max) { max = count; most = next; } prev = next; } System.out.println("Most common: " + most); } return total; }

2 of 6


5. Array Programming // "increase i by 2 each time" solution public static void swapPairs(String[] a) { for (int i = 0; i < a.length - 1; i += 2) { String temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } // "i % 2" solution // (doesn't work if you use i%2==1 and [i-1] public static void swapPairs(String[] a) { for (int i = 0; i < a.length - 1; i++) { if (i % 2 == 0) { String temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } } // "multiply indexes by 2" solution public static void swapPairs(String[] a) { for (int i = 0; i < a.length / 2; i++) { String temp = a[i*2]; a[i*2] = a[i*2 + 1]; a[i*2 + 1] = temp; } }

3 of 6


6. Array Programming // "two nested loops, boolean found flag" solution public static void banish(int[] a1, int[] a2) { for (int i = 0; i < a1.length; i++) { // see whether a1[i] is contained in a2 boolean found = false; for (int j = 0; j < a2.length && !found; j++) { if (a1[i] == a2[j]) { found = true; } } if (found) { // shift all elements of a1 left by 1 for (int j = i + 1; j < a1.length; j++) { a1[j - 1] = a1[j]; } a1[a1.length - 1] = 0; i--; } } } // "triple nested loops to remove" solution public static void banish(int[] a1, int[] a2) { for (int i = 0; i < a1.length; i++) { int found = 0; for (int j = 0; j < a2.length; j++) { if (a1[i] == a2[j]) { found++;

}

}

}

}

for (int k = i + 1; k < a1.length; k++) { a1[k - 1] = a1[k]; } a1[a1.length - 1] = 0;

if (found > 0) { i--; }

// a2-based solution public static void banish(int[] a1, int[] a2) { int count = 0; for (int j = 0; j < a2.length; j++) { for (int i = 0; i < a1.length; i++) { if (a1[i] == a2[j]) { for (int k = i; k < a1.length - 1; k++) { a1[k] = a1[k+1]; } count++; a1[a1.length - count] = 0; i--; } } } }

4 of 6


7. Critters public class Raptor extends Critter { private boolean east; private int stompCount;

// "stompCount drops from 20 to 0" solution

public Raptor(boolean startEast) { east = startEast; stompCount = 0; } public boolean eat() { stompCount = 20; east = !east; return true; }

}

public Direction getMove() { if (stompCount > 0) { stompCount--; if (stompCount % 2 == 1) { return Direction.NORTH; } else { return Direction.SOUTH; } } else { if (east) { return Direction.EAST; } else { return Direction.WEST; } } }

public class Raptor extends Critter { private boolean walkEast; private int stompCount = 0; private boolean stomping = false;

// "stompCount goes up from 0 to 20" solution

public Raptor(boolean walkEast) { this.walkEast = walkEast; } public boolean eat() { stompCount = 0; stomping = true; return true; }

}

public Direction getMove() { if (stompCount >= 20) { stompCount = 0; stomping = false; if (walkEast == true) { walkEast = false; } else { walkEast = true; } } if (stomping) { if (stompCount % 2 == 0) { stompCount++; return Direction.NORTH; } else { stompCount++; return Direction.SOUTH; } } else { if (walkEast) { return Direction.EAST; } else { return Direction.WEST; } } }

5 of 6


8. Objects public void transfer(BankAccount other, double amount) { if (amount > 0.00) { if (amount + 5.00 <= balance) { withdraw(amount + 5.00); other.deposit(amount); } else if (balance > 5.00) { other.deposit(balance - 5.00); withdraw(balance); } } } public void transfer(BankAccount other, double amount) { if (balance > 5 && amount > 0) { balance -= 5; if (balance < amount) { amount = balance; }

}

}

other.deposit(amount); withdraw(amount);

public void transfer(BankAccount other, double amount) { if (balance > 5 && amount > 0) { transactions++; other.transactions++; balance -= 5; if (balance >= amount) { other.balance += amount; balance -= amount; } else { other.balance += balance; balance = 0.0; } } }

6 of 6


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.