CS111 Final Exam Review Problems

These review problems are the examples which will be covered in the CS111 final exam review session on Monday, December 13, 1999 from 2-5pm led by Elaine. This review only covers material since the second exam. It does not cover all the material since the second exam and it does not cover any material before the second exam. Please refer to other sources for practice on that material. The review (and hence, these problems) cover three broad categories: Answers to these problems.
Note: Typo corrections were last made to these problems Monday noon.


GUI components, layout and behavior

GUI 1. Exploring LayoutManager differences

Let's assume we have the following methods available to us:
public Panel makeLabelPanel (String text) {
  Panel p = new Panel();
  p.add(new Label(text));
  return p;
}

public Panel makeButtonPanel (String text) {
  Panel p = new Panel();
  p.add(new Button(text));
  return p;
}

public Panel makeTextFieldPanel (String text, int cols) {
  Panel p = new Panel();
  p.add(new TextField(text, cols));
  return p;
}

public Panel makeSpacerPanel () {
  Panel p = new Panel();
  p.setBackground(Color.black);
  return p;
}
Draw the following applet layouts:
Labels in Different Layouts
public void init () {
  // Label Layout 1
  this.add(new Label("one"));
  this.add(new Label("twotwo"));
  this.add(new Label("Three's Company"));
  this.add(new Label("four more!"));
  this.add(new Label("five"));
}
public void init () {
  // Label Layout 2
  this.setLayout(new GridLayout(5,1));
  this.add(new Label("one"));
  this.add(new Label("twotwo", Label.CENTER));
  this.add(new Label("Three's Company", Label.LEFT));
  this.add(new Label("four more!", Label.RIGHT));
  this.add(makeLabelPanel("five"));
}
public void init () {
  // Label Layout 3
  this.setLayout(new GridLayout(1,3));
  this.add(new Label("one"));
  this.add(makeSpacerPanel());
  this.add(new Label("twotwo"));
}
public void init () {
  // Label Layout 4
  this.setLayout(new GridLayout(5,1));
  this.add(new Label("one"));
  this.add(new Label("twotwo"));
  this.add(new Label("Three's Company"));
  this.add(new Label("four more!"));
  this.add(new Label("five"));
}
public void init () {
  // Label Layout 5
  this.setLayout(new GridLayout(1,3));
  this.add(makeLabelPanel("one"));
  this.add(makeSpacerPanel());
  this.add(makeLabelPanel("twotwo"));
}
public void init () {
  // Label Layout 6
  this.setLayout(new GridLayout(5,1));
  this.add(makeLabelPanel("one"));
  this.add(makeSpacerPanel());
  this.add(makeLabelPanel("twotwo"));
  this.add(makeLabelPanel("Three's Company"));
}
public void init () {
  // Label Layout 7
  this.setLayout(new BorderLayout());
  this.add("North", new Label("North"));
  this.add("South", new Label("South"));
  this.add("East", new Label("East"));
  this.add("West", new Label("West"));
  this.add("Center", new Label("Center"));
}
public void init () {
  // Label Layout 8
  this.setLayout(new BorderLayout());
  this.add("North", makeLabelPanel("North"));
  this.add("South", makeLabelPanel("South"));
  this.add("East", makeLabelPanel("East"));
  this.add("West", makeLabelPanel("West"));
  this.add("Center", makeLabelPanel("Center"));
}

Buttons in Different Layouts
public void init () {
  // Button Layout 1
  this.add(new Button("one"));
  this.add(new Button("twotwo"));
  this.add(new Button("Three's Company"));
  this.add(new Button("four more!"));
  this.add(new Button("five"));
}
 
public void init () {
  // Button Layout 2
  this.setLayout(new GridLayout(1,3));
  this.add(new Button("one"));
  this.add(makeSpacerPanel());
  this.add(makeButtonPanel("twotwo"));
}
public void init () {
  // Button Layout 3
  this.setLayout(new GridLayout(5,1));
  this.add(new Button("one"));
  this.add(new Button("twotwo"));
  this.add(makeSpacerPanel());
  this.add(makeButtonPanel("Three's Company"));
  this.add(makeButtonPanel("four more!"));
}
public void init () {
  // Button Layout 4
  this.setLayout(new BorderLayout());
  this.add("North", new Button("North"));
  this.add("South", new Button("South"));
  this.add("East", new Button("East"));
  this.add("West", new Button("West"));
  this.add("Center", new Button("Center"));
}
public void init () {
  // Button Layout 5
  this.setLayout(new BorderLayout());
  this.add("North", makeButtonPanel("North"));
  this.add("South", makeButtonPanel("South"));
  this.add("East", makeButtonPanel("East"));
  this.add("West", makeButtonPanel("West"));
  this.add("Center", makeButtonPanel("Center"));
}

