Sunday, December 13, 2009

Final Averages

Below is the grade distribution for the final test. Some students did not show up for the final, thus the 0 grades.

The final grade distribution for the whole class is:

You will be receiving you final grade shortly.

Friday, December 11, 2009

Final Test

145 Final Test

  1. (10%) Implement a method which takes as input two Strings and returns one String which is formed by interleaving the two arguments. Assume that the two input strings have the same length. For example, if given the input
    then it should return a String with the value:
       * Interleaves the letters of first and second. Assumes that first and second have the same length.
       * @return the interleaved string
      public static String interleave(String first, String second){
        String result = "";
        for (int i =0; i < first.length(); i++){
          result += first.substring(i, i+1) + second.substring(i,i+1);
        return result;

  2. (10%) Implement a method that takes an array of long values representing phone numbers and prints out how many of those phone numbers are in Columbia (803), Greenville (864), and Charleston (843). You must use a switch statement in your method.
    For example, if we call your method with the following array n as input:
    long[] n = {8031234567l, 8649878787l, 8031223456l, 8034543212l, 8642323214l, 8432341231l};
    you will print out:
      public static void countAreaCodes (long[] phoneNumber){
        int columbia = 0;
        int greenville = 0;
        int charleston = 0;
        for (int i =0; i < phoneNumber.length;i++){
          int areaCode = (int) (phoneNumber[i] / 10000000);
          switch (areaCode) {
          case 803: 
            break; //Don't forget the breaks!
          case 864:
          case 843:
        System.out.println("Columbia:" + columbia);
        System.out.println("Greenville:" + greenville);
        System.out.println("Charleston:" + charleston);

  3. (10%) What does the following program print out?
    public class Enigma {
      private static int x;
      protected String s; 
      public Enigma(int x, String s){
        System.out.println("Creating an Engima");
        this.x = x;
        this.s = s;
      public void addItUp(int z){
        x = x + z;
      public void merge(Enigma e){
        s = s + "+" +  e.s;
      public String toString(){
        return "s=" + s + " x=" + Integer.toString(x);
    public class Mystery extends Enigma {
      private int y;
      public Mystery (int x, int y, String s){
        System.out.println("Creating a Mystery");
        this.y = y;
      public void addItUp(int z){
        y = y + z;
      public String toString(){
        return super.toString() + " y=" + Integer.toString(y);
    public class Paradox extends Mystery {
      public Paradox(int x, int y, String s) {
        super(x, y, s);
        System.out.println("Creating a Paradox");
      public void merge (Paradox p){
        s = "Do not cross the paradoxes!";
    public class Main {
      public static void main(String[] args) {
        Paradox p = new Paradox (5,10,"This sentence is false");
        Enigma e = new Enigma(33, "Black hole");
        Enigma e2 = (Enigma)p;
    Creating an Engima
    Creating a Mystery
    Creating a Paradox
    Creating an Engima
    s=This sentence is false x=33 y=10
    s=Black hole x=33
    s=Black hole+This sentence is false x=33
    s=Do not cross the paradoxes! x=33 y=10
    s=Black hole+This sentence is false+Do not cross the paradoxes! x=33
    s=Do not cross the paradoxes! x=33 y=110
    s=Do not cross the paradoxes! x=33 y=610

  4. (10%) A diagonal matrix is a 2-dimensional square array of integers where the numbers on the diagonal are all 1 and the rest are 0. For example, the following is a 1x1 diagonal matrix:
    and this is a 4x4 diagonal matrix:
    1 0 0 0
    0 1 0 0
    0 0 1 0
    0 0 0 1
    Implement a method that takes an integer n and returns an n x n array of integers that is a diagonal matrix.
      public static int[][] makeDiagonalMatrix (int size){
        int [][] result = new int[size][size];
        for (int i = 0; i<size; i++ ){
          result[i][i] = 1;
        return result;

  5. (10%) Implement a class called Tracker which keeps track (in variables) of
    1. how many times each instance's toString() method has been called
    2. the total number of times all instances of the class have had their toString() invoked.

    public class Tracker {
      private static int totalCount = 0;
      private int count;
      public Tracker(){
        count = 0;
      public String toString() {
        return "";

  6. (10%) Implement an Exception called SilentException such that a we do not have to place within a try.catch block a method that throws SilentException.

    public class SilentException extends RuntimeException {

  7. (10%) Implement a method that calculates the shipping and handling costs of an Order, which has methods (these exists, you don't have to write them):
    1. boolean oversized(): returns true if this order is for an oversized item.
    2. CARRIER getCarrier(): where CARRIER is defined as enum CARRIER {UPS, FEDEX, USPS}, returns the carrier. (A carrier is a company that ships packages. UPS, FEDEX, and USPS are the names of three different carrier companies.)
    3. boolean rush(): return true if this a rush order.
    The method you will implement is called double getShippingCosts(Order o) and it will calculate the the shipping and handling costs. The shipping costs for the different carries are given in this table:


    The is also a standard handling fee of $4 for all packages. Also, if it is a rush order then you must add an extra 10% to the regular shipping costs.

      public static double getShippingCosts(Order o){
        double basePrice = 0;
        switch (o.getCarrier()) {
        case UPS:
          if (o.oversized())
            basePrice = 15;
            basePrice = 10;
        case FEDEX:
          if (o.oversized())
            basePrice = 22;
            basePrice = 11;
        case USPS:
          basePrice = 9;
        if (o.rush())
          basePrice = basePrice * 1.10;
        basePrice += 4;
        return basePrice;

  8. (15%) Implement a method that takes a String input which represents a DNA sequence and returns the index of the start of longest string of 'A' letters in the sequence. If there are no A's then return -1. For example,

    given input "ACTAAAGA" you return 3,
    given input "AAAAGA" you return 0,
    given input "CTGATTAAAA" you return 6,
    given input "CTG" you return -1

       * This solution is good enough for 145*/
      public static int longestRepeatA(String dna){
        int longestIndex = -1;
        int longestCount = 0;
        for (int i =0; i < dna.length(); i++){
          int lengthA = 0;
          while (i + lengthA < dna.length() && dna.charAt(i+lengthA) == 'A'){
          if (lengthA > longestCount){
            longestCount = lengthA;
            longestIndex = i;
        return longestIndex;
      /** More experienced developers realize that the above is O(N^2) and that 
       * there is a way to implement it in linear time, like this: */ 
      public static int longestRepeatB(String dna){
        int longestIndex = -1;
        int longestCount = 0;
        int count = 0;
        for (int i = 0; i < dna.length(); i++){
          if (dna.charAt(i) == 'A') {
          if (count > longestCount) {
            longestCount = count;
            longestIndex = i - count + 1;
          if (dna.charAt(i) != 'A'){
            count = 0;
        return longestIndex;

  9. (15%) Implement a method that calculates the average of an array of grades after first dropping the lowest 4 grades. That is, implement:
    double getAverageDropFourLowest(double [] grade)
    Assume that grades.length >= 5. For example, when given
    double[] grade = {100,0,0,0,5,80,90};
    as input, your method should return
    Alert: Notice that this has to work when the lowest grades match, like in the example above where 3 of them where 0.

      /** Returns an an array identical to grades but without the lowest number in grades dropped.
       * if there are more than one minimum we only drop the first one.
       * @param gradesthe array of grades
       * @return a new array of size 1 less than grades.
      public static double[] dropMin(double [] grade){
        double minval = grade[0];
        double[] result = new double[grade.length - 1];
        for (double i : grade){
          if (i < minval)
            minval = i;
        int j = 0; //index into result
        for (int i = 0; i < grade.length; i++){
          if (j < i){ //already dropped min, so just copy the rest of the array
            result[j++] = grade[i];
          else if (grade[i] > minval) { //not the min
            result[j++] = grade[i];
          //if j==i and grades[i] == minval we do nothing, so i increases while j stays the same, 
          // thus ignoring this grade[i]        
        return result;
      /** Returns the average after dropping the lowest 2 grades. */  
      public static double getAverageDropFourLowest(double [] grades){
        double[] g = FinalTest.dropMin(grades);
        g = FinalTest.dropMin(g);
        g = FinalTest.dropMin(g);
        g = FinalTest.dropMin(g);
        double sum = 0;
        for (double i : g){
          sum += i;
        return sum / (double) g.length;

Friday, December 4, 2009

Screencasts: kinda useful

The result of my little screencast survey thus far is:

Were the screencasts useful to you?

So, slightly more useful than not. Most of the people who did not find them usefull did not leave comments. But, one did express a preference for textbook. I too prefer to learn new programming languages by sitting back with a book, so I definitely sympathisze.

Someone else pointed out that he could not ask me a question when he got to a part he did not understand and would forget by the time class came around. In class I suggested students should send me a quick email (or IM) when they came across some part of the video that confused them and I would answer these in class, but I only received a couple of emails during the semester.

Someone who liked them felt it is good to actually see things getting done. This is why I like watching screencasts of, say, using the Google App Engine, and I thought more students would mention it. But only one did.

In any case, the survey is still open so fill it out if you haven't! The graph above will automatically update to show your vote. Isn't software wonderful!

Thursday, December 3, 2009

Grade Distributions

The grade distribution for Test 3 is:

The grade distribution of the weighted average of all grades so far (that is, the grade you would get if there was no final) is:

And, one final correlation graph:

Wednesday, December 2, 2009

Were the Screencasts useful to You?

This semester, for the first time, I did screencasts (videos) for each chapter in the textbook. Could you please fill out the survey below so I can gauge how useful they were to students. Thanks! (Remember to click on the submit button when you are done.)

Final Exam Practice Questions

As mentioned in class, the final is on Friday December 11 @ 2:00pm (to 5:00pm) in our classroom. It will be just like all the other tests: open book, no computers. The test will focus a bit more on the first chapters as these deal with the basic of all programming languages: variables, loops, methods, arrays, etc. Below are links to some practice questions. I also recommend you do all the programming exercises from the textbook. Like I said the first day, the only way to learn to program is by programming, a lot. Have fun with these!
  1. Write a method that finds a given number in a sorted array.
  2. Write a method that returns an array with the first n Fibonnaci numbers.
  3. Write a method that takes as input a 3x3 array of integers and returns true if that array is a magic square.
  4. Implement a simple 1-dimensional automata.
  5. Once your 1D automata works, try working an a simple 2D automata.
  6. Write a method that prints out a simple distribution graph.
  7. Implement a class that limits the number of instances of itself to 4.
  8. Write a method that reverses an array in place.

Tuesday, December 1, 2009

Lab test 3 for Section 006

Write a program to implement a simple selling machine.

Each instance of the selling machine can hold 10 items using ArrayList. Partial program is given and you need to finish all the methods. You can add new items to the selling machine and get items from it if there is one. You need to implement a method to save the selling record (date & item name) to a file. You can use the Exception class for exception handling.

In this lab test, we only consider one type of the items, the Drink class. Code is given.

Please check your email box for the codes.

Test 3

145 Test 3: Fall 2009

  1. (20%) What does the following program print out?
    public class MyExceptions {
      public int trySomething(int x) throws Exception{
        if (x < 0) {
          throw new Exception("X is less than 0");
        return 5;
      public static void main(String[] args){
        MyExceptions m = new MyExceptions();
        try {
          int result = m.trySomething(10);
          System.out.println("Got " + result);
          result = m.trySomething(- 10);
          System.out.println("Got " + result);
          System.out.println("No more tries");
        catch (Exception e){
    Got 5
    X is less than 0

  2. (10%) In the program above, what would happen with we removed the whole catch block? Would the program compile or not? If you think it would not compile then explain what the compiler complains about. If you think is would compile then show what the program would print out when run.
    Answer: It does not compile. You cannot have a try without a catch.

  3. (10%) Implement a class called Employee, with data members String name and int salary. Make sure that instances of your Employee can be written out to a binary file. But, do not write the code to write instances to a file, just make sure that instances of Employee can be written out to a binary file.
    public class Employee implements Serializable {
      private String name;
      private int salary;
      /** Add other methods, as needed. */

  4. (20%) Given the following text file, called data.txt:
    write a program that reads those three values from the text file into an integer, double, and string variables, respectively.
    import java.util.Scanner;
    public class ReadFile {
      public static void main (String[] args){
        String fileName = "data.txt";
        try {
          Scanner inputStream = new Scanner(new File(fileName));
          int i = inputStream.nextInt();
          double d = inputStream.nextDouble();
          String s =;
          System.out.println("i=" + i + "\nd=" + d + "\ns=" + s);
        catch (FileNotFoundException e){
          System.out.println("File Not Found");

  5. (20%) A fast way of finding the greatest common divisor (gcd) of two numbers x and y is by using the following recursive definition of gcd(x,y):
    the gcd(x,y) is equal to the gcd of y and x%y,
    the gcd(x,0) is equal to x.
    Implement a recursive function that calculates the greatest common division of any two integers.
    public class GCD {
      /** Calculate the greatest common division, using the recursive function:
          gcd(x,y) = gcd(y,x%y)
          gcd(x,0) = x  */
      public static int gcd (int x, int y){
            if (y == 0)
              return x;
            return GCD.gcd(y, x%y);
      public static void main (String[] args){

  6. (20%) The following program contains two compile-time errors. What are they?
    import java.util.ArrayList;
    public class Test<Type, E>{
      private ArrayList<Type> list;
      private ArrayList<E> another;
      public Test(){
        list = new ArrayList<E>();
        another = new ArrayList<E>();
      public Type badFunction(E x, Type t){
        E y = x;
        Type tt = t;
        Test<String,String> justMe = new Test<String,String>();
        justMe.add("Bob", "Charlie");
        return tt;
    1. The line
      list = new ArrayList<E>();
      is wrong because the type E should be Type as per the declaration of list.
    2. The line
      because we cannot assume that the type of another will be ArrayList<String>.

SECTION 005: Lab test 03

The Towers of Hanoi is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.

The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:

1. Only one disk may be moved at a time.

2. Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.

3. No disk may be placed on top of a smaller disk.

Below you will find a partial implementation of a Tower of Hanoi with two methods missing: getHeight and hanoi. For this test you will implement these methods.

--- the start Pole, destination Pole and the intermediate Pole are labeled A, B, C.

--- Each disk is labeled (from 1 to the n, n is the height of the tower)

--- Disk 1 is the smallest disk, and Disk n is the largest one.

Hint : The idea is that the method of moving n disks from start pole to destination pole is the same as the method of moving n-1 disks. For example, initially the tower has height 5, we must recursively move a tower of height 4 from A to C, move the biggest disk 5 from A to B (by simply calling method moveDisk), and finally recursively move the tower of height 4 to B from C.

public class HanoiTower {
static int moves = 0;  //number of moves so far

/*Method getHeight is used to get the height of tower from user input*/
static int getHeight()
   // TO DO

/*Method hanoi moves the tower of height n recursively
 * it accept four arguments: the height of the current tower n, the fromPole, the toPole and the withPole.
 * @param n the height of the current tower
 * @param fromPole the start pole
 * @param toPole the destination pole
 * @param withPole the intermediate pole
 * */
static void hanoi(int n, char  fromPole, char  toPole, char  withPole)
   // TO DO

/*Method moveDisk move the disk of diskLabel by simply printing on the console each move*/
static void moveDisk(int diskLabel, char fromPole, char toPole)
     System.out.println("steps: "+ moves);
     System.out.println("Move " + diskLabel + " from " + fromPole + " to " +toPole);

 * @param args
public static void main(String[] args) {
    // TODO Auto-generated method stub

    int TowerHeight;
    char FromPole='A', ToPole='B', WithPole='C';

    System.out.println("Please Enter Tower height...");

    TowerHeight = getHeight();

    hanoi(TowerHeight, FromPole, ToPole, WithPole);



Here is the output of height of 3 after you properly implement the methods:

Please Enter Tower height...


steps: 1

Move 1 from A to B

steps: 2

Move 2 from A to C

steps: 3

Move 1 from B to C

steps: 4

Move 3 from A to B

steps: 5

Move 1 from C to A

steps: 6

Move 2 from C to B

steps: 7

Move 1 from A to B


Submit your file to before 4:00pm. No late submission accepted!