CSC 1051 Algorithms and Data Structures I Final Examination May 2, 2015 Name: Question Value 1 10 Score 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 20 TOTAL 100 Please answer questions in the spaces provided. If you make a mistake or for some other reason need more space, please use the back of and clearly indicate where the answer can be found. Good luck and best wishes for a wonderful summer!
1. ( / 10) What gets printed? Please show output as it will appear, or indicate NO OUTPUT, or show some of the output followed by INFINITE LOOP. int a = 5; Output: do a--; System.out.println(a); while (a >= 6) System.out.println("Done: " + a); Output: for (int a = 4; a > 0; a++) System.out.println(a * 2); System.out.println("Done: " + a); String[] notes = "do", "re", "mi"; for (String st: notes) System.out.println(st + st); Output: System.out.println("Done: "); for(int a = 1; a <= 3; a++) for (int b = 5; b <= 6; b++) System.out.println(a + "\t" + b); Output: System.out.println("Done");
2. ( / 10) a) Show what gets printed and rewrite using if/else: char ch = 'n'; System.out.print ("The answer is "); switch(ch) case 'y': System.out.println ("positive."); break; case 'N': System.out.println ("negative."); break; default: System.out.println ("unclear."); Output: Using if/else: 2. Show what gets printed and rewrite using while and if/else (i.e., eliminate the for and conditional operator): for (int a = 0; a < 4; a++) System.out.println(a + (a % 2 == 0? " yes": " no ")); Using while and if/else: Output:
3. ( / 10) Consider the following program: import java.util.scanner; import java.io.*; public class FinalS15FileIO public static void main(string[] args) throws IOException Scanner infile; PrintWriter outfile; infile = new Scanner (new File("data-in.txt")); outfile = new PrintWriter("data-out.txt"); while (infile.hasnext()) String line = infile.nextline(); Scanner scan = new Scanner(line); int count = 0; while (scan.hasnext()) String token = scan.next(); count ++; outfile.println(count); outfile.close(); a) Suppose the file data-in.txt is used as the input file. Show the contents of the file data-out.txt after execution of the program. b) List two examples of situations that could cause IOExceptions in the above code. c) Suppose you want to catch and handle the IOExceptions using the following catch clause: catch (IOException e) System.out.println("Warning: problem with IO. Run interactively."); infile = new Scanner(System.in); outfile = new PrintWriter(System.out); (i.e., keep running, but issue a warning and do interactive I/O instead) Show how to incorporate this in the above program: 1) Draw a box around the statements of the above program that you would include in the try block, and 2) mark the position where you would insert the catch code.
4. ( / 10) (a) Write a Java method findmax() with one parameter that is a 2D array of double, that finds and returns the largest of all the values in the 2D array. Assume that all the values will be positive. There may be repetitions, but it should not matter, the method should still return a value that is no less than any of the other values. The method should have one parameter (the 2D array of double) and it should return a double, and not print anything. (b) Assume findmax() is defined as a static method in the class below. Complete the code of main() below to use findmax so as to print the largest of the numbers stored in either of the arrays a and b (i.e., the largest number overall). public class ThisIsATest public static void main(string[] args) double[][] a =... (arrays are initialized with some values) double[][] b =... //**** print the largest value stored in either a or b
5. ( / 10). (a) Show the output produced by the following code fragment: String mess = ""; char[] grades = 'A', 'B', 'C', 'D', F'; for (char ch: grades) mess = ch + mess; System.out.println (mess); (b) Show the output produced by the following code fragment: char[] grades = 'A', 'B', 'C', 'D', F'; for (char ch: grades) System.out.print ((char) (ch + 1)); (c) Suppose an int array ratings contains values in the range 0-3. Write a code fragment that creates an array count that contains the frequency of occurrences of 0 s, 1 s, 2 s and 3 s in the ratings array, and then prints this information. Example: if the array ratings has these contents: ratings 0 1 2 3 4 5 6 2 3 2 1 0 2 2 Your code should create the array count with the following contents: count 0 1 2 3 1 1 4 1 and the output would be: Count for 0: 1 Count for 1: 1 Count for 2: 4 Count for 3: 1 Write your code fragment below. Assume the array ratings is already initialized to some values. Your code should work for any size array.
6. ( / 10) Suppose you have a Die class defined as follows: import java.awt.*; public class Die private int facevalue; // current value showing on the die // Constructor: Sets the initial face value. public Die() facevalue = 1; // Rolls the die and returns the result. public int roll() facevalue = (int)(math.random() * 6) + 1; return facevalue; ç Write your answer on facing page (back of previous page). ç // Face value mutator. public void setfacevalue (int value) facevalue = value; // Face value accessor. public int getfacevalue() return facevalue; // Returns a string representation of this die. public String tostring() String result = Integer.toString(faceValue); return result; // Draws the die on page at position x, y. public void draw (Graphics page, int x, int y) page.setcolor (Color.white); page.fillrect (x, y, 30, 30); page.setcolor (Color.black); page.drawstring(integer.tostring(facevalue), x+10, y+20); On the facing page, write the Java code for a driver class that uses the Die class to determine how likely it is to roll snake eyes, i.e., two ones. Use the following approach: Ø Declare and instantiate two Die objects, die1 and die2 Ø Roll them 10,000 times (or some sufficiently large number, specified by a constant in your program) while keeping track of how many times you rolled ones on both dice Ø In the end, print how many times the dice were rolled, the number of snake eyes, and proportion of snake eyes (i.e., probability). Careful: use a cast when dividing integers!
7. ( / 10) Suppose you have a Passenger class defined as follows to represent passengers in the Titanic: public class Passenger // instance data private int status; private boolean child; private char sex; private boolean survivor; // constructor public Passenger(int status, boolean child, char sex, boolean survivor) this.status = status; this.child = child; this.sex = sex; this.survivor = survivor; // tostring() returns String description of Passenger public String tostring() String pass = ""; switch (status) case 1: pass += "1st class\t"; break; case 2: pass += "2nd class\t"; break; case 3: pass += "3rd class\t"; break; case 4: pass += "crew\t"; break; pass += (child? "child": "adult") + "\t"; pass += ((sex == 'm')? "male" : "female") + "\t"; pass += (survivor? "survived": "perished"); return pass; On the next page, write the code for a PassengerCollection class to represent the list of passengers of the Titanic and to keep track of total number of passengers and survivors, using an array of Passenger objects. Some bits of the code and comments are already written. Use these comments as guidelines for your code, in the spaces provided on the next page. Note that you only need to implement the constructor and addpassenger() methods, which should initialize and update, respectively, the array and the two counts (i.e., count and numsurvivors).
(Question 7, continued) public class PassengerCollection private Passenger[] collection; private int count; private int numsurvivors; // additional count: survivors //------------------------------------------------------ // Constructor: Creates an initially empty collection // with space for up to 5000 passengers. // Initializes count and numsurvivors appropriately. //------------------------------------------------------ //------------------------------------------------------ // Method addpassenger(): Adds a Passenger to the // collection. Update // count and numsurvivors. //------------------------------------------------------ public void addpassenger (int status, boolean child, char sex, boolean survivor)
8. ( / 10) Construct an algorithm that inputs an integer num and 10,000 other integers and prints a message indicating whether num was found among the 10,000 other integers, followed by a goodbye message. Hint: You need to use a boolean variable found to keep track of whether you found a match. Example: If num (i.e., the first number input) is 1318, and 10,000 other numbers are input after that, none of which is equal to 1318, the algorithm should print: Searching for 1318 Not found Goodbye Alternatively, if the number 1318 occurred one or more times among the other numbers, it should print: Searching for 1318 Found it! Goodbye Directions: Write your algorithm by rearranging and structuring elements chosen from the list below, using indentation to show structure. Do not use anything else and note that not all of these are needed, but you may use one of them more than once, if necessar found = true found = false input num input x count = 1 count = count + 1 x = x + 1 if (x == num) if (found) if (found == true) if (found == false) if (x!=num) else while (count <= 10000) while (num <= 10000) while (count <= num) print Searching for num print x print num print Found it! print Not found print Goodbye
9. ( / 20) Write a complete Java program consisting of a datatype Cat and a client CrazyCatLady and draw a UML class diagram for your classes. Example: Ø Name: Henri Ø Age: 7 Ø Lives: 5 a) The Cat class should have the following methods: Constructor: One parameter (for the name). Sets Cat s age to 0 and lives to 9. birthday(): increases age of Cat by 1. death(): decreases the Cat s number of lives by 1. tostring(): returns a String corresponding to this Cat. getage(): returns this Cat s age draw(graphics page, int x, int y): draws this Cat in the current Graphics context at position x, y. Please do not do anything fancy here: just draw a simple shape to represent the cat and add its name nearby.add another feature such as color or different shape to depict the age or number of lives (you only need to do one of them). b) The client CrazyCatLady should implement the following algorithm: o Instantiate three variables of the Cat class named cat1, cat2, cat3 (Kindly make up funny names for them I m spending my holidays grading this exam! J ) o Print the info of cat1, cat2, cat3 Let s pretend that two years have gone by So the Cats ages need to increase. Also, cat3 has done something stupid and loses a life. Write some code that uses the birthday() and death() methods to model this situation. o Print the info of cat1, cat2, cat3 (again). o Calculate and print the average age of the cats. o NOTE: this is not a graphical class, so it does NOT use the draw() method at all. c) Draw a UML class diagram depicting the classes Cat and CrazyCatLady. Write the complete code for the two classes and UML diagram in the next 3 pages. It is NOT necessary to include comments with your code, but be sure to use good indentation. è è è