TextFields in Different Layouts
public void init () {
  // TextField Layout 1
  this.add(new TextField("one",6));
  this.add(new TextField("twotwo",4));
  this.add(new TextField("Three's Company"));
  this.add(new TextField("four more!",8));
  this.add(new TextField("five",20));
}
 
public void init () {
  // TextField Layout 2
  this.setLayout(new GridLayout(1,3));
  this.add(new TextField("one",6));
  this.add(new TextField("twotwo",4));
  this.add(new TextField("Three's Company"));
}
public void init () {
  // TextField Layout 3
  this.setLayout(new GridLayout(5,1));
  this.add(new TextField("one",6));
  this.add(new TextField("twotwo",4));
  this.add(new TextField("Three's Company"));
  this.add(makeTextFieldPanel("four more!",8));
  this.add(makeTextFieldPanel("five",20));
}
public void init () {
  // TextField Layout 4
  this.setLayout(new BorderLayout());
  this.add("North", new TextField("North",5));
  this.add("South", new TextField("South",10));
  this.add("East", new TextField("East",4));
  this.add("West", new TextField("West",8));
  this.add("Center", new TextField("Center",10));
}
public void init () {
  // TextField Layout 5
  this.setLayout(new BorderLayout());
  this.add("North", makeTextFieldPanel("North",5));
  this.add("South", makeTextFieldPanel("South",10));
  this.add("East", makeTextFieldPanel("East",4));
  this.add("West", makeTextFieldPanel("West",8));
  this.add("Center", makeTextFieldPanel("Center",10));
}

GUI 2. Understanding GUI code and behavior

Here is the code for an applet:
import java.awt.*; // use graphics
import java.applet.*; // make applet

public class GUIMystery extends Applet {

  int rows = 4;
  int cols = 3;
  int currentRow = 1;
  int currentCol = 1;
  int maxVisits = 3;
		
  TextField rowField = new TextField(3);
  TextField colField = new TextField(3);
  TextField scoreField = new TextField("0",3);
  TextField currentTextField;
  TextField [] textfields = new TextField[rows*cols];
	
  public void init () {
    this.setLayout(new BorderLayout());
    this.add("North", makeStatusPanel());
    this.add("South", makeControlPanel());
    this.add("Center", makeTextFieldsPanel());
  }
	
  public Panel makeStatusPanel () {
    Panel p = new Panel();
    p.setLayout(new GridLayout(3,1));
    p.add(new Label("Visit as many places till you are stopped!"));
    p.add(makePositionPanel());
    p.add(makeScorePanel());	
    return p;
  }
	
  public Panel makePositionPanel () {
    Panel p = new Panel();
    p.add(new Label("POSITION"));
    p.add(rowField);
    p.add(colField);
    return p;
  }

  public Panel makeScorePanel () {
    Panel p = new Panel();
    p.add(new Label("SCORE"));
    p.add(scoreField);
    p.add(new Button("Reset"));
    return p;
  }	
	
  public Panel makeControlPanel() {
    Panel p = new Panel();
    p.setLayout(new GridLayout(3,1));
    p.add(makeButtonPanel("UP"));
    p.add(makeLeftRightPanel());
    p.add(makeButtonPanel("DOWN"));
    return p;
  }
	
  public Panel makeButtonPanel (String text) {
    Panel p = new Panel();
    p.add(new Button(text));
    return p;
  }
	
  public Panel makeLeftRightPanel () {
    Panel p = new Panel();
    p.setLayout(new GridLayout(1,2));
    p.add(new Button("Left"));
    p.add(new Button("Right"));
    return p;
  }

  public Panel makeTextFieldsPanel () {
    Panel p = new Panel();
    p.setLayout(new GridLayout(rows,cols));	
    for (int i=0; i < rows; i++) {
      for (int j=0; j < cols; j++) {
        TextField tf = new TextField(Integer.toString(maxVisits),2);
        textfields[(i*cols)+j] = tf;
        p.add(makeTextFieldPanel(tf));
      }
    }
    updateTextFields();
    return p;
  }
	
  public Panel makeTextFieldPanel (TextField tf) {
    Panel p = new Panel();
    p.add(tf);
    return p;
  }
	
  public boolean action (Event evt, Object arg) {
    if (arg.equals("Reset")) {
      resetAction();
    } else if (arg.equals("UP")) {
      moveUpAction();
    } else if (arg.equals("Left")) {
      moveLeftAction();
    } else if (arg.equals("Right")) {
      moveRightAction();
    } else if (arg.equals("DOWN")) {
      moveDownAction();
    } else {
      return super.action(evt,arg);
    }
    return true;
  }		

