CIS 1068: Practice Final 1 [I assume you remember well the class Fraction dealt with in one of our homeworks]: 1. Assignments among primitive types and wrapper types Which of the following is a legal assignment? a. int x = 0; boolean y = x; // Not legal b. char x = '1'; int y = x; // Legal c. double x = 1.0; int y = x; // Not legal d. int x = 1; double y = x; // Legal e. Integer y = 3; // Legal f. int z = new Integer(7); // Legal 2. Multiple Choice For each question below, circle the best answer. i. What does the this keyword refer to? a. The class in which a method is defined. b. The implicit parameter of a method call. // This c. The method in which a Java statement is written. d. A local variable. ii. What is the main difference between data stored in a file and data stored in memory? a. Data stored in a file will remain after program execution, and after the computer is powered off. // This b. Data stored in memory will remain after program execution, and after the computer is powered off. c. Data stored in a file is much faster to access. d. There is no major difference between the two. iii. The protected access control limits access to a variable to a. The current class b. The current directory c. The current directory and the subclasses of the current class // This d. Only the subclasses of the current class 3. Evaluating Expressions and Statements For each expression write down its value. Be sure to list a constant of the appropriate type (e.g., 2 represents an int, 2.0 represents a double, and "2" represents a String). If the expression results in an error, write "ERROR". 2.5 + 2 / 5 - 7 % 3 // 3.5 "12".equals("1" + 9 % 7) // True (new Point(0,0)) == (new Point(0,0)) // False "hello".length() == "g'bye".length() // True new double[10][0] // pointer to array with 10 mositions each pointing // to an array with zero elements "rosalie".substring(2,3) // "s" The class Child extends the class Parent. Parent has the toString method that returns "parent". Child has the toString method that returns "child". If Parent a = new Parent(); Child b = new Child(); Parent c = new Child(); what is the value of a.toString() + b.toString() + c.toString() // parentchildchild 4. Reviewing Some Concepts: Short Answer Questions a) What is a method's signature? // The method name followed by the type of the formal parameters b) In Java, method names can be overloaded. What does that mean? // In a class multiple methods can have the same name as long as they // have different signatures c) What is the scope of a variable? // The text of the program where that variable is known d) What are stubs and why do we use them? // Stubs are methods with minimal implementations that are used // initially in place of the required implementation of the method // so as to have as soon as possible a program that compiles and runs. e) What is and why do we use "loop invariants"? // It is an assertion that is assumed true at each iteration // of a loop. It is used to prove that a loop does what it was // intended to do. f) What is "garbage collection"? // When instances of objects are no longr referenced, the memory // associated to them can be reclaimed and re used for other instances. 5. Assignments, Casting, and Constructors Let Moo be an interface, and let Foo and Goo be concrete classes that implement the Moo interface. For each statement below, write whether it is a legal or illegal Java statement. a) Foo x = new Foo(); legal? // yes b) Moo y = new Foo(); legal? // yes c) Moo z = x; legal? // yes d) Moo u = new Moo(); legal? // no e) Foo w = z; legal? // no f) Goo v = x; legal? // no 6. Translating to Java simple English expressions. You can assume that x and y refer to integers, s and v to strings, a to an integer array, and c to a character a. x is even // x % 2 == 0 b. the length of s is 5 // s.length() == 5 c. s and v are equal // s.equals(v) d. the third element of a is 5 // a[2] == 5 e. a is empty (i.e. it has no elements) // a.length == 0 f. c is a digit (i.e. '0', or '1', .. or '9') // c >= '0' && c <= '9' 7. Classes and Objects: public class Pair { private int first; private int second; public Pair() {} public Pair(int x, int y) { first = x; second = y; } public Pair(Pair a) { first = a.first; second = a.second; } public int getFirst() { return first; } public int getSecond() { return second; } public boolean equals(Pair a) { // returns true iff a and the hidden parameter have the same //content} } The class Pair defines an object that contains a pair of integers. For the questions below, assume that the variables p1 and p2 are of type Pair. a) Write an expression that is true if the pairs referenced by p1 and p2 share the same storage (that is, they point to the same address in memory). // p1 == p2 b) Implement the equals method public boolean equals(Pair a) { return first == a.first && second == a.second; } 8. File Processing Write a method called translateToFrench that reads in an English text file and translates certain words to French. Assume that the following variable is in scope for your method: String [ ][ ] eng2French = { {"yes", "oui"}, {"hello", "bonjour"}, {"cheese", "fromage"}, {"haha", "honhonhon"} }; Your method should read words from the text file and check to see if they are contained in the eng2French variable. If so, it should translate the words to the French equivalent. Otherwise, it should leave the word alone. Your method should accept two parameters, specifying the names of an input and output file. Your method should read from the input file, and write to the output file. If an input word does not appear in the eng2French variable, the method should simply print the input word to the output file. If it does appear, it should print the translated word. You must handle checked exceptions with the try .. catch .. finally mechanisms. You may wish to define helper methods, but it is not necessary to receive full credit. private static String [ ][ ] eng2French = { {"yes", "oui"}, {"hello", "bonjour"}, {"cheese","fromage"}, {"haha", "honhonhon"} }; /** Searches for s the array eng2French and returns s if not there, otherwise it returns corresponding french word */ public static String translate(String s) { for (String[] a: eng2French) if (s.equals(a[0])) return a[1]; return s; } public static void translate2French(String filenamein, String filenameout) { Scanner filein = null; PrintWriter fileout = null; try { filein = new Scanner(new File(filenamein)); fileout = new PrintWriter(new File(filenameout)); while (filein.hasNextLine()) { String line = filein.nextLine(); Scanner scan = new Scanner(line); while (scan.hasNext()) { String word = scan.next(); fileout.print(translate(word) + " "); } fileout.println(); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (filein != null) filein.close(); if (fileout != null) fileout.close(); } } 9. Fractions Implement the method double avg(Fraction[] a) that returns the average value of the fractions in a double avg(Fraction[] a) { Fraction sum = new Fraction(); for (Fraction f: a) sum = sum.add(f); return sum.multiply(new Fraction(1, a.length)); } 10. String Matching Implement a static method distinctParts that returns the number of non- overlapping occurrences of String a in String b, where a and b are the arguments of the method. For example, if b = "babababa" and a = "aba", the result of distincParts(a, b); should be 2. public static int distinctParts(String a, String b) { } public static int distinctParts(String a, String b) { int count = 0; int k = 0; while ( (k = a.indexOf(b, k)) >= 0 ) { count++; k += b.length(); } return count; } If your code contains a loop, specify its loop invariant. count is the number of occurrences of b in a.substring(0, k) 11. Exceptions Implement the function public static int readInt() that prompts the user to enter an integer and returns it to the method caller. Use an exception handler to deal with the possibility that the user may by mistake enter something that is not an integer. Do not return to the caller until the user has actually entered an integer. public static int readInt() { Scanner scan = new Scanner(System.in); System.out.print("Enter an integer: "); while (scan.hasNext()) { if (scan.hasNextInt()) { int n = scan.nextInt(); return n; } scan.next(); System.out.println("Sorry, that is not an integer"); System.out.print("Enter an integer: "); } return Integer.MIN_VALUE; } 12. Path Class Below is a definition of a Point class: class Point { public double x = 0; public double y = 0; public Point(double x, double y) (this.x = x; this.y = y; } public double distance(Point other) { double xDist = (other.x - x) * (other.x - x); double yDist = (other.y - y) * (other.y - y); return Math.sqrt(xDist + yDist); } } A Path is a sequence of Point objects. The abstract class below describes the major operations required of a Path: public abstract class Path { protected ArrayList elements; // Constructor that takes an argument indicating the number of //points. public Path(int size) { elements = new ArrayList(size); } // A method to set the ith point along the path to p public abstract void setPoint(int i, Point p); // A method to insert the point p in the ith position public abstract void insertPoint(int i, Point p); // pathLength determines the length of the path by adding up the // distances between consecutive pairs of points on the path public abstract double pathLength(); } Write a class called ArrayPath that implements the Path interface using an arraylist of length size initialed as follows: Each point in the path will have x and y coordinates between 0.0 and 5.0, chosen randomly. Use the Math.random() method, which returns a double value between 0.0 and 1.0. public class ArrayPath extends Foo { public ArrayPath(int size) { super(size); for (Point p: elements) p = new Point(5.0*Math.random(), 5.0*Math.random()); } // A method to set the ith point along the path to p public void setPoint(int i, Point p) { elements.set(i, p); } // A method to insert the point p in the ith position public void insertPoint(int i, Point p) { elements.add(i,p); } // pathLength determines the length of the path by adding up the // distances between consecutive pairs of points on the path public double pathLength() { double sum = 0.0; for (int k = 0; k < elements.size()-1; k++) { Point from = elements.get(k); Point to = elements.get(k+1); sum += from.distance(to); } return sum; } } 13. Algorithms a) Here is an integer array {7,3,8,1,2} Show its content after each pass of insertion sort 7,3,8,1,2 3,7,8,1,2 1,3,7,8,2 1,2,3,7,8 b) Given the integer array {2,3,5,8,12,15,16} list the position examined during the binary search for the value 6. 3 1 2 c) Show the steps of the euclidean algorithm to compute the greatest common divisor of 327 and 63 a b remainder 327 63 12 63 12 3 12 3 0