Answer Key
CSC1051 Data Structures and Algorithms I Fall 2014 Dr. Papalaskari
CSC 1051 Algorithms and Data Structures I
Final Examination December 19, 2014
Name:______________________________
Question Value Score 1 10
2 10
3 10
4 10
5 10
6 10
7 10
8 20
9 10
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 happy holiday season!
Answer Key
CSC1051 Data Structures and Algorithms I Fall 2014 Dr. Papalaskari
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 = 0; while (a > 0) { System.out.println(a); a = a + 3; } int a = 5; do { System.out.println(a); a++; } while (a >= 6) for (int a = 4; a > 0; a--) System.out.println(a * 2); String[] a = {"red", "green", "blue"}; for (String st: a) System.out.println(st.charAt(0));
Output: NO OUTPUT
Output: r g b
Output: 5 6 7 … INFINITE LOOP
Output: 8 6 4 2
Answer Key
CSC1051 Data Structures and Algorithms I Fall 2014 Dr. Papalaskari
2. (________/ 10) a) Show what gets printed and rewrite using a while and if/else (i.e., eliminate the do and switch): int a = 6;
do { System.out.print(a + " is "); int category = a/3; switch(category) { case 0: System.out.println ("red."); break; case 1: System.out.println ("green."); break; default: System.out.println ("yellow."); } a--; } while (a > 1);
b) Rewrite using while and the conditional operator (i.e., eliminate the for and if/else):
for (int a = 0; a < 5; a++) { System.out.print(" This question is worth " + a); if (a == 1) System.out.print(" point. "); else System.out.print(" points. ");
}
Output: 6 is yellow 5 is green 4 is green 3 is green 2 is red
Using while and if/else: int a = 6; while (a > 1) { System.out.print(a + " is "); int category = a/3;
if (category == 0) System.out.println ("red."); else if (category == 1) System.out.println ("green."); else System.out.println ("yellow."); a--; }
Using while and conditional operator: int a = 0; while (a < 5) { System.out.println(" This question is worth " + a + (a == 1 ? " point. ": " points. ")); a++; }
Answer Key
CSC1051 Data Structures and Algorithms I Fall 2014 Dr. Papalaskari
3. (________/ 10) Show what gets printed with the file contents shown below. //******************************************************** // SomethingToDoWithFiles.java Author: MAP //******************************************************** import java.util.Scanner; import java.io.*; public class SomethingToDoWithFiles { public static void main (String[] args) throws IOException { String line1, line2; Scanner fileScan1, fileScan2; File myFile1 = new File("sample1.inp"); fileScan1 = new Scanner (myFile1); File myFile2 = new File("sample2.inp"); fileScan2 = new Scanner (myFile2); while (fileScan1.hasNext() && fileScan2.hasNext()) { line1 = fileScan1.nextLine(); line2 = fileScan2.nextLine(); System.out.println (line1 + " and " + line2); } System.out.println(fileScan2.hasNext()? "do do do": "re re re"); } } OUTPUT: do re mi and mi fa re mi fa and fa sol mi fa sol and sol sol sol sol re re re
sample1.inp do re mi re mi fa mi fa sol
sample2.inp mi fa fa sol sol sol sol sol
Answer Key
CSC1051 Data Structures and Algorithms I Fall 2014 Dr. Papalaskari
4. (________/ 10) Write the code for a Java method avgArray()that computes and returns the average of all the numbers stored in an array of double. The method should have one parameter (the array of double) and it should return the average computed (also a double). Note that the method should not print anything.
(b) Assume avgArray() is defined as a static method in a class named Utilities. Complete the code for the client below to use avgArray() from Utilities so as to print the averages of the numbers stored in each of the arrays a and b. public class ThisIsATest { public static void main(String[] args) { double[] a = {88.2, 72.5, 90.0}; double[] b = {1, 3, 4, 2.5, 7, 1.2, 6}; //**** print the average of each array
System.out.println(“Average of array a: “ + Utilities.avgArray(a));
System.out.println(“Average of array b: “ + Utilities.avgArray(b));
} }
public static double avgArray(double[] array) { double sum = 0; for (double value: array) sum += value; return sum/array.length; }
Answer Key
CSC1051 Data Structures and Algorithms I Fall 2014 Dr. Papalaskari
5. (________/ 10) Review the program and answer the questions below: import java.awt.*; import javax.swing.JApplet; public class FinalApplet extends JApplet { public void paint( Graphics page) { Color myColor = new Color(50, 50, 50); // what’s this color? page.setColor( myColor); page.fillRect(0, 0, 200, 300); page.setColor( Color.blue ); page.drawLine(0, 300, 200, 0);
page.setColor( Color.red); page.fillOval(-100,-100,200,200); } }
a) For each identifier listed in the table, specify what it refers to – choose one of the following:
Class ....... Method......... Object......... Package (Note: some of these may occur more than once)
java.awt JApplet Graphics page Color myColor setColor fillOval package class class object class object method method
b) What do you think the myColor looks like? __________gray____(dark)___ c) Draw a sketch of the image displayed by the applet – indicate the color of each figure or line. Be sure to label the coordinate system. 0 100 200 300 400
100
200 300 400
Answer Key
CSC1051 Data Structures and Algorithms I Fall 2014 Dr. Papalaskari
6. (________/ 10) Suppose you look up a class in the Java API and find something that looks like the following (NOTE: this is a made-‐up class.):
a) What import statement do you need to include in your program in order to use this class? import java.exam.Mystery; b) Write some code to declare variables for two objects of this class, named thing1 and thing2 (use any values of the appropriate type in the constructor). Mystery thing1 = new Mystery(3.14); Mystery thing2 = new Mystery(42.0);
java.exam Class Mystery java.lang.Object
java.exam.Mystery
public class Mystery extends Object
This is a made-up class. It does not matter what it actually does, I am just trying to see if you know how to use it.
Constructor Summary
Mystery(double x) Creates a new Mystery object.
Method Summary
boolean decider(int x, String y) Mystery method 1.
void updator(double x) Mystery method 2.
Answer Key
CSC1051 Data Structures and Algorithms I Fall 2014 Dr. Papalaskari
(Question 6, continued) c) For each of the methods listed in the method summary, state its name, return type and the number and types of parameters it requires.
d) Suppose you are writing a driver class that uses Mystery and you have already declared and instantiated objects thing1 and thing2. For each of the following, check the appropriate box to indicate whether it represents a valid Java statement. Valid Java statement? Yes No thing1.updator(5.3); ✓
thing1.updator(double x); ✓
Mystery.updator(double x); ✓
Mystery.updator(7.2); ✓
thing2.decider(int x, String y); ✓
thing2.decider(5, "d"); ✓ ✓☛
System.out.println("answer= " + thing2.decider(5, "d")); ✓
System.out.println("answer= " + thing2.updator(7.2)); ✓
if (thing2.updator(0) == 2.0) System.out.println("ok");
✓
if (thing2.decider(5, "d")) System.out.println("ok");
✓
☛ accepting both answers as correct, since the method can be used as standalone statement, although it does not make much sense that way.
Method name: ___________________ Method return type: ___________ Required parameters for the method: (how many? of what type(s)?) _____________________________________________________
Method name: ___________________ Method return type: ___________ Required parameters for the method: (how many? of what type(s)?) _____________________________________________________
Answer Key
CSC1051 Data Structures and Algorithms I Fall 2014 Dr. Papalaskari
7. (________/ 10) Suppose you have a Die class defined as follows: //******************************************************************** // Die.java Author: Lewis/Loftus // Represents one die with faces showing values between 1 and 6. //******************************************************************** import java.awt.*; public class Die { private final int MAX = 6; // maximum face value 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() * MAX) + 1; return faceValue; } // 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; } } 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!
ç Write your answer on facing page (back of previous page). ç Answer key on next page
Answer Key
CSC1051 Data Structures and Algorithms I Fall 2014 Dr. Papalaskari
public class SnakeEyes { public static void main(String[] args) { final int NUM_TIMES = 10000; Die die1 = new Die(); Die die2 = new Die(); int snakes = 0; // counter for snake eyes for (int i = 0; i < NUM_TIMES; i++) { die1.roll(); die2.roll(); if (die1.getFaceValue() == 1 && die2.getFaceValue() == 1) snakes ++; } System.out.println("The dice were rolled " + NUM_TIMES); System.out.println("There were " + snakes + " snake eyes."); System.out.println("Approximate probability of " + "getting snake eyes: " + ((double) snakes/ NUM_TIMES)); } }
Answer Key
CSC1051 Data Structures and Algorithms I Fall 2014 Dr. Papalaskari
8. (________/ 20) Write a complete Java program consisting of a datatype Cat and a client named CrazyCatLady. The Cat class should contain instance variables representing information about the Cat: Example:
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
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.
Write the complete code for the two classes in the next two pages. It is NOT necessary to include comments with your code, but be sure to use good indentation. Notes:
• It is NOT necessary to include comments with your code, but be sure to use good indentation.
Write the complete code for the two classes in the next two pages. èè
Ø Name: Henri Ø Age: 7 Ø Lives: 5
Answer Key
CSC1051 Data Structures and Algorithms I Fall 2014 Dr. Papalaskari
public class Cat { private int age; private int lives; private String name; // Constructor: One parameter (for the name). // Sets Cat's age to 0 and lives to 9. public Cat(String name) { this.name = name; age = 0; lives = 9; } // birthday(): increases age of Cat by 1. public void birthday() { age++; } // death(): decreases the Cat's number of lives by 1. public void death() { lives--; } // toString(): returns a String corresponding to this Cat. public String toString() { return (name + ", Age: " + age + ", Lives: " + lives); } // getAge(): returns this Cat's age public int getAge() { return age; } }
Answer Key
CSC1051 Data Structures and Algorithms I Fall 2014 Dr. Papalaskari
public class CrazyCatLady { public static void main(String[] args) { //Instantiate 3 variables of the Cat class named cat1, cat2, cat3 Cat cat1 = new Cat("Macavity"); Cat cat2 = new Cat("Mungojerrie"); Cat cat3 = new Cat("Rumpelteazer"); // print info on cats System.out.println(cat1); System.out.println(cat2); System.out.println(cat3); // Let's pretend that two years have gone by… // So the Cats' ages need to increase. cat1.birthday(); cat2.birthday(); cat3.birthday(); cat1.birthday(); cat2.birthday(); cat3.birthday(); // Also, cat3 has done something stupid and loses a life. cat3.death(); // print info on cats System.out.println(cat1); System.out.println(cat2); System.out.println(cat3); // Calculate and print the average age of the cats. System.out.println( "Average feline age: " + (double) (cat1.getAge() + cat2.getAge() + cat3.getAge()) / 3 ); } }
Answer Key
CSC1051 Data Structures and Algorithms I Fall 2014 Dr. Papalaskari
9. (________/ 10) Draw the UML class diagram for the previous problem, i.e., depicting the classes Cat and CrazyCatLady.
CrazyCatLady
main(args: String[]): void
Cat name: String age: int lives: int
birthday(): void death(): void toString: String getAge(): int
Answer Key
CSC1051 Data Structures and Algorithms I Fall 2014 Dr. Papalaskari
Answer Key
CSC1051 Data Structures and Algorithms I Fall 2014 Dr. Papalaskari
Answer Key
CSC1051 Data Structures and Algorithms I Fall 2014 Dr. Papalaskari