Explanations are often given in the comments. Read the comments carefully. Below are some important ideas for developing algoithms. They may make more sense after you read/try the review questions. I put them up front to make sure that you see them. Important ideas for developing algoithms (learned from review questions below): + Try to identify when iterations are necessary or "Smell the iteration" When you say to yourself "do something until some condition is met," that's an iteration, like question 6 below. This is what we call indefinite iteration--you don't know how many iterations before you stop. In this case, $while$ is a good loop to use. Ask yourself what is the condition for continuing the iteration and how to update the variable(s) to be tested in that condition. Sometimes, some "smart" initialization is needed to enter the loop correctly. Don't let that bother you--just start by writing the general condition for continuing the iteration and whatever initialization you can think of. Then go back to check to see if you enter the loop correctly and make sure that your update works properly. Now you're ready to make any necessary changes to make the initialization/condition "smart." When you say to yourself "one at a time," like "add one space at a time" in question 4a, that's an iteration also. If you know when to stop (e.g., add $x$ spaces), a good choice is the $for$ loop. + Try to identify simple tasks within a complicated problem/procedure. In an exam, we sometimes help you break down the problem by listing the methods or saying that one method should call another. Tackle the simple tasks one at a time, but occasionally jump around for inspiration. Don't forget to check the whole thing in the end! + Give yourself a concrete example and draw some diagrams, box-scope or not. If you went to the review session, think back to how we worked on question 6. Sometimes we help you by giving you an example in the question statement. Read (and analyze) the example and any example output carefully! Lots of information/insights can be gained. E.g., instance vs static, parameter types for methods, etc. ============================================================ Question 1: Box-scope diagram Numbers in square brackets [] indicate step number. Please see http://courses.cs.cornell.edu/cs100/2000sp/Prelims/box.txt for step-by-step explanation. class Frippy { int x; Frippy F; } class Boingo { String a; Frippy b; } public class Problem1 { public static void main(String[] args) { Frippy F1 = new Frippy(); Frippy F2 = new Frippy(); Boingo B1 = new Boingo(); Boingo B2 = new Boingo(); B2.a = "grok"; B1.b = new Frippy(); F2.F = B1.b; B1.b.F = F1; ++B1.b.F.x; Boingo B3; F2 = null; // ****draw the box/scope diagram up to this point*** } } class Problem1 +--------------------------------------------------------------[10]-+ | +---+ +---+ +----+ +---+ +---+ +---+ | | args | *-+-+ F1 | * | F2 |null| B1 | * | B2 | * | B3 | ? | | | +---+ | +-+-+ +-+--+ +-+-+ +-+-+ +---+ | +------------+------+----------+----------+----------+--------------+ | | | | | <----+ | [1] [11] X [2] [3] +--+ [4] +------+ class Frippy | | | | +-------------------+----------+-------------+--------------+--------------+ | [12] V | | | [12] | | +--\-------/ +----------+ >+----------+ | +----------+ | +--\-------/ | | | \----+/| | \-/--+ | | +----+ | | | +----+ | | | \----+/| | | | x |\ / | | x |0[9]|1| | x |0 | | | | x |0 | | | | x |\ / | | | | +-\-/+ | | /-\--+ | | +----+ | | | +----+ | | | +-\-/+ | | | | X | | | | [7] | | | | | | X | | | | +-/-\+ | | +----+ | | +-\-/+ | | | +-\-/+ | | | +-/-\+ | | | | F |/ \ | | F |null| | | F |nuXl*-+-+>| F |nuXl| | | | F |/ \ | | | | /----+\| | +----+ | | +-/-\+ | | | +*/-\+ | | | /----+\| | | +--/-------\ +----------+ +----------+ | +----+-----+ | +--/-------\ | | [8] ^----------------+------+ ^ | | +--------------------------------------------+--------+-----+--------------+ | | | | [6] | | class Boingo | | | +--------------------------------------------+--------|-----+--------------+ | [12] [12] [12] | | | | | +--\-------/ +--\-------/ +--\-------/ +>+------|---+ +>+----------+ | | | \----+/| | \----+/| | \----+/| | +--|-+ | | +-\-/+ | | | | a |\ / | | a |\ / | | a |\ / | | a |nu|l| | | a |nuXl*-+-+-+ | | +-\-/+ | | +-\-/+ | | +-\-/+ | | +--|-+ | | +-/-\+ | | | | | X | | X | | X | | | | | | | | | | +-/-\+ | | +-/-\+ | | +-/-\+ | | +-\*/+ | | +----+ | | | | | b |/ \ | | b |/ \ | | b |/ \ | | b |nuXl| | | b |null| | | | | | /----+\| | /----+\| | /----+\| | +-/-\+ | | +----+ | | | | +--/-------\ +--/-------\ +--/-------\ +----------+ +----------+ | | | | | +--------------------------------------------------------------------------+ | | class String | +----------------------+ | | | [5] | | "grok"<--------------+-----------------------------------------------------+ | | +----------------------+ ============================================================ Question 2: constructors, passing parameters Solution: $swap4$ is the only method that swaps sucessfully. Use box-scope diagrams to prove it to yourself. //------------------------------------ // Class $FatInteger$ is a "wrapper class". Its purpose is to allow us to // treat an $int$ as an object by simply storing the $int$ in an object. // It provides constructors to create $FatInteger$s, a method to set the value // of a $FatInteger$ from another $FatInteger$, and a $toString()$ method. class FatInteger{ private int n; // the interger inside the object // Constructor for default case ($n$=0), no argument FatInteger(){} // Constructor: assign to $n$ the value of an integer argument FatInteger(int n){ this.n = n; // note: $this$ is necessary } // Constructor: assign to $n$ the value stored in the $FatInteger$ argument FatInteger(FatInteger other){ this.n = other.n; // note: $this$ is NOT necessary } // Set the value of a FatInteger based on another FatInteger void setValue(FatInteger other){ this.n = other.n; // note: $this$ is NOT necessary } // The toString() method for printing public String toString(){ return "" + n; } } class Swap{ public static void main(String arg[]){ // Call various methods to attempt to swap the variables that are // passed to the methods. You determine which of them succeed. // Predict the output from each of the four print statements. int x = 5, y = 7; swap1(x,y); System.out.println("After swap1, x = " + x + ", y = " + y); FatInteger p = new FatInteger(6); FatInteger q = new FatInteger(8); swap2(p,q); System.out.println("After swap2, values in p, q are " + p + ", " + q); FatInteger r = new FatInteger(15); FatInteger s = new FatInteger(17); swap3(p,q); System.out.println("After swap3, values in r, s are " + r + ", " + s); FatInteger t = new FatInteger(16); FatInteger u = new FatInteger(18); swap4(t,u); System.out.println("After swap3, values in t, u are " + t + ", " + u); } static void swap1(int a, int b){ int temp; temp = a; a = b; b = temp; } static void swap2(FatInteger a, FatInteger b){ FatInteger temp; temp = a; a = b; b = temp; } static void swap3(FatInteger a, FatInteger b){ FatInteger temp; temp = new FatInteger(a); a = new FatInteger(b); b = new FatInteger(temp); } static void swap4(FatInteger a, FatInteger b){ FatInteger temp = new FatInteger(); temp.setValue(a); a.setValue(b); b.setValue(temp); } } ============================================================ Question 3: Returning multiple values in methods via objects Write the code for method $calcStats$ to calculate some statistics given 3 numbers. Then fill in the missing code in method $main$ where you call the $calcStats$ method. If necessary, check out the example in the book on page 227 (in the grey box) for additional help. //------------------------------------ // class StatValues{ // instance variables double average; double minimum; double maximum; // constructor that does nothing public StatValues(){} } class Statistics{ // main method public static void main(String[] args){ // assign 3 double variables // note: we forgot to declare num1,num2,num3 in the original question double num1=12.32; double num2=66.01; double num3=32.39; // call method $calcStats$ to get the average, minimum, // and maximum for the 3 numbers above //--------------------------------------------- StatValues mystat=calcStats(num1,num2,num3); //--------------------------------------------- // Output System.out.println("My avg: "+mystat.average); System.out.println("My min: "+mystat.minimum); System.out.println("My max: "+mystat.maximum); } // Determine the average, minimum, and maximum of exactly 3 $double$ // numbers. Return a reference to an object of class $Statvalues$ . // (Once you know how arrays work you can easily change the code // to determine these statistics for any number of numbers.) public StatValues calcStats(double a,double b,double c){ StatValues result; // reference variable for results result=new StatValues(); double sum=a+b+c; double min,max; // determine $max$ and $min$ if (a<=b){ min=a; max=b; } if (min>c) min=c; if (max S --> S --- | | S denotes station | | ---- S <-- S <- Each station has a name and an integer level of difficulty ranging from 1 to 4, inclusive. A person can start at any station and can visit any station at most once. At any station, (do the exercise and) roll a 4-sided dice. If the dice comes up equal to the degree of difficulty of the current station, stop. Otherwise go to the next station, (exercise and) repeat decision process. Complete class $Station$ below. Objects of class $Station$ have the fields: $name$, $difficulty$, $nextstop$ and the following methods: go_on() Decide if condition is met for going to next $Station$ (return $boolean$ value) itinerary() Print the names of the start and end stations Must call method $go_on()$ Method $main$ below is complete and serves as an example of the usage of class $Station$. This example instantiates 3 $Station$s, forms a directed loop, and calls method $itinerary()$ of the chosen starting $Station$. //------------------------------------ // Notes to solutions below: // Notice that all the variables, methods are INSTANCES (as opposed to CLASS), // so each $Station$ object instiantiated has all the variables and methods // listed above. As you code, always ask yourself "FROM WHICH object?" or // "IN WHICH object?". // Before starting to code, read the example carefully to orient youself. // The simulation of an exercise routine is done using one single call of // method $itinerary$. Ask yourself WHICH method $itinerary$?! It is the // one in the starting $Station$ (object). What's the implication? Within // the method $itinerary$, $this$ refers to the starting $Station$ // class Station { String name; // station name int difficulty; // degree of difficulty [1..4] Station nextstop; // next station // Choose to go on unless 4-sided dice comes up equal to current // degree of difficulty. boolean go_on() { // Hint: $(int) (Math.random()*4)+1)$ returns 1, 2, 3, or 4 return (difficulty != (int) (Math.random()*4)+1); } // Print names of start station and last station at which exercise is done void itinerary() { // Note: $itinerary$ is an INSTANCE method. It is called once to // start a simulation of an exercise routine. // Create a pointer (reference variable) $current$ to indicate which // $Station$ you are at currently. Initialize it to be the // starting $Station$, given by $this$. Station current=this; System.out.println("Start at station " + this.name); // or just $name$ instead of $this.name$ // Algorithm: keep going unless next station is starting station or // go_on() returns false while (current.nextstop != this && current.go_on()) current = current.nextstop; // Note: $this$ ALWAYS refers to the STARTING $Station$, the // object from which instance method $itinerary$ is called, // regardless of which station $current$ points to. System.out.println("Last exercise at station " + current.name); } } //class Station public class ExercisePath { public static void main(String[] args) { // Set up exercise path Station sp = new Station(); Station ss = new Station(); Station sj = new Station(); sp.name = "Push-ups"; sp.difficulty = 3; sp.nextstop = ss; ss.name = "Sit-ups"; ss.difficulty = 2; ss.nextstop = sj; sj.name = "Jumping jacks"; sj.difficulty = 1; sj.nextstop = sp; // Start at Station ss this time and print exercise itinerary ss.itinerary(); } } //class ExercisePath ============================================================