Tuesday, October 26, 2010

LabTest#2 -- Main Class

This can be used to Test your Program :
---------------------------------------
public class Driver

{

  public static void main(String[] args)

  {

      Dungeon theD = new Dungeon();

      System.out.println("~~OUTPUT 1:~~");
      Ghost ghost1 = new Ghost("Ghost1", Monster.MonsterType.GHOST, 1,1, theD);
      Goblin goblin1 = new Goblin("Goblin1", Monster.MonsterType.GOBLIN, 1, 0, theD);
      Zombie zombie1 = new Zombie("Zombie1", Monster.MonsterType.ZOMBIE, 2,1, theD);
      System.out.println(theD.toString());


      System.out.println("~~OUTPUT 2:~~");
      goblin1.moveNorth(theD);
      System.out.println(theD.toString());

 
      System.out.println("~~OUTPUT 3:~~");
      Ghost ghost2 = new Ghost("Ghost2", Monster.MonsterType.GHOST,1,3, theD);
      System.out.println(theD.toString());


      System.out.println("~~OUTPUT 4:~~");
      ghost2.moveSouth(theD);
      System.out.println(theD.toString());


      System.out.println("~~OUTPUT 5:~~");
      ghost2.moveSouth(theD);
      System.out.println(theD.toString());


      System.out.println("~~OUTPUT 6:~~");
      Goblin goblin2 = new Goblin("Goblin2", Monster.MonsterType.GOBLIN, 1,1,theD);
      System.out.println(theD.toString());


      System.out.println("~~OUTPUT 7:~~");
      zombie1.moveWest(theD);
      System.out.println(theD.toString());


      System.out.println("~~OUTPUT 8:~~");
      goblin1.moveEast(theD);
      System.out.println(theD.toString());


      System.out.println("~~OUTPUT 9:~~");
      goblin2.moveEast(theD);
      System.out.println(theD.toString());


      System.out.println("~~OUTPUT 10:~~");
      ghost1.moveNorth(theD);
      System.out.println(theD.toString());


      System.out.println("~~OUTPUT 11:~~");
      ghost2.moveSouth(theD);
      System.out.println(theD.toString());

 }

}


Test 2

  1. (20%) Implement a method called determineWinner which takes two integer arrays as parameters. The arrays represent the number of points each team scored in a set of games that the teams played against each other. Your method should print out the name of the team that won the most games, or whether the tournament was a tie. Remember that if both teams score the same number of points in a game then that game is a tie (it is not a win for either team). Below is an example of how your method will be called:
    public class Tournament {
      
      public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5, 6, 7, 8};
        int[] b = {8, 7, 6, 5, 4, 3, 2, 1};  //in game 0 a scored 1 and b scored 8 
        Tournament.determineWinner(a, b); //it was a tie
        a[0] = 10;
        Tournament.determineWinner(a, b); //a wins
        a[0] = 1;
        b[7] = 10;
        Tournament.determineWinner(a, b); //b wins
      }
    
    }
    
    Answer:
      public static void determineWinner (int [] a, int[] b) {
        int teamaLead =0; //positive is in a's favor, negative in b
        for (int i = 0; i < a.length; i++) { 
          if (a[i] > b[i]) {
            teamaLead++;
          }
          else if (a[i] < b[i]) {
            teamaLead--;
          }
        }
        if (teamaLead > 0) {
          System.out.println("Team A wins!");
        } 
        else if (teamaLead < 0) {
          System.out.println("Team B wins!");
        }
        else {
          System.out.println("It was a tie!");
        }
        
      }
    
  2. (10%) What is wrong with the following program?
    public interface Talkative {
      public void talk();
      
      public String toString() {
        return "";
      }
    }
    
    public class Bobby implements Talkative {
    
      public void talk() {
        System.out.println("Hello friend!");
      }
      
      public String toString() {
        return "My name is Bobby";
      }
    
    }
    
    Answer: An interface cannot implement a method; it can only declare it.
  3. (30%) What does the following program print out?
    public class A {
      private String name;
      
      public int age;
      
      protected double salary;
      
      public static int count = 0;
      
      public A() {
        age = 11;
        count++;
      }
      
      public A(String name, double salary) {
        this.name = name;
        this.salary = salary;
      }
      
      public String toString() {
        return name + " " + age + " " + salary;
      }
    
    }
    
    public class B extends A {
      
      public int score;
    
      public B(String name, double salary, int score) {
        super(name,salary);
        this.score = score;
      }
      
      public String toString(int version) {
        return version + ":" + super.toString() + " score=" + score; 
      }
      
      public static void main(String[] args) {
        A a = new A();
        System.out.println(a);
        A a2 = new A("a2", 10000);
        System.out.println(a2);
        B b = new B("b",20000,33);
        b.score = 22;
        System.out.println(b);
        B b2 = b;
        b2.score = 55;
        System.out.println(b2.toString(1));
        System.out.println(b.toString(2));
        System.out.println("count= " + b.count); 
      }
    }
    
    Answer:
    null 11 0.0
    a2 0 10000.0
    b 0 20000.0
    1:b 0 20000.0 score=55
    2:b 0 20000.0 score=55
    count= 1
    
  4. (40%) Implement a method called check which takes as a parameter a two-dimensional array of integers, you can assume the array is a square of size n, and returns true if the array contains every single integer in the set 1...n^2, false otherwise. Remember that a square array of size n has exactly n^2 elements. (Yes, this is like one of the Sudoku rules).
      /**
       * Returns true if the board contains all the integers from 1...board.length^2
       * Assumes board is a square array.
       * @param board
       * @return
       */
      public static boolean check (int[][] board) {
        boolean[] isIn = new boolean[board.length * board.length]; //all false by default
        for (int rowi = 0; rowi < board.length; rowi++) {
          for (int coli = 0; coli < board.length; coli++) {
            isIn[board[rowi][coli]-1] = true;
          }
        }
        //now return true if they are all true
        for (boolean val : isIn) {
          if (!val) return false;
        }
        return true;
      }
    