  public void resetAction () {
    currentRow = 1;
    currentCol = 1;
    scoreField.setText("0");
    for (int i=0; i < textfields.length; i++) {
      textfields[i].setText(Integer.toString(maxVisits));
    }
    updateTextFields();	
  }

  public void moveUpAction () {
    if (!(currentTextField.getText().equals("0") || (currentRow == 1))) {
      currentRow--;
      updateTextFields();
    }
  }
	
  public void moveDownAction () {
    if (!currentTextField.getText().equals("0")) {
      if (currentRow==rows) {
        currentRow = 1;
      } else {
        currentRow++;
      }
      updateTextFields();
    }		
  }
	
  public void moveLeftAction () {
    if (!currentTextField.getText().equals("0")) {
      if (currentCol==1) {
        currentCol = cols;
      } else {
        currentCol--;
      }
      updateTextFields();			
    }		
  }
	
  public void moveRightAction () {
    if (!(currentTextField.getText().equals("0") || (currentCol == cols))) {
      currentCol++;
      updateTextFields();
    }		
  }
	
  public void updateTextFields () {
    rowField.setText(Integer.toString(currentRow));
    colField.setText(Integer.toString(currentCol));
    int tempScore = Integer.parseInt(scoreField.getText());
    tempScore++;
    scoreField.setText(Integer.toString(tempScore));
    currentTextField = textfields[((currentRow-1)*cols)+(currentCol-1)];
    int tempVisits = Integer.parseInt(currentTextField.getText());
    tempVisits--;
    currentTextField.setText(Integer.toString(tempVisits));
  }
	
}
Task 1 Draw the initial state of the applet.

Task 2 Draw the state of the applet after pressing the following sequence of buttons: "DOWN", "DOWN", "Left", "UP", "Right", "Left", "Left".


Arrays and Iteration

Processing Arrays

Task 1 Let's say we have an array of integers. We can write a method switch which will switch the contents of two slots in the array. So, if we have an integer array a1=[1,2,3,4] and we do switch(a1,0,2) then a1=[3,2,1,4]. Flesh out the skeleton for the switch method below.
public static void switch (int[] a, int slot1, int slot2);
Does not modify a if either slot1 or slot2 is invalid. Otherwise, modifies a so that the contents of slot1 are in slot2 and vice versa. Note that no new arrays are created by this method.

Task 2 We can write a version of the switch method called copySwitch which returns a new array which is the result of switching the two elements of the original array, but does not modify the original array. For example, if we have a1 from above and we do int [] a2 = copySwitch(a1,0,2) then a1=[1,2,3,4] (unchanged) and a2=[3,2,1,4]. Flesh out the skeleton for the copySwitch method below.

public static int [] copySwitch (int[] a, int slot1, int slot2);
Returns a copy of a if either slot1 or slot2 is invalid. Otherwise, returns a copy of a with the contents of slot1 in slot2 and vice versa.

Palindromes and Arrays

Palindromes are sequences of characters that read the same forwards and backwards. For example, "abcba". Given a sequence of digits, we can create two palindromes from it depending on if we want that sequence of digits to be at the beginning or the end of the palindrome. For example, if we have "123", we could make the following two palindromes: "12321" and "32123". Let's store our digits in an integer array. Flesh out the skeleton for our palindromeArray method which returns to us an array with two elements, each element is one of the answers above.
public static int[][] palindromeArray (int[] a);
Returns an array with the two possible palindromes. Each palindrome created from the integer array is represented by an integer array. Auxiliary methods are not needed and your solution should create the fewest number of arrays necessary to get the job done. The original array a should not be modified.

Palindromes and Lists

We can also create palindromes from sequences of numbers stored in an IntList structure. We'll assume that the ILO.reverse method is available to us as well as all the methods in the IntList contract which we can use by prefixing the methods with IL. Here is a tail-recursive version of palindromeList which specifies the iteration in four state variables named seq1, seq2, ans1, ans2:
public static IntList [] palindromeList (IntList L) {
  IntList reverseL = ILO.reverse(L);
  return palindromeListTail(tail(L),tail(reverseL),L,reverseL);
}

public static IntList [] palindromeListTail (IntList seq1, IntList seq2,
                                          IntList ans1, IntList ans2) {
  if (IL.isEmpty(seq1)) {
    return twoLists(ans1,ans2);
  } else {
    palindromeListTail(IL.tail(seq1),IL.tail(seq2),
                    IL.prepend(head(seq1), ans1),
                    IL.prepend(head(seq2), ans2));
  }
}

// Auxiliary method used by palindromeList
public static IntList [] twoLists (IntList L1, IntList L2) {
  IntList [] result = new IntList[2];
  result[0] = L1;
  result[1] = L2;
  return result;
}
Task 1 Suppose that IntList A has the printed representation [1,2,3,4]. Fill in the following table to show the parameters passed to successive calls to palindromeListTail in the computation that begins with the invocation palindromeList(A). You have been provided with more rows than you need so some rows should remain empty when you are done.
seq1seq2 ans1ans2
     
     
     
     
     
     
     

