Show solutions

145 Practice Final Test

  1. Write a program which prints out the numbers from 0 to 99.
    public class Count {
      public static void main (String [] args){
        for (int i=0; i<100;i++){
          System.out.println(i);
        }
      }
    }
    
  2. The Fibonacci series consists of a series of numbers where the next number is calculated by adding the previous two. The first two numbers in the series are 1. That is, the series starts out:
    1
    1
    2
    3
    5
    8
    13
    Write a function which takes as input an integer x an returns an array of integers filled with fibonacci numbers in order.
    public class Fibonacci {
    
      public static int[] getSeries(int x){
        int[] result = new int[x];
        result[0]= 1;
        result[1]= 1;
        for (int i=2; i < x; i++){
          result[i] = result[i-1] + result[i-2];
        }
        return result;
      }
      
      public static void main (String [] args){
        int[] fib = Fibonacci.getSeries(20);
        for (int i : fib){
          System.out.println(i);
        }
      }
    }
    
  3. Write the smallest possible Java program which still compiles and runs.
    public class Smallest{
      public static void main(String[] args){
      }
    }
    
  4. Answer the following questions: --Lookup solution in the book.
    1. What is the difference between an instance variable, an argument variable, a temporary (or local) variable, and a class variable?
    2. What is the difference between a class, an interface, an an abstract class?
    3. How do you create instantiate a Robot?
    4. What is the difference between a declaration and an instantiation? Show an example of each.
    5. What is a constructor? How many can you have in one class? Why are there no destructors in Java?
    6. What is garbage collection and why does it make your life easier?
    7. What is the difference between a primitive type and a class?
    8. Write an infinite loop.
    9. What is the difference between overloading and overriding?
    10. Can you overload toString()? why? can you override it?
    11. What is the difference between a private, protected, and public method?
    12. Does it matter (to the compiler) in what order the various variables and methods in a class are defined?
    13. What is the difference between a service, a method, and a function? - None
    14. What is Javadoc? Give an example.
    15. What is the UML symbol for inheritance? for implementing an interface? for having a reference to instances from another class? for a private method? for a public method?
    16. What is whitespace?
    17. What is the syntax for commenting in Java? Show examples of all ways of commenting.
    18. What do the following Java keywords do?
      1. extends
      2. implements
      3. break
      4. continue
      5. try
      6. instanceof
      7. static
      8. final
      9. %
      10. +
      11. !
      12. =
      13. ==
      14. &&
    19. What is stepwise refinement?
    20. Write a while loop that iterates 10 times, then write an equivalent for loop.
    21. A typical function declaration in Java is public int foo(String x). What is (explain what each one's role is using proper teminology):
      1. public
      2. int
      3. foo
      4. String
      5. x
    22. Let m be an instance of some class.
      1. What does m.x do?
      2. When will m.x fail?
      3. What does m.f(3) do?
      4. When whill m.f(3) fail?
      5. Can you extend m?
      6. Can you pass m as an argument to some other function? That is, do x.f(m)?
      7. Can you do m++?
      8. Can you do System.out.println(m)?
      9. Can you do int x = m;?
      10. Can you do String x = m;?
      11. Can you do (m = n)?
      12. Can you do (m == n)?
      13. Can you do (m < n)?
      14. Can you do if (m) ...?
      15. Can you do (String) m?
      16. Under which situations will (Robot) m work?
    23. How do you declare a constant (like the speed of light)?
    24. How do you convert a double to an int?
    25. How do you concatenate two Strings into one?
    26. What does it mean to say that the class String is immutable?
    27. What is a token? Show an example file and identify the tokens.
    28. What is polymorphism? Show a polymorphic function.
  5. The following problem comes from the TopCoder High School competition

    Problem Statement

        

    A new device is being designed for all the post offices in Byteland. This device will make mail classification and delivery more efficient by automatically recognizing the addresses written on envelopes. You are responsible for the software component that determines if two addresses match.

    Given two Strings address1 and address2, determine if they match using the following procedure. First, remove all spaces from both addresses. Then, perform a case-insensitive string comparison. If the two strings are equal, return -1. Otherwise, return the leftmost 0-based position at which they differ (the index after removing the spaces).

     

    Definition

        
    Class:PostOffice
    Method:matchAddress
    Parameters:String, String
    Returns:int
    Method signature:int matchAddress(String address1, String address2)
    (be sure your method is public)
        
     

    Constraints

    -address1 and address2 will each contain between 0 and 50 characters, inclusive.
    -address1 and address2 will contain only letters ('a'-'z', 'A'-'Z'), digits ('0'-'9'), and spaces.
     

    Examples

    0)
        
    "145 West 44th Street"
    "145 west 44 th street"
    Returns: -1
    After all spaces are removed, the two addresses become:
    "145West44thStreet"
    "145west44thstreet"
    These two strings are equal if you do a case-insensitive comparison, so -1 is returned.
    1)
        
    " wall street "
    "WallStreet"
    Returns: -1
    Again, these two addresses are equal after all spaces are removed and a case-insensitive comparison is done between the resulting strings.
    2)
        
    " Wall Street"
    "  Waal Street"
    Returns: 2
    First, remove the spaces:
    "WallStreet"
    "WaalStreet"
    These strings differ at position 2 (0-based). The first string has an 'l' at that position while the second string has an 'a'.
    3)
        
    "                                                 A"
    "a                                                 "
    Returns: -1
    4)
        
    "Wall"
    "WallStreet"
    Returns: 4
    These strings differ at position 4 (0-based). The first string does not have a character at that position while the second string has a 'S'.

    This problem statement is the exclusive and proprietary property of TopCoder, Inc. (c)2006, TopCoder, Inc. All rights reserved.

    //Solution by tomekkulczynski
    //translated to Java by JM Vidal.
    public class PostOffice {
     
      public static int matchAddress(String a, String b)
      {
        String a2 = "";
        String b2 = "";
        int i;
        for(i=0; i<a.length(); i++){
          if(a.charAt(i) != ' ')
            a2 += a.substring(i,i+1).toLowerCase();
        }
        for(i=0; i<b.length(); i++){
          if(b.charAt(i) != ' ')
            b2 += b.substring(i,i+1).toLowerCase();
        }
        if(a2.equals(b2)) return -1;
    
        //The commented-out line is tomekkulczynski's solution, but it is
        //broken.  It fails (IndexOutOfBounds) when comparing, say "Wall"
        //and "WallStreet" It is interesting to study why his solution
        //works (in C++) most of the time.
    
        //for(i=0; a2.charAt(i)==b2.charAt(i); i++);
        for(i=0; i< a2.length() && i < b2.length() && a2.charAt(i)==b2.charAt(i); i++);
        return i;
      }
      
      public static void main (String [] args){
        System.out.println(PostOffice.matchAddress("145 West 44th Street",
                                                   "145 west 44 th street"));
        System.out.println(PostOffice.matchAddress(" wall street ",
                                                   "WallStreet"));
        System.out.println(PostOffice.matchAddress(" Wall Street",
                                                   "  Waal Street"));
        System.out.println(PostOffice.matchAddress("                                                 A",
                                                   "a                                                 "));
        System.out.println(PostOffice.matchAddress("Wall", "WallStreet"));
      }
    }
    
  6. This one came from the TopCoder SRM competition. It is hard. First try to just determine if a given string is a fence (in its entirety) or not:

    Problem Statement

        A sequence of characters is called a fence if it consists of alternating '|' and '-' characters, like "|-|-|-|" or "-|-|" (quotes for clarity only). Notice that "|-||-|" or "--" are not fences, because each contains two equal characters adjacent to each other. Given a string s, find the longest consecutive substring of it that is a fence, and return its length.
     

    Definition

        
    Class:FunnyFence
    Method:getLength
    Parameters:String
    Returns:int
    Method signature:int getLength(String s)
    (be sure your method is public)
        
     

    Constraints

    -s will contain between 1 and 50 characters, inclusive.
    -Each character of s will be either '|' or '-'.
     

    Examples

    0)
        
    "|-|-|"
    Returns: 5
    The entire string is a fence.
    1)
        
    "-|-|-|-"
    Returns: 7
    Still a fence.
    2)
        
    "||||||"
    Returns: 1
    A fence can be just 1 character long, so every 1 character substring here is a fence.
    3)
        
    "|-||-|-"
    Returns: 4
    The last 4 characters form the longest consecutive substring that is a fence.
    4)
        
    "|-|---|-|---|-|"
    Returns: 5
    "-|-|-" right in the middle gives the longest fence.
    5)
        
    "|||-||--|--|---|-||-|-|-|--||---||-||-||-|--||"
    Returns: 8

    This problem statement is the exclusive and proprietary property of TopCoder, Inc. (c)2006, TopCoder, Inc. All rights reserved.

    /** From topcoder.com:
    
    FunnyFence is a simple problem, which asks you to find the largest
    fence in a string. Coming up with an algorithm to solve the problem
    isn't too difficult, but while implementing it you must pay careful
    attention to avoid fencepost errors.
    
    Typically, to avoid bugs creeping into your implementation, you should
    code up the simplest algorithm you can think of that won't timeout. If
    you are afraid that the simple solution will timeout, you can then
    make small optimizations until your algorithm is fast enough.
    
    For example, the simple algorithm for FunnyFence is to go through
    every substring and test it to see if it is a fence. To do each test
    you can loop through each character in the substring and make sure
    that it is different from the one right before it. This will end up
    looking something like:
    
        smallest=infinity;
        for(start=0 ; start < s.length ; start++)
            for(end=start+1 ; end<= s.length ; end++)
                sub = s.subString(start,end)
                if( isFence(sub) )
                  smallest = max( smallest, sub.length)
    
    isFence() returns true if the substring is indeed a fence. Since there
    are O(n2) substrings we will call isFence() a total of O(n2)
    times. Each call to isFence() could take up to O(n) time, since it
    examines each character in the substring, so overall this algorithm is
    O(n3). Since n is at most 50, we have plenty of time to do the O(n3)
    operations.
    
    Code translated to Java by jmvidal*/
    
    public class FunnyFence {
    
      //by jmvidal
      public static boolean isFence(String s){
        if (s.length() == 1) return true;
        for (int i=1; i < s.length(); i++){
          if (s.charAt(i) == s.charAt(i-1))
            return false;
          if (s.charAt(i) != '-' && s.charAt(i) != '|')
            return false;
        }
        return true;
      }
    
      /** Top coder solution */
      public static int getLength(String s){
        int smallest = -99999999;
        for(int start=0; start < s.length(); start++){
          for(int end = start+1; end <= s.length(); end++) {
            String sub = s.substring(start,end);
            if( FunnyFence.isFence(sub) )
              smallest = Math.max(smallest, sub.length());
          }
        }
        return smallest;
      }
    
      /** Their solution (above) seems extremely inefficient and overly
         complicated. Below is my solution to the problem which is much
         faster and seems to solve the problem.
    
         This solution assumes that s contains only the - and |
         characters, as their examples seem to imply.*/
      public static int myGetLength(String s){
        if (s.length() == 1) return 1;
        int maxLength = 1;
        int currentLength = 1;
        for (int i = 1; i<s.length(); i++){
          if (s.charAt(i) != s.charAt(i-1))
            currentLength++;
          else
            currentLength = 1;
          if (currentLength > maxLength)
            maxLength = currentLength;
        }
        return maxLength;
      }
      
      public static void main (String [] args){
        System.out.println(FunnyFence.getLength("|-|-|"));
        System.out.println(FunnyFence.getLength("-|-|-|-"));
        System.out.println(FunnyFence.getLength("||||||"));
        System.out.println(FunnyFence.getLength("|-||-|-"));
        System.out.println(FunnyFence.getLength("|-|---|-|---|-|"));
        System.out.println(FunnyFence.getLength("|||-||--|--|---|-||-|-|-|--||---||-||-||-|--||"));
        System.out.println("---");
        System.out.println(FunnyFence.myGetLength("|-|-|"));
        System.out.println(FunnyFence.myGetLength("-|-|-|-"));
        System.out.println(FunnyFence.myGetLength("||||||"));
        System.out.println(FunnyFence.myGetLength("|-||-|-"));
        System.out.println(FunnyFence.myGetLength("|-|---|-|---|-|"));
        System.out.println(FunnyFence.myGetLength("|||-||--|--|---|-||-|-|-|--||---||-||-||-|--||"));
      }
    }
    
  7. And, yet another one from our friends at TopCoder. This one might look more complicated than it really is. Note that you can convert an integer to a string with Integer.toString(int x).

    Problem Statement

        The town John lives in consists of a large number of streets numbered 1 to streets, inclusive. He insists on parking his car only on street numbers that are palindromic (i.e., they read the same forward and backward). He is currently located at street number now. Return the closest street where he can park his car. If there are multiple solutions, return the smallest among them.
     

    Definition

        
    Class:CarParking
    Method:closestShed
    Parameters:int, int
    Returns:int
    Method signature:int closestShed(int now, int streets)
    (be sure your method is public)
        
     

    Notes

    -Leading zeroes shouldn't be considered. So you can't interpret "10" as "010" and consider it palindromic.
     

    Constraints

    -streets will be between 1 and 2147483647, inclusive.
    -now will be between 1 and streets, inclusive.
     

    Examples

    0)
        
    19
    22
    Returns: 22
    22 is the closest palindromic street.
    1)
        
    19
    21
    Returns: 11
    Now there is one less street. So the next nearby palindrome is 11.
    2)
        
    1234567
    12345678
    Returns: 1234321
    3)
        
    9999
    99999999
    Returns: 9999

    This problem statement is the exclusive and proprietary property of TopCoder, Inc. (c)2006, TopCoder, Inc. All rights reserved.

    /** Solution by jmvidal */
    public class CarParking{
    
      public static boolean isPalindrome(int i){
        String s = Integer.toString(i);
        for (int j=0; j< s.length() / 2; j++){
          if (s.charAt(j) != s.charAt(s.length() - j - 1))
            return false;
        }
        return true;
      }
    
      /** Solve it by simply searching in the order: now, now-1, now+1,
          now-2, now+2...
          But, make sure to stop if now+i > streets */
      public static int closestShed(int now, int streets){
        for (int i=0; ; i++){ //yest, its an infinite loop, theoretically
          if ((now - i) >=0 && CarParking.isPalindrome(now - i))
            return now - i;
          if ((now + i) <= streets && CarParking.isPalindrome(now + i))
            return now + i;
        }
      }
    
      public static void main (String[] args){
        System.out.println(CarParking.closestShed(19,22));
        System.out.println(CarParking.closestShed(19,21));
        System.out.println(CarParking.closestShed(9999,99999999));
        System.out.println(CarParking.closestShed(9991,99999999));
        System.out.println(CarParking.closestShed(123456,99999999));
      }
          
    
    
    }
    
  8. Hey kids, lets do some computational Biology! As you know, the DNA that guides the development of all living things (except for intelligent robots, of course) is just a very long string where each charcter is one of the four letters: A, G, C, T. Implement a class called DNAString which stores as its member variable one such string, can turn itself into a string, and implements a function called positionOf which takes as input a string and returns the starting position of that substring in the DNA string. That is, the following code:
    public class DNAString {
    
    /** The gene. I choose to represent it as an array since its is then more natural to access random positions and I can change it in place without copying the whole thing (Remember: Strings are immutable). */ protected char[] strand; public DNAString(int length){ strand= new char[length]; } public void set(String g){ for (int i=0; i < g.length(); i++){ strand[i] = g.charAt(i); } } public String toString(){ String result = ""; for (char g : strand){ result += g; } return result; } /** @param s the substring we are looking for. Returns the starting position of s in this DNAString or -1 if s is not found anywhere in this strand */ public int positionOf(String s){ for (int i=0; i < strand.length - s.length(); i++){ boolean match = true; for (int j =0; j< s.length(); j++){ if (strand[i+j] != s.charAt(j)) { match = false; break; } } if (match) { return i; } } return -1; }
    public static void main (String [] args){ String joeDNA = "AGCTGAAAAAGTCCCCACGATCATCAAGACTTGACTACGCTAGC"; DNAString joe = new DNAString(joeDNA.length()); joe.set(joeDNA); System.out.println(joe); System.out.println("AAGT is first found at position " + joe.positionOf("AAGT")); } }
    should produce the following output:
    AGCTGAAAAAGTCCCCACGATCATCAAGACTTGACTACGCTAGC
    AAGT is first found at position 8
  9. Unfortunately, Biologists tell us that people sometimes have small differences in their DNA and that their sequencing equipment is not foolproof. Thus, there might be errors in the DNAString. Implement a new class which extends the previous DNAString and overrides the positionOf to take as input Strings that might also contain the '*' character, which is allowed to match any letter. Thus the following code:
    public class DNAString2 extends DNAString { public DNAString2(int l){ super(l); } /** @param s the substring we are looking for. The '*' character means that we don't care which letter is in that position. Returns the starting position of s in this DNAString or -1 if s is not found anywhere in this strand */ public int positionOf(String s){ for (int i=0; i < strand.length - s.length(); i++){ boolean match = true; for (int j =0; j< s.length(); j++){ if (s.charAt(j) != '*' && strand[i+j] != s.charAt(j)) { match = false; break; } } if (match) { return i; } } return -1; }
    public static void main (String [] args){ String joeDNA = "AGAACTGAAAAAGTCCCCACGATCATCAAGACTTGACTACGCTAGC"; DNAString2 joe = new DNAString2(joeDNA.length()); joe.set(joeDNA); System.out.println(joe); System.out.println("AA*T is first found at position " + joe.positionOf("AA*T")); }
    }
    produces the following output
    AGAACTGAAAAAGTCCCCACGATCATCAAGACTTGACTACGCTAGC
    AA*T is first found at position 2
  10. You are given the following code skeleton. Our eventual goal is to extend this into a program which reads and writes all recordings to a file. You will do this by answering the questions that follow.
    //Recording.java
    import java.util.Scanner;
    
    public abstract class Recording{
      /** The total time of this recording, in seconds.*/
      private double duration;
    
      /** The title */
      private String title;
    
      public Recording(String title, double duration){
        this.title = title;
        this.duration = duration;}
    
    
    /** Create me by reading a string (which can contain spaces) folloed by a double */ public Recording(Scanner in){ title = ""; while (!in.hasNextDouble()){ title += in.next() + " "; } title = title.trim(); //gets rid of the extra space at the end. duration = in.nextDouble(); } public String toString(){ return title + " " + duration; }
    }
    //AudioRecording.java
    import java.util.Scanner;
    
    public class AudioRecording extends Recording {
      /** Bit rate (Sampling rate) in kpbs */
      private double sample;
    
      /** Artist's name */
      private String artist;
      
      public AudioRecording(String title, double duration,
                            String artist, double sample){
        super(title, duration);
        this.artist = artist;
        this.sample = sample;
      }
    
    
    /** Create me by reading from a file */ public AudioRecording(Scanner in){ super(in); artist = ""; while (!in.hasNextDouble()){ artist += in.next() + " "; } artist = artist.trim(); sample = in.nextDouble(); } public String toString(){ return "audio " + super.toString() + " " + artist + " " + sample; }
    }
    //VideoRecording.java
    import java.util.Scanner;
    
    public class VideoRecording extends Recording {
      /** x resolution */
      private int xResolution;
    
      /** y resolution */
      private int yResolution;
    
      public VideoRecording(String title, double duration, int x, int y){
        super(title,duration);
        this.xResolution = x;
        this.yResolution = y;}
    
    /** Create me by reading from a file */ public VideoRecording(Scanner in){ super(in); this.xResolution = in.nextInt(); this.yResolution = in.nextInt(); in.nextLine(); } public String toString(){ return "video " + super.toString() + " " + xResolution + " " + yResolution; }
    }
    //MyTunes.java
    import java.io.*;
    import java.util.*;
    
    public class MyTunes {
    
      private Recording[] m;
    
    
    /** Create an instance of the database by reading every Recording from a file */ public MyTunes (String filename){ try { Scanner in = new Scanner(new File(filename)); m = new Recording[in.nextInt()]; in.nextLine(); int i = 0; while (in.hasNext()){ String type = in.next(); if (type.equals("audio")){ m[i] = new AudioRecording(in); } else { //it must be video m[i] = new VideoRecording(in); } i++; } } } /** Writes the whole array to a string. The first number is the number of items in the array. */ public String toString(){ String result = ""; result += m.length + "\n"; for (Recording r : m){ result += r + "\n"; } return result;} /** @param filname is the name of the file Write m to filename. */ public void writeToFile(String filename){ try { PrintWriter out = new PrintWriter(filename); out.print(this); out.close(); } catch (FileNotFoundException ex) { System.out.println(ex.getMessage()); } }
    public static void main(String[] a){ //Read it all from a file MyTunes mine = new MyTunes("recs.txt"); //Print it to screen System.out.println(mine); //Write it to a file mine.writeToFile("recs2.txt"); //recs.txt and recs2.txt should now be identical. } }
    If you can't write the function for one of these questions and you need it for a following question, don't worry. Simply write in English what the function should do and assume that it has been correctly implemented.
    1. Draw a UML class diagram for the program above.
    2. Implement toString() functions for AudioRecording, VideoRecording and Recording. These return a string with all the values for the instance variables. Make sure that the data is returned in a format that is easy to parse as you will be writting functions to read that data in the next questions.
    3. Implement toString() function for MyTunes. It should return a string with the values for all the elements in its instance variable m. It should use the functions from the previous question.
      Tip: the character '\n' represents the end-of-line.
    4. Using the toString() functions you defined above, write the code to write the m array from MyTunes into a file. That is, implement the writeToFile function that is called from the main in the code above.
    5. Write constructors for AudioRecording, VideoRecording and Recording which take as input a Scanner and read their instance variable values from it. Assume that the data is in the format (order) implemented by your toString() methods. Note that to do this you might need to make minor changes to your toString() methods.
      Tip: remember that the title and artist instance variables are strings that could have spaces in them, such as "Pink Floyd" and "Battlestar Galactica".
    6. Write the MyTunes constructor which takes as input a filename and populates his instance variable m by reading all the recodings in that file. Use the constructors from the previous question and assume the file was written using the MyTunes toString() function.
      Tip: writing the length of the array first helps you know what size the array needs to be.
A funny comic strip.