Chapter 9 Video

Below is the screencast for Chapter 9 which covers Exceptions. Most modern object-oriented programming languages (Java, C++, C#) implement exceptions. Creating Exceptions for the short programs you write in class is a bit of an overkill. Still, Exceptions are very useful in large programs.

CSCE 145: Chapter 9 from Jose Vidal on Vimeo.

Below are the textbook slides for this chapter.

Wednesday, October 20, 2010

Chapter 8 Video

Below is the screencast for Chapter 8 which covers inheritance and polymorphism. Both of these are features that every object-oriented programming language implements. They help one minimize the number of methods that your program must define. They are overkill for the small programs we will be writing in this class but are indispensable for managing real-world software which is always much larger.

CSCE 145: Chapter 8 from Jose Vidal on Vimeo.

Also, here are the slides from the textbook.

Tuesday, October 19, 2010

Lab 15 - section 6 - Overloading Methods

Write a class Height which has the instance variables feet (int) and inches (int)

(1) Write two constructors (one is default constructor and another should take two arguments of type int)

(2) Write two set methods ..(a) one set will have one argument (inches) of type int and set it to feet and inches ..using conversion rule
(b) Another set method will take an argument of type Height and set the instance variables (feet, inches) to the corresponding fields of the argument

(3) And two equal methods ..(a) one takes one argumnet of type Height and check the corresponding fields and returns a boolean value
(b) another equal takes one argument of type int (in inches) and returns a boolean value

Write a main method and test the methods you have written...
Note that 12 inches = 1 foot

Lab 15 -- Section 5 -- Overloading with Species Class

Problem 2 -- Page 434

HW5 Solution

Below is my solution to this homework:
package hw5;

public class Person {
 
 /** The person's full name */
 private String name;
 
 public enum Status {MARRIED, SINGLE, UNKNOWN, ITS_COMPLICATED};
 
 private Status status;
 
 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 private FriendsList friends;
 
 private Wall wall;
 
 public Person() {
  this("",Status.UNKNOWN);
 }
 
 public Person (String name, Status status) {
  this.name = name;
  this.status = status;
  friends = new FriendsList();
  wall = new Wall();
 }
 
 public String toString() {
  return name + " " + status + "\n" + friends.getNum() + " Friends:\n" + friends 
   + "Wall:\n" + wall;
 }
 
 public void addFriend(Person p) {
  friends.addFriend(p);
  p.friends.addFriend(this); //p.addFriend would create an infinite loop
 }
 
 public void removeFriend(Person p) {
  friends.removeFriend(p);
  p.friends.removeFriend(this);
 }

 public void addWallMessage(String msg, Person author) {
  if (friends.isFriend(author)) {
   wall.addPost(msg, author);
  }
  else {
   System.out.println("ERROR: " + author.getName() + " is not a friend of " + name);
  }
 }
 /**
  * Two persons are the same if they have the same name.
  * @param other
  * @return true if both have the same name.
  */
 public boolean equals(Person other) {
  return name.equalsIgnoreCase(other.name);
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  Person mark = new Person("Mark Zuckerberg",Status.SINGLE);
  Person cam = new Person("Cameron Winklevoss",Status.ITS_COMPLICATED);
  Person tyler = new Person("Tyler Winklevoss",Status.MARRIED);
  Person tyler2 = new Person("tyler winklevoss",Status.UNKNOWN);
  Person peter = new Person("Peter Thiel",Status.UNKNOWN);

  System.out.println(mark);

  mark.addFriend(cam);
  mark.addFriend(tyler);
  mark.addFriend(tyler); //adding it for a SECOND time, so it does not get added
  mark.addFriend(tyler2); //tyler2 does not get added because he has the same name as tyler
  System.out.println(mark); //mark has 2 friends
  System.out.println(tyler); //tyler has 1 friend
  


  mark.addWallMessage("Hello there! We have a project for you!", tyler);
  mark.addWallMessage("Yeah, its a Harvard-only friendster", cam);
  tyler.addWallMessage("Cool, I'll work on it", mark);
  
  System.out.println(mark);
  System.out.println(tyler);
  
  mark.addWallMessage("Hey, how is our social website coming?", cam);
  cam.addWallMessage("Its going to take some time, I got finals", mark);

  peter.addFriend(mark);
  peter.addWallMessage("I made this cool website, want to fund me?", mark);
  mark.addWallMessage("Sure", peter);
  
  mark.addWallMessage("Wait a minute! We paid you to build that!", cam);
  cam.addWallMessage("Nah hah", mark);
  mark.addWallMessage("Yeah ha", cam);
  cam.addWallMessage("I'm unfriending you and your twin", mark);
  
  mark.removeFriend(cam);
  mark.removeFriend(tyler);
  System.out.println(mark); 
  System.out.println(tyler);
  System.out.println(cam);
  System.out.println(peter);
  
  mark.addWallMessage("I'm going to sue you in federal court!", cam);
  
  System.out.println(mark);
  
 }

}

package hw5;

public class FriendsList {
 
 private static final int MAX_FRIENDS = 1024;
 
 private Person[] friend; 
 
 private int numFriends;
 
 public int getNum() {
  return numFriends;
 }
 
 public FriendsList() {
  friend = new Person[MAX_FRIENDS];
  numFriends = 0;
 }
 
 /**
  * Find out if p is in here.
  * @param p
  * @return true if p is in this friendlist
  */
 public boolean isFriend(Person p) {
  for (int i=0; i < numFriends; i++) {
   if (friend[i].equals(p)) {
    return true;
   }
  }
  return false;
 }
 
 /**
  * Add p to list but only if it is not in here already.
  * @param p
  */
 public void addFriend(Person p) {
  if (!isFriend(p)) {
   friend[numFriends++] = p;
  }
 }
 
 public String toString() {
  String result = "";
  for (int i=0; i < numFriends; i++) {
   result += friend[i].getName() + "\n";
  }
  return result;
 }
 
 public void removeFriend(Person p) {
  int i;
  for (i=0; i < numFriends; i++) {
   if (friend[i].equals(p)) break;
  }
  if (i < numFriends) {//p is a friend, at index i
   //overwrite friend[i] with friend[i+1], and so on till the end of the list
   for (int j = i; j < numFriends - 1; j++) {
    friend[j] = friend[j+1];
   }
   numFriends--;
  }
 }
 

}

package hw5;

public class Post {
 public String message;
 public Person author;
 
 public Post(String message, Person author) {
  this.message = message;
  this.author = author;
 }
 
 public String getMessage() {
  return message;
 }
 
 public String getAuthorName() {
  return author.getName();
 }
}

package hw5;

public class Wall {
 
 private Post[] posting;
 
 private int numPosts;
 
 private static final int MAX_WALL_POSTS = 1024;
 
 public Wall() {
  posting = new Post[MAX_WALL_POSTS];
  numPosts = 0;
 }
 
 public void addPost(String msg, Person author) {
  Post post = new Post(msg, author);
  posting[numPosts++] = post;
 }
 
 public String toString() {
  String result = "";
  for (int i=numPosts-1; i >= 0; i--) {
   result += posting[i].getAuthorName() + " writes:\n" + posting[i].getMessage() + "\n";
  }
  return result + "\n";
 }
}



Tuesday, October 12, 2010

Lab 14 - section 6 - Matrix Addition

Write a java code that will add two matrices of same order ( say 3X4 ).

Note a matrix is just a 2D array of numbers. So if the matrix is 3X4 then it has 3 rows and 4 columns. The result of adding two matrics is a matrix of the same order and the elements of the resultant matrix are found by adding corresponding elements of the matrices.

Lab 14 -- Section 5 -- Half Pascals Triangle with 2D Arrays