Task 2 It is possible to express any iteration as a while loop. Flesh out the following code skeleton of an palindromeListWhile() method that behaves just like the above palindromeList() method except that it uses a while loop rather than tail recursion to express the iteration of palindromeListTail(). Your palindromeListWhile should not call any auxiliary methods other than twoLists() and the IntList contract and ILO.reverse.

public static IntList [] palindromeListWhile (IntList L);

Objects, Object Diagrams, and Data Abstraction

The recent issue of Counterpoint has an article about Wellesley stereotypes. Inspired by that, we will model students based on their intelligence, diligence, and gpa. Intelligence and diligence are integer ratings from 1-10. GPA is a double from 0.0 to 4.0. It is often interesting to graph student data in a three dimensional graph where intelligence and diligence correspond to a typical x-y axis and gpa is the z axis. The contract for the Student class is as follows:

Student contract

public Student (int iRating, int dRating, double gpa);
Creates a new Student with the given intelligence rating, diligence rating, and gpa.

public int getIntelligence ();
Returns the intelligence rating (1-10).

public int getDiligence ();
Returns the diligence rating (1-10).

public double getGPA ();
Returns the gpa (0.0-4.0).

public Point getIDRating ();
Returns a Point with intelligence rating as x-coordinate and diligence rating as y-coordinate.

public void setIntelligence (int i);
Sets the intelligence rating.

public void setDiligence (int d);
Sets the diligence rating.

public void setGPA (double gpa);
Sets the gpa.

public void setIDRating (Point idRating);
Sets the intelligence and diligence ratings.

public int getTotalRating ();
Returns a total rating which is three times the sum of the intelligence and diligence ratings plus ten times the gpa.

public boolean isPassing ();
Returns true if gpa is greater or equal to 2.0.

public boolean isHardWorking ();
Returns true if the sum of the intelligence and diligence ratings is greater than or equal to ten and the gpa is greater than or equal to the intelligence rating times 0.4.


Below is one implementation of such a Student.
public class Student {

  private Point idRating; // intelligence, diligence rating
  private double gpa;

  public Student (int iRating, int dRating, double gpa) {
    this.idRating = new Point(iRating, dRating);
    this.gpa = gpa;
  }

  public int getIntelligence () {
    return idRating.x;
  }

  public int getDiligence () {
    return idRating.y;
  }

  public double getGPA () {
    return this.gpa;
  }

  public Point getIDRating () {
    return idRating;
  }

  public void setIntelligence (int i) {
    this.idRating.x = i;
  }

  public void setDiligence (int d) {
    this.idRating.y = d;
  }

  public void setGPA (double gpa) {
    this.gpa = gpa;
  }

  public void setIDRating (Point idRating) {
    this.idRating = idRating;
  }

  public int getTotalRating () {
    return (int) 3*(this.idRating.x+this.idRating.y) + gpa*10;
  }

  public boolean isPassing () {
    return this.gpa >= 2.0;
  }

  public boolean isHardWorking () {
    return ((this.idRating.x+this.idRating.y) >= 10) &&
            (this.gpa >= (this.idRating.x*0.4));
  }
}
Task 1 Consider the following TestStudents class:
public class TestStudents {
  public static void test() {
    Students [] class1 = new Students[4];
    Student barb = new Student(7,3,3.5);
    class1[0] = barb;
    class1[1] = new Student(2,8,1.8);
    class1[3] = new Student(6,6,2.6);
		barb.setDiligence(class[3].getDiligence());
    class1[3].setIDRating(class[0].getIDRating());
    class1[1].setGPA(3.0);
    double barbRating = barb.getTotalRating();
    boolean allPass = class1[0].isPassing() &&
                      class[1].isPassing() &&
                      class[3].isPassing();
    boolean hasHardWorker = class1[0].isHardWorking() ||
                            class1[1].isHardWorking() ||
                            class1[2].isHardWorking();
  }
}
Draw one execution frame for the execution of TestStudents.test(). Do not draw any other execution frames. Draw object diagrams for all objects created by the execution of TestStudents.test().

Task 2 Students can also be represented by an array of three integers which hold the intelligence rating, the diligence rating, and 10 times the gpa (assume gpas are calculated to 1 decimal place only). Write a version of the Student class using this representation which fulfills the entire Student contract.

Task 3 Students can also be represented by three integer instance variables which hold the sum of the intelligence and diligence ratings, the difference between the intelligence and diligence ratings (i.e. intelligence-diligence), and the total rating of the student as specified by the contract. Write a version of the Student class using this representation which fulfills the entire Student contract.