CSC 1051 Algorithms and Data Structures I Final Examination December 17, 2013 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 this page or the extra blank page at the end and clearly indicate where the answer can be found. Good luck and best wishes for the holidays and the New Year!
1. ( / 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. For 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.
2. ( / 10) Draw diagrams showing the contents of the arrays after execution of the following code fragment: a) int[] a = 3, 5, 2; int[] b = new int[8]; for (int i=0; i<a.length; i++) b[i] = a[i]; for (int i=b.length - 1; i >= a.length; i--) b[i] = a[0]; b) int[][] table = new int[4][5]; for (int i=0; i < 3; i++) table[i][i+1] = i + 10; c) char[][] table = new char[3][3]; String sample = "Relax. Exams can be fun. "; int count = 0; for (int i=0; i < 3; i++) for (int j=0; j < 3; j++) table[i][j] = sample.charat(count); count++;
3. ( / 10) Show what gets printed with the file contents shown below. //********************************************************* **** // SomethingToDoWithFiles.java Author: MAP //********************************************************* **** import java.util.scanner; public class SomethingToDoWithFiles public static void main(string[] args) throws IOException File myfile1 = new File("sample1.inp"); filescan1 = new Scanner (myfile1); int count = 0; while (filescan1.hasnext()) String line = filescan1.nextline(); Scanner scanline = new Scanner(line); String[] word = new String[3]; for (int i = 0; i< 3; i++) word[i] = scanline.next(); System.out.println(count + " " + word[2])); count++; System.out.println("All done " + count); sample1.inp do re mi re mi fa mi fa sol
4. ( / 10) (a) Write the Java code for a method named counta() that accepts a String parameter named str. The method should compute and return the number of occurrences of the letter A in str. For example, if the method is invoked with the String HAPPY BIRTHDAY, it should return 2. (b) Assume counta() is defined as a static method in some class, and that a String has already been obtained from the user and stored in a variable named msg. Write a code fragment that could be used in the main() method of that class to invoke counta() so as to print the number of A s in msg as follows: The message contains 2 occurrences of the letter A. (In this example, we assume msg= HAPPY BIRTHDAY but your code should work for any String.) Note: Be sure that your code, above, always use singular/plural appropriately.
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(100, 100, 100); // what s this color? page.setcolor( mycolor); page.fillrect(0, 0, 300, 200); page.setcolor( Color.black ); page.drawline(0, 200, 300, 0); page.setcolor( Color.red); page.filloval(-50,-50,100,100); 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 b) What do you think the mycolor looks like? 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.
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.): java.bogus Class Awesome java.lang.object java.bogus.awesome public class Awesome 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 Awesome(int x) Creates a new Awesome object of size x. Method Summary int computate(boolean x, char y) Mystery method 1. void updator(int x) Mystery method 2. getth a) What import statement do you need to include in your program in order to use this class? 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).
(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. Method name: Method return type: Required paramaters for the method: (how many? of what type(s)?) Method name: Method return type: Required paramaters for the method: (how many? of what type(s)?) d) Suppose you are writing a driver class that uses Awesome 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 Awesome.updator (5); thing1.updator (int x); thing1. computate (boolean x, char y); thing1. computate (false, 'y'); thing2.updator(); thing2.updator(0); if (thing2.computate(true, 'y') > thing1.computate(true, 'y')) System.out.println( ok ); thing1.computate (false, 'y'); same as previous thing2.updator(1) = 2; System.out.println(thing1.computate(false, 'y'));
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 PassengerData 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 PassengerData private Passenger[] collection; private int count; private int numsurvivors; //------------------------------------------------------ // Constructor: Creates an initially empty collection // with space for up to 5000 passengers. //------------------------------------------------------ //------------------------------------------------------ // Method addpassenger(): Adds a Passenger to the // collection. //------------------------------------------------------ public void addpassenger (int status, boolean child, char sex, boolean survivor)
8. ( / 10) Construct an algorithm that inputs a number num and prints all its factors (i.e., all the values of x in the range 2 (num- 1) such that num is divisible by x). After the factors are printed, print a goodbye message. Note: You are NOT being asked to print the only prime factors (that one is more challenging). Example: If num (i.e., the input) is 20, the algorithm should print: The factors of 20 are: 2 4 5 10 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 necessary. input num input x x = 1 x = 2 x = x + 1 if (num % x == 0) if (num % 2 == 0) if (num % 2 == x) else while (x < num) while (x <= num) while (num %2 == x) while (num % 2 == 0) print The factors of num are: print x print num print Goodbye
9. ( / 20) Write a complete Java program consisting of a class Book and a driver class named Bookshelf. The Book class should contain instance variables representing information such as the following: Example: Ø Title: A Confederacy of Dunces Ø Author: John Kennedy Toole Ø Average Customer Review: 4.2 Ø Price: $11.48 Ø Quantity in stock: 52 The Book class should have a constructor, accessor and mutator methods for the average customer review score, and a tostring() method. Do not write code for any additional methods (no need to write accessors and mutators for all instance variables). The driver class Bookshelf should implement the following algorithm: o Instantiate three variables of the Book class named item1, item2, item3 (make up values for the data) o Print the info of item1, item2, item3 o Change the average customer review score for item2 (make up a new value) o Print the info of item1, item2, item3 Notes: It is NOT necessary to include comments with your code, but be sure to use good indentation. Reminder: Formatting a number as a currency: Example: (assumes import java.text.numberformat; ) NumberFormat fmt = NumberFormat.getCurrencyInstance(); System.out.println(fmt.format(3.4)); è Prints: $3.40 Write the complete code for the two classes in the next two pages. è è