Exam Solutions: =============== Problem 1: ---------- /** * This is one way to write it. You need to be careful to compare the * string lengths, but *return* a string rather than a length. */ public String longestString(String a, String b, String c) { if (a.length() > b.length()) { if (a.length() > c.length()) { return a; } else { return c; } } else { if (b.length() > c.length()) { return b; } else { return c; } } } Problem 2: ---------- a) The mystery method takes an int and a list of ints, and inserts the value into the list at a position that would keep the list ordered. (That is, if the input list was ordered before calling this method, it's still ordered afterwards.) I'd probably call it "orderedInsert" or something similar. b) There's a loop in the body of the method, so we'd want to run enough test cases to at least exercise 0, 1, and many iterations of the loop. These three test cases would do that: mystery(10, []) // Pass it an empty list -- zero iterations of loop mystery(10, [5]) // Causes while loop to iterate once mystery(10, [5,6,7,8]) // Iterate multiple times To be thorough, I'd also want to verify that it can insert at the beginning of a non-empty list, in the middle, and at the end. For example: mystery(1, [5,6,8]) // Inserting at the front mystery(7, [5,6,8]) // Inserting in the middle mystery(9, [5,6,8]) // Inserting at the end I'd probably also want to make sure it handles ties properly: mystery(7, [5,6,7,8]) Problem 3: ---------- a) Binary Search can only be performed on sorted arrays. Linear Search can make more sense when searching unsorted arrays. b) A count-controlled loop performs some action a specific number of times, while an event-controlled loop keeps repeating an action until some condition is true. You might use a count-controlled loop to move a Boulder a specific number of times, for example, while you'd use an event-controlled loop to keep reading from a file until the file runs out. c) Sorting is more work than searching. For an array of size N, it takes roughly N^2/2 computational steps but only N, worst case, to search. N^2 grows much more rapidly than N as the array size increases. d) Testing small pieces first means you can count on those small pieces working correctly when you move on to test more complex code. It also means that if something goes wrong it's easier to find and fix since the bug is occurring in a small piece of code. Problem 4: ---------- public Dice(int numDice, int numSides) // Part a { dice = new Die[numDice]; for (int i=0; i= 1 while(s.hasNextInt()) { int next = s.nextInt(); if (next > max) { max = next; } } return max; } else { return -1; } } Problem 6: ---------- Blanks are: 0 data.length left != right-1 (or right-left > 1, or left+1 != right) right = mid left = mid