Show solutions

145 Practice Test 3

  1. Write a program that reads and properly parses a file called "people.txt" which contains the name of the person followed by his age and then his height in feet. A sample file looks like:
    Mario 34 4.5
    Donkey Kong 15 5.7
    Luigi 38 5.8
    Princess Peach Toadstoll 25 5.2
    
    Each person should be parsed into a Person class which holds data for a person. You can assume that all the names are strings (not numbers) and that all ages are integers.
    import java.io.*;
    import java.util.Scanner;
    
    public class Person {
      private String name;
      private int age;
      private double height;
    
      public Person (Scanner in){
        name = "";
        while (!in.hasNextInt()){
          name += in.next() + " ";
        }
        age = in.nextInt();
        height = in.nextDouble();
        in.nextLine();
      }
    
      public String toString(){
        return name + " " + age + " " + height;
      }
    
      public static void main (String[] args){
        String filename = "people.txt";
        try {
          Scanner in = new Scanner(new File(filename));
          while (in.hasNextLine()){
            Person p = new Person(in);
            System.out.println(p);
          }
        } catch (FileNotFoundException e){
          System.out.println("Sorry, could not find file " + e);
        }
      }
      
    }
    
  2. If you could choose between implementing a program that reads in a whish list formatted this way (A):
    Lego Mindstorms - Nintendo Wii - Tickle Me Elmo - Bratz - Theory of Games and Economic Behavior
    
    vesus this way (B)
    Lego Mindstorms
    Nintendo Wii
    Tickle Me Elmo
    Bratz
    Bratz Petz
    Theory of Games and Economic Behavior
    
    which one would you choose and why? I would choose (B) since it is easier to use a readLine() statement to read a whole line for each item in the list instead of having to look out for the "-".
  3. Write a function which reverses the contents of an array in place. That is, write reverseArray:
    public class Reverse {
    
    public static void swap(int[] a, int x, int y){ int t = a[x]; a[x] = a[y]; a[y] = t;}
    /** Reverses the order of the elements in a, regardless of the size of a. */ public static void reverseArray(int[] a){
    //the -1 is tricky for (int i=0; i<(a.length-1)/2; i++){ Reverse.swap(a,i,a.length - 1 -i);} } //Do some unit testing public static void main (String [] argv){ int[] a = new int[9]; //Should test with odd and even. for (int i=0; i < a.length; i++){ a[i] = i*i;} for (int i=0; i < a.length; i++){ System.out.print(a[i] + " ");} System.out.println(""); Reverse.reverseArray(a); for (int i=0; i < a.length; i++){ System.out.print(a[i] + " ");} System.out.println(""); }
    }
  4. Write a function which finds the maximum number in an array. That is, write the following function:
    public class FindMax {
      /** @param a an array of integers of length > 0
          Returns the maximum integer in a */
      public static int findMax(int[] a){
    
    int theMax = a[0]; for (int i =0; i < a.length; i++){ if (a[i] > theMax) { theMax = a[i];} } return theMax; } //Do some unit testing public static void main (String [] argv){ int[] a = new int[5]; a[0] = 1; a[1] = 3; a[2] = 2; a[3] = 7; a[4] = 5; System.out.println(findMax(a)); }
    }
  5. Write a function called biggerThanN which, given an array and a number n, returns an array of all the numbers in the original array that are bigger than n.
    public class BiggerThanN {
      /** @param a an array of integers of length > 0
          @param n
          Returns an array of all a[i] for which a[i] > n.*/
      public static int[] biggerThanN(int[] a, int n){
        //I don't know how many items are bigger than n so I must
        //first count them so I can then create an array of the correct
        //size
        int count = 0;
        for (int i =0; i < a.length; i++){
          if (a[i] > n) {
            count++;}
        }
        int result[] = new int[count];
        int j = 0;
        for (int i =0; i < a.length; i++){
          if (a[i] > n) {
            result[j++] = a[i];}}
        return result;
      }
    
      public static void printArray(int[] a){
        for (int i=0; i < a.length; i++){
          System.out.println(a[i]);}
      }
    
      //Do some unit testing
      public static void main (String [] argv){
        int[] a = new int[5];
        a[0] = 1; a[1] = 3; a[2] = 2; a[3] = 7; a[4] = 5;
        printArray(a);
        System.out.println("-");
        printArray(biggerThanN(a,4));
        System.out.println("-");
        printArray(biggerThanN(a,2));
      }
    }
    
  6. A one-dimensional cellular automata is an array where each position is either off (.) or on (X). At each time step the contents of each cell are updated using a simple rule such as the following: For example, if you start with
    ....X
    then next time you will have
    ...XX
    and the next two steps will be
    ..XXX
    .XX.X
    Write a problem that implements and displays this one dimensional cellular automata rule. You can assume that the first and last positions never change their state.
    public class OneDCell {
      private char[] row;
    
      public OneDCell(int length){
        row = new char[length];
        for (int i = 0; i < row.length; i++){
          row[i] = '.';}
        row[row.length-1] = 'X';
      }
    
      /** Implement Wolfram's rule 110.
       * Did you know: Stephen Wolfram believes the universe is best
       * understood using cellular automata */
      public void step(){
        char[] newRow = new char[row.length];
    
        //To Do: Generalize this to encode anyone of the 2^8 rules.
        for (int x=1; x < row.length -1; x++){
          if (row[x] == '.'){
            newRow[x] = row[x+1];
          }
          else {
            if (row[x-1] == 'X' && row[x+1] == 'X'){
              newRow[x] = '.';}
            else {
              newRow[x] = 'X';}
          }
        }
        //Set the first and last
        newRow[0] = row[0];
        newRow[row.length-1] = row[row.length-1];
        row = newRow;
      }
    
      /**The Obvious visualization */
      public String toString(){
        String result = "";
        for (int i=0; i< row.length; i++){
          result += row[i];}
        return result;}
    
      //Unit testing
      public static void main(String[] argc){
        OneDCell ca = new OneDCell(80);
    
        //Behold! complexity arises out of simplicity!
        while (true) {
          System.out.println(ca);
          ca.step();}
      }
    }
    
  7. A two-dimensional cellular automata implements the same idea but in a two-dimensional array. The most famous one is Conway's game of life which uses the following rules (from Wikipedia):
    1. Any live cell with fewer than two live neighbours dies, as if by loneliness.
    2. Any live cell with more than three live neighbours dies, as if by overcrowding.
    3. Any live cell with two or three live neighbours lives, unchanged, to the next generation.
    4. Any dead cell with exactly three live neighbours comes to life.
    Where the neighbors of a cell are those which immediately surround it. Thus, if you start with
    .......
    .......
    .......
    ..XXX..
    .......
    .......
    then the next step is
    .......
    .......
    ...X...
    ...X...
    ...X...
    .......
    Write a class which implements and displays Conway's game of life. This time, try to make the cells on the edge (border) neighbors of those at the other side, that is, make the space wrap around.
    public class TwoDCell {
      private int[][] board;
    
      /**Creates a square board */
      public TwoDCell(int length){
        board = new int[length][length];
        for (int i = 0; i < board.length; i++)
          for (int j=0; j < board[i].length; j++)
            board[i][j] = 0;
      }
    
      /** Ugly hack, just for testing. Its a flipper. */
      public void setup(){
        board[4][3] = 1;
        board[4][4] = 1;
        board[4][5] = 1;}
    
      /** A true modulo function for the board. Negative numbers get
         wrapped around, as well as numbers bigger than the size of the
         board. Only works if n >= -board.length.*/
      private int mod(int n){
        if (n < 0) return board.length + n;
        return n % board.length;
      }
    
      /** Return the number of neighbors, assumes that x,y are not on the
         border of the board. This works out because I set 0 to be a dead
         cell and 1 to be a live cell...sneaky me.*/
      public int getNumNeighbors(int x, int y){
        return //picture this
          board[mod(x-1)][mod(y-1)] + board[x][mod(y-1)] + board[mod(x+1)][mod(y-1)] + 
          board[mod(x-1)][y]                             + board[mod(x+1)][y] +
          board[mod(x-1)][mod(y+1)] + board[x][mod(y+1)] + board[mod(x+1)][mod(y+1)];
      }
      
      /** Take a step in Conway's Game of Life */
      public void step(){
        int[][] newBoard = new int[board.length][board.length];
    
        //Apply the rule of Life
        for (int i = 0; i < board.length; i++)
          for (int j=0; j < board[i].length; j++){
            int neighbors = getNumNeighbors(i,j);
            if (board[i][j] == 1) {
              if (neighbors < 2) {
                newBoard[i][j] = 0;}
              else if (neighbors < 4) {
                newBoard[i][j] = 1;}
              else { //5 or more 
                newBoard[i][j] = 0;}}
            else {//dead cell
              if (neighbors == 3) {
                newBoard[i][j] = 1;}
              else 
                newBoard[i][j] = 0;}};
    
        board = newBoard;
      }
    
      /**The Obvious visualization */
      public String toString(){
        String result = "";
        for (int i=0; i< board.length; i++){
          for (int j=1; j < board.length; j++){
            if (board[i][j] == 0) 
              result += '.';
            else
              result += 'X';}
          result += '\n';}
        return result;}
    
      //Unit testing
      public static void main(String[] argc){
        TwoDCell life = new TwoDCell(8);
        life.setup();
        System.out.println(life);
        life.step();
        System.out.println(life);
        life.step();
        System.out.println(life);
      }
      //from wikipedia:
    
      //Conway was interested in a problem presented in the 1940s by
      //renowned mathematician John von Neumann, who tried to find a
      //hypothetical machine that could build copies of itself and
      //succeeded when he found a mathematical model for such a machine
      //with very complicated rules on a Cartesian grid. Conway tried to
      //simplify von Neumann's ideas and eventually succeeded. By
      //coupling his previous success with Leech's problem in group
      //theory with his interest in von Neumann's ideas concerning
      //self-replicating machines, Conway devised the Game of Life.
    
      //It made its first public appearance in the October 1970 issue of
      //Scientific American, in Martin Gardner's "Mathematical Games"
      //column. From a theoretical point of view, it is interesting
      //because it has the power of a universal Turing machine: that is,
      //anything that can be computed algorithmically can be computed
      //within Conway's Game of Life. Gardner wrote:
    
      //    "The game made Conway instantly famous, but it also opened up
      //    a whole new field of mathematical research, the field of
      //    cellular automata (...) Because of Life's analogies with the
      //    rise, fall and alterations of a society of living organisms,
      //    it belongs to a growing class of what are called "simulation
      //    games" - games that resemble real-life processes."
    }
    
  8. You are asked to develop a program for organizing people's contacts on their cell phone. It is to be a J2ME application that keeps track of the user's contacts. A contact can be either a person or an establishment (such as a store, library, bar, etc.). The people should have the usual information associated with them: name, picture, various telephone numbers, email addresses, IM handles, etc. The establishements have similar data but also include location. Draw UML class diagram for your design for this application.
    I won't go into details but you should really know this by now. The main classes are going to be People and Establishment with the appropiate member variables. You should also realize that both of these classes have a lot of functionality in common and, thus, should both extend some other abstract class called, say Entry. You will also need a main Contacts class which keeps an array of Entrys and has they appropiate functions.
  9. Which ones of the following are a proper metaphor for polymorphism as we define it object-oriented programming:
    1. The way a ship commander yells "Battle stations" and each soldier does what she needs to do.- Yes.
    2. The way a coach yells "Play number AB-37" and every player knows what play he is talking about.- Not really. It just says that all players know the play. If I had said that every player knows which part to play in the play then that would be polymorphism.
    3. The way all reality shows are based on the premise of putting people in embarrassing situations. - This seems more like a metaphor for inheritance to me.
    4. The way the + sign is use in Java (and in math) to add integers, reals, doubles, concatenate strings, merge sets (in math), etc. -Yes, indeed. In fact, in C++ you can define your own polymorphic operators. So, you can make the + sign add, say, 3D vectors for a graphics application, or imaginary numbers for your Mandelbrot set toy program.
    5. The way every student knows how to answer this question. - Well, aside from the fact that most of you do not know the answer to this question, there is also the problem that even if you did then you would all know the same answer. Thus, no polymorphism.
    6. The way that blue supervillian changes shapes in the X-men movie.- I don't think so. I mean, she does change shapes but it is still just her.It is more like she is getting typecasted into different classes.
  10. What does the following program print out:
    public class A {
      public A(){};
    
      public String toString(){
        return "A";}
    }
    
    public class B extends A{
      public B(){super ();};
    
      public String toString(){
        return "B";}
    }
    
    public class C extends B{
      public C(){super ();};
    
      public String toString(){
        return "C";}
      
      public static void main (String[] a){
        A v1 = new C();
        System.out.println(v1);
        A v2 = new B();
        System.out.println(v2);
        A v3 = new A();
        System.out.println(v3);
        System.out.println((B)v3); 
        B v4 = new C();
        System.out.println(v4);
        System.out.println((B)v4);
        System.out.println((A)v4);
    
        System.out.println("---");
        if (v4 instanceof A) {
          System.out.println("A");}
        else {
          System.out.println("not A");}
        if (v4 instanceof B) {
          System.out.println("B");}
        else {
          System.out.println("not B");}
        if (v4 instanceof C) {
          System.out.println("C");}
        else {
          System.out.println("not C");}
    
        System.out.println("---");
    
        if (v2 instanceof A) {
          System.out.println("A");}
        else {
          System.out.println("not A");}
        if (v2 instanceof B) {
          System.out.println("B");}
        else {
          System.out.println("not B");}
        if (v2 instanceof C) {
          System.out.println("C");}
        else {
          System.out.println("not C");}
    
      }
    }
    
    If any line throws out an exception just note that it does and proceed to the next line as if it had not happened.
    C
    B
    A
    Exception is raised. Cannot typecast v3 to type B.
    C
    C
    C
    ---
    A
    B
    C
    ---
    A
    B
    not C
  11. You are implementing a media library application, like iTunes and Media Library. Thus, you need to store information about songs, audio podcasts, video podcasts, and photos. Some of these types share certain data attributes such as: title, duration, and author, as well as certain functional attributes such as play, stop, forward, backward. The songs have album name, genre, and track number. The podcasts have a website address. The photos have a resolution. Use your imagination to fill in the rest of the needed functionality. Write the classes and interfaces you will need (no need to fill in the body of your functions).
    /** Everything that can be played should implement this interface */
    public interface Media {
      /** Plays this piece of media */
      public void play();
    
      /** Stops playing */
      public void stop();
    
      /** Go faster */
      public void forward();
    
      /** Go back */
      public void backward();
    
      /** Returns the percentage of the item we have played. */
      public double getPosition();
    
    }
    
    /** A media record refers to a piece of media. Here we collect the
        common attributes that a media item needs. */
        
    public abstract class MediaRecord {
      private String title;
    
      /** Duration of the piece, in seconds. */
      private double duration;
    
      /** Name of the author. */
      private String author;
    
      /** Pretty print it. */
      public String toString () {
        //some code here
      }
    
      /** Save it to disk */
      public void store(File f) {
        //some code here
      }
    
      /**Draw it on the GUI */
      public void display();
    }
    
    public class Song extends MediaRecord implements Media {
      private String album;
    
      private String name;
    
      private String genre;
    
      private int track;
    
      private String lyrics;
    
      public Song(String name){
        //code here
      }
    }
    
    /** An abstract class for all podcasts */
    public class abstract Podcast extends MediaRecord implements Media{
    
      /** RSS feed for this podcast */
      private String url;
    
      /** Title of the show (NOT of the episode) */
      private String showTitle;
    
      /** Title of this episode */
      private String title;
    
      /** Summary of this episode */
      private String description;
    }
    
    public class AudioPodcast extends Podcast {
    
    }
    
    public class VideoPodcast extends Podcast {
    
    }
    
    /** Note that a photo does not implement Media since it cannot be played */
    public class Photo extends MediaRecord {
    
      private int xSize;
      private int ySize;
    
    }
    
  12. Show an example of a factory method. - Listing 12-11 from the textbook. You need to understand what it does.
A funny comic strip.
Jose M Vidal
Last modified: Tue Nov 28 16:15:26 EST 2006