## Sunday, October 31, 2010

### HW 6: Finance

In this homework you will practice using exceptions and files by writing a short program that reads in stock prices and prints out, and saves to a file, some information about these prices.

If you go to this page you will see how Google makes available historical prices for all stocks, in this case GOOG. On that page there is a link called download to spreadsheet which will download these price to a CSV file. Download that file and open it in a text editor so you can see what it looks like. You will be writing a program that can read these files (CSV files of historical stock prices from finance.google) and parse them into an array.

One thing you will notice is that some of the days a trading volume of 0. These are holidays. These days will mess up our later calculations so when you read from a file you must skip these days.

Also, assume that there are at most 1000 days of data. If there are more in the data file, your program should throw a `FileTooBigException`.

Once you have parsed a file, your program will then calculate the volatility of the stock for the last X days, where X is an argument to your function. To calculate volatility for the last X days you

1. Calculate the average close price for the last X days. Call this `average-close`.
2. Add up the `square-difference = (closing-price - average-close) ^ 2` for every closing price in the last X days, then divide this number by X and then take its square root. That's the volatility.

The volatility tells us how much a stock price has moved, but it is only one number. We want to get a better picture of how the stock has moved. What we need is a distribution of the closing prices and the number of days, in the last X days, that the stock has closed at that price (where all prices are truncated to their integer value).

Implement a method called `int[] getPriceDistribution(int X)` which returns an array whose values are the number of days the stock has closed at that price (like a grade distribution, but for prices). Also implement `getMinClose(int X)` which returns the minimum closing price in the last X days. Then, the index 0 on the array returned by `getPriceDistribution` will be the number of days the stock closed at the price `getMinClose(X)`.

Finally, now that you have this price distribution, we'll want to save it to a CSV file. Implement a method called `savePriceDistribution(String outFile, int X` which writes the price distribution of the last X days to outfile, in CSV format.

Below is a concrete example of a `main` using the new `Security` class and the output it generates.

``` public static void main(String[] args) {
Scanner istream = null;
String inputFile = "/Users/jmvidal/data.csv";
try {
istream = new Scanner(new File(inputFile));
} catch (FileNotFoundException e) {
System.out.println("Ooops, no such input file:" + inputFile);
System.exit(1);
}

Security s = new Security(); //Security class will hold all the data
try {
} catch (FileTooBigException e1) { //file is to big to read
System.out.println(e1.getMessage());
System.exit(1);
}

System.out.println(s); //print out all the contents. Note: no days with 0 volume.

try {
System.out.println("Volatility in the last 10 days = " + s.getVolatility(10));
System.out.println("Volatility in the last 1000 days = " + s.getVolatility(1000));

} catch (NotEnoughDataException e) {
System.out.println("Sorry, not enough data." + e.getMessage());
}

System.out.println("Price Distribution for the last 10 days.");
System.out.println("price\tnumber of days");
int[] priceDistribution = s.getPriceDistribution(10); //get the distribution array
int minClose = (int)s.getMinClose(10);
for (int i=0; i < priceDistribution.length; i++) { //we need this loop to print it out
int p = minClose + i;
System.out.println(p + "\t" + priceDistribution[i]);
}

try {
//now, save the distribtion for the last 20 days to a file.
s.savePriceDistribution("/Users/jmvidal/distribution-20.csv",20);
} catch (FileNotFoundException e) {
System.exit(1);
}

}
```

And here is the output it generates:

```28-Oct-10 618.58 2187396
27-Oct-10 616.47 2242414
26-Oct-10 618.6 2513633
25-Oct-10 616.5 3158700
...well you get the idea...
...notice, no days with 0 volume...
5-Nov-09 548.65 1848039
4-Nov-09 540.33 2333629
3-Nov-09 537.29 2382892
2-Nov-09 533.99 3202875
30-Oct-09 536.12 3469738

Volatility in the last 10 days = 5.4362785064784855
Sorry, not enough data.Need more historical data
Price Distribution for the last 10 days.
price number of days
601 1
602 0
603 0
604 0
605 0
606 0
607 2
608 0
609 0
610 0
611 1
612 1
613 0
614 0
615 0
616 2
617 1
618 2
```

This homework is due Tuesday, November 9 @9:00am

## Thursday, October 28, 2010

### Lab 17 -- Solution -- Class: Driver

```

import java.util.Scanner;

public class Driver {

public static void main(String[] args)
{
boolean valid;
int num_Employees;
Employee[] data = new Employee[100];
int salary_sum = 0;
double avg_salary;

Scanner keyboard = new Scanner(System.in);

do
{
System.out.println("Number of Employees:");
num_Employees = keyboard.nextInt();
}while(num_Employees < 0 || num_Employees > 100);

int e_count = 1;
String ssnInput;
int sal;

while(e_count <= num_Employees)
{
Employee e = new Employee();

// Enter Employee Details
e.EnterEmployeeDetails(e_count);

salary_sum += e.getSalary();

// Verification of SSN (Length and Character)
do
{
valid = true;

try
{
String str = e.getSSN();
int count = 0;

// Check for SSNLength Exception
for(int i=0; i < str.length(); i++)
{
if(str.charAt(i) != '-' && str.charAt(i) != ' ')
count++;
}

if(count != 9)
{ valid = false;
throw new SSNLengthException();
}

/* **************************************** */

for(int j = 0; j < str.length(); j++ )
{
if(str.charAt(j) != '-' && str.charAt(j) != ' ')
{
if(!Character.isDigit(str.charAt(j)))
{
valid = false;
throw new SSNCharacterException();
}
}
}

}
catch(SSNLengthException exp)
{
System.out.println(exp.getMessage());
e.EnterEmployeeSSN(e_count);
}
catch(SSNCharacterException expr)
{
System.out.println(expr.getMessage());
e.EnterEmployeeSSN(e_count);
}

}while(valid == false);

data[e_count - 1] = e;

e_count++;
} // end of while

avg_salary = (double)salary_sum / num_Employees;

for(int k=0; k < num_Employees; k++)
{
if(data[k].getSalary() > avg_salary)
{
System.out.printf("EmpNumber %d: %s ABOVE SALARY  %n", k+1, data[k].toString());
}
else
System.out.printf("EmpNumber %d: %s BELOW SALARY %n", k+1, data[k].toString());
}

}
}
```

### Lab 17 -- Solution -- Class: Person

```

public class Person
{
private String name;

public Person()
{
name = "No Name Yet";
}

public Person(String initialName)
{
name = initialName;
}

public void setName(String newName)
{
name = newName;
}

public String getName()
{
return name;
}

public void writeOutput()
{
System.out.println("Name: " + name);
}

public boolean hasSameName(Person otherPerson)
{
return this.name.equalsIgnoreCase(otherPerson.name);
}
}
```

### Lab 17 -- Solution -- Class: Employee

```
import java.util.Scanner;

public class Employee extends Person
{
String SSN;
int salary;

Scanner k1 = new Scanner(System.in);
Scanner k2 = new Scanner(System.in);
Scanner k3 = new Scanner(System.in);

public Employee()
{
SSN = "";
salary = 0;
}

public Employee(String s, int sal)
{
this.SSN = s;
this.salary = sal;
}

public String getSSN() {
return SSN;
}

public void setSSN(String sSN) {
SSN = sSN;
}

public int getSalary() {
return salary;
}

public void setSalary(int salary) {
this.salary = salary;
}

public void EnterEmployeeDetails(int empNumber)
{
// Enter Name
System.out.println("Employee " + empNumber + ":" + " Enter Name:");
super.setName(k1.nextLine());

this.EnterEmployeeSSN(empNumber);

// Enter Salary
System.out.println("Employee " + empNumber + ":" + " Enter Salary:");
this.setSalary(k3.nextInt());

}

public void EnterEmployeeSSN(int empNumber)
{
System.out.println("Employee " + empNumber + ":" + this.getName() + " :Enter SSN:");
this.setSSN(k2.nextLine());
}

public String toString()
{
String str;
str = String.format("Emp Name:%s EmpSSN:%s EmpSalary:%d", this.getName(), this.getSSN(), this.getSalary());
return str;
}
}
```

### Lab 17 -- Solution -- Class: SSNLengthException

```
public class SSNLengthException extends Exception
{
public SSNLengthException()
{
super("SSN Length not exactly 9 Characters");
}

public SSNLengthException(String msg)
{
super(msg);
}

}
```

### Lab 17 -- Solution -- Class: SSNCharacterException

```
public class SSNCharacterException extends Exception
{
public SSNCharacterException()
{
super("Inappropriate Character in SSN:Non Digit Character Found");
}

public SSNCharacterException(String msg)
{
super(msg);
}
}
```

### Lab 17 -- Section 6

Same as Section 5

### Lab 17 - Section 5 -- Exception Handling

Problem 7 -- Page 675 --For Persons Class refer to Page 552

## Wednesday, October 27, 2010

### Revised Solutions for LabTest#2 - Section 5/6 Posted

I have posted the revised solutions of LabTest#2 - Section 5/6 having replaced the ('instanceof' keyword && SuperClass to SubClass typecast ) and making accompanying modifications. ( after Prof. Vidals comments .. :) .. ). My apologies. Hope this helps.

### LabTest#2: Revised Solution -- Section 6 -- Class: Item

I had forgotton to include this before
```public class Item
{
private String name;
private int Price;

public Item()
{
name = "";
Price = 0;
}

public Item(String n, int p)
{
this.name = n;
this.Price = p;
}

public String getName() {
return name;
}

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

public int getPrice() {
return Price;
}

public void setPrice(int price) {
Price = price;
}

}
```

### Celebrity Interview

Below is an interview with Jeff Atwood, creator of stackoverflow.

See all 3 videos here. He talks about HTML5 issues, which we will be covering in my CSCE 242 class next semester.

## Tuesday, October 26, 2010

### Not So Good Solutions

The solutions Shamik and Humayun provided below, while functional, are not really how you should solve these problems. Specifically, you should not use instanceof. You should use inheritance instead. I'll explain in class. I'm going to have to give them a B- for these solutions.

The simple rule is: never use instanceof. There are some rare occasions when its useful.

### LabTest#2: Revised Solution -- Section 5 -- Class: Dungeon

```public class Dungeon
{

private Tile[][] theDungeon;

public Dungeon()
{
theDungeon = new Tile[10][10];

for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{
theDungeon[i][j] = new Tile();
}
}
}

/* ************************************************************* */

public void addMonsters(Monster m, int x, int y)
{
if(x < 0 || x > 10)
System.out.println("Out of Range");

if(y < 0 || y > 10)
System.out.println("Out of Range");

}

/* ***************************************************************** */

public void deleteMonsters(int x, int y)
{
// Gets the array of monsters at Dungeon[x][y]
Monster[] m_xy = theDungeon[x][y].getMonsters();

for(int i = 0; i < theDungeon[x][y].getSize(); i++)
{
System.out.println("Monster: "
+ m_xy[i] + " AT DUNGEON[" + x + "][" + y + "] GETS EATEN  UP");
}

// Creating an empty array of Monster[] type:
Monster[] newMonsterArray = new Monster[100];

// Replace the Monster[] array of this TILE with an empty one
theDungeon[x][y].setMonsters(newMonsterArray);
theDungeon[x][y].setSize(0);
}

/* ***************************************************************** */

// Returns the 2D Array
public Tile[][] getTheDungeon()
{
return theDungeon;
}

/* ***************************************************************** */

public String toString()
{
String Str = "";
String contents = "";

for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{

contents = theDungeon[i][j].toString();

if(!contents.equals(""))
{
Str += String.format("DUNGEON[%d][%d] CONTAINS :: %n %s %n",i, j, contents);
}
else
{
//Str += String.format("DUNGEON[%d][%d] CONTAINS :: %n EMPTY %n",i, j);
}
}
}

return Str;
}

/* ***************************************************************** */

}
```

### LabTest#2: Revised Solution -- Section 5 -- Class: Tile

```public class Tile
{
private Monster[] monsters;
private int size;

public Tile()
{
monsters = new Monster[100];
size = 0;
}

/* ******************************************************************* */

public void setSize(int s)
{
this.size = s;
}

/* ******************************************************************* */

public int getSize()
{
return this.size;
}

/* ******************************************************************* */

{
monsters[size] = m;
size++;
}

/* ******************************************************************* */

public void deleteTheMonster(Monster m)
{
int index;

// If match found then delete
if((index = this.contains(m)) >= 0)
{
for(int i = index; i < this.getSize() - 1; i++)
{
// The shift after deletion
monsters[i] = monsters[i+1];
}
size--;
}
}

/* ******************************************************************* */

public int contains(Monster m)
{
int match_index = -1;

for(int i=0; i < this.getSize(); i++)
{
if(monsters[i].getName().equalsIgnoreCase(m.getName()) && monsters[i].getMonsterType() == m.getMonsterType())
{
match_index = i;
break;
}
}

return match_index;
}

/* ******************************************************************* */

// returns the array of monsters at the particular tile
public Monster[] getMonsters()
{
return monsters;
}

/* ******************************************************************* */

// set the array of monsters for a particular tile
public void setMonsters(Monster[] m)
{
this.monsters = m;
}

/* ******************************************************************* */

// Checks to see if this CHANNEL contains anyone of Monster.MonsterType monsType
public boolean contains(Monster.MonsterType monsType)
{
boolean returnValue = false;

for(int i = 0; i < this.getSize(); i++)
{
if(monsters[i].getMonsterType() == monsType)
{
returnValue = true;
break;
}
}
return returnValue;
}

/* ******************************************************************* */

//
public String toString()
{
String str = "";

if(this.getSize() > 0)
{
for(int i = 0; i < this.getSize(); i++)
{
str += String.format("Cell[%d]: %s %n",i, monsters[i]);
}
}
return str;
}

/* ******************************************************************* */

}
```

### LabTest#2: Revised Solution -- Section 5 -- Class: Monster

```public class Monster
{
private String name;
public enum MonsterType { GOBLIN, ZOMBIE, GHOST };
public MonsterType type;

public enum LiveStatus { LIVING, DEAD };
public LiveStatus liveStat;

public Monster()
{
name = "";
}

public Monster(String n)
{
this.setName(n);
}

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

public String getName()
{
return this.name;
}

public void setMonsterType(MonsterType m)
{
type = m;
}

public MonsterType getMonsterType()
{
return type;
}

public void setLiveStatus(LiveStatus l)
{
liveStat = l;
}

public LiveStatus getLiveStatus()
{
return liveStat;
}

}

```

### LabTest#2: Revised Solution -- Section 5 -- Class: Goblin

```
public class Goblin extends Monster
{
private int x;
private int y;

public Goblin(String n, MonsterType m, int x, int y, Dungeon theD)
{
super(n);
super.setMonsterType(m);
this.setX(x);
this.setY(y);
super.setLiveStatus(Monster.LiveStatus.LIVING);

}

/* ************************************************************* */

// Setters and Getters

public int getX() {
return x;
}

public void setX(int x) {
this.x = x;
}

public int getY() {
return y;
}

public void setY(int y) {
this.y = y;
}

/* ************************************************************** */

// Movements

// move North
public void moveNorth(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

// Goes North till it finds an empty space
do
{
this.setY(this.getY() + 1);

// Wraps around ( if it goes beyond GRID)
if(this.getY() > 9)
this.setY(0);

}while(theD.getTheDungeon()[this.getX()][this.getY()].getSize() > 0);

// when it has found an empty space --> it then adds itself there
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

// move South
public void moveSouth(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

// Goes on till it finds an empty space
do
{
this.setY(this.getY() - 1);

// Wraps around ( if it goes beyond GRID)
if((this.getY()) < 0)
this.setY(9);

}while(theD.getTheDungeon()[this.getX()][this.getY()].getSize() > 0);

// when it has found an empty space --> it then adds itself there
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

// move West
public void moveWest(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

// Goes on till it finds an empty space
do
{
this.setX(this.getX() - 1);

// Wraps around ( if it goes beyond GRID)
if((this.getX()) < 0)
this.setX(9);

}while(theD.getTheDungeon()[this.getX()][this.getY()].getSize() > 0);

// when it has found an empty space --> it then adds itself there
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

// move West
public void moveEast(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

// Goes on till it finds an empty space
do
{
this.setX(this.getX() + 1);

// Wraps around ( if it goes beyond GRID)
if((this.getX()) > 9)
this.setX(0);

}while(theD.getTheDungeon()[this.getX()][this.getY()].getSize() > 0);

// when it has found an empty space --> it then adds itself there
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

/* **************************************************************** */

public String toString()
{
String str;
//str = super.getName() + " " + super.getMonsterType().toString() + "\n";
str = String.format("%s %s", super.getName(), super.getMonsterType().toString());
return str;
}
}
```

### LabTest#2: Revised Solution -- Section 5 -- Class: Zombie

```public class Zombie extends Monster
{
private int x;
private int y;

public Zombie(String n, MonsterType m, int x, int y, Dungeon theD)
{
super(n);
super.setMonsterType(m);
this.setX(x);
this.setY(y);
super.setLiveStatus(Monster.LiveStatus.LIVING);

}

/* ****************************************************************** */

// Setters and Getters

public int getX() {
return x;
}

public void setX(int x) {
this.x = x;
}

public int getY() {
return y;
}

public void setY(int y) {
this.y = y;
}

/* ************************************************************** */

// Movements

// move north
public void moveNorth(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

this.setY(this.getY() + 1);

// Wraps around ( if it goes beyond GRID)
if((this.getY()) > 9)
this.setY(0);

this.TheZombieAct(theD, this.getX(), this.getY());
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

// move south
public void moveSouth(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

this.setY(this.getY() - 1);

// Wraps around ( if it goes beyond GRID)
if((this.getY()) < 0)
this.setY(9);

this.TheZombieAct(theD, this.getX(), this.getY());
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

// Move west
public void moveWest(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

this.setX(this.getX() - 1);

// Wraps around ( if it goes beyond GRID)
if((this.getX()) < 0)
this.setX(9);

this.TheZombieAct(theD, this.getX(), this.getY());
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

// Move east
public void moveEast(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

this.setX(this.getX() + 1);

// Wraps around ( if it goes beyond GRID)
if((this.getX()) > 9)
this.setX(0);

this.TheZombieAct(theD, this.getX(), this.getY());
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

/* **************************************************************** */

// The Zombie's Act

public void TheZombieAct(Dungeon theD, int x, int y)
{
// The Zombie now deletes all monsters at Dungeon[x][y + 1]
theD.deleteMonsters(x, y);

// And it adds itself at Dungeon[x][y + 1] after having eaten everyone at Dungeon[x][y + 1]
}

/* **************************************************************** */

public String toString()
{
String str;
//str = super.getName() + " " + super.getMonsterType().toString() + "\n";
str = String.format("%s %s", super.getName(), super.getMonsterType().toString());
return str;
}

}
```

### LabTest#2: Revised Solution -- Section 5 -- Class: Ghost

```
public class Ghost extends Monster
{
private int x;
private int y;

public Ghost(String n, MonsterType m, int x, int y, Dungeon theD)
{
super(n);
super.setMonsterType(m);
this.setX(x);
this.setY(y);
super.setLiveStatus(Monster.LiveStatus.LIVING);

}

/* ************************************************************** */

// Getters and Setters

public int getX() {
return x;
}

public void setX(int x) {
this.x = x;
}

public int getY() {
return y;
}

public void setY(int y) {
this.y = y;
}

/* ************************************************************** */

// Movements

// move north

public void moveNorth(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{
// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

// Goes North till it finds a TILE without another GHOST
do
{
this.setY(this.getY() + 1);

// Wraps around ( if it goes beyond GRID)
if((this.getY()) > 9)
this.setY(0);

}while(theD.getTheDungeon()[this.getX()][this.getY()].contains(Monster.MonsterType.GHOST));

// theD.getTheDungeon() --> returns Tile[][] array
// theD.getTheDungeon()[x][y] --> returns a Tile Object --> containing Monsters[]

// Now it adds itself to this CHANNEL
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

// move south
public void moveSouth(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

// Goes south till it finds a TILE without another ghost
do
{
this.setY(this.getY() - 1);

// Wraps around ( if it goes beyond GRID)
if((this.getY()) < 0)
this.setY(9);

}while(theD.getTheDungeon()[this.getX()][this.getY()].contains(Monster.MonsterType.GHOST));

// theD.getTheDungeon() --> returns Tile[][] array
// theD.getTheDungeon()[x][y] --> returns a Tile Object --> containing Monsters[]

// Now it adds itself to this TILE
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

// move west
public void moveWest(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

// Goes west till it finds a TILE without another ghost
do
{
this.setX(this.getX() - 1);

// Wraps around ( if it goes beyond GRID)
if((this.getX()) < 0)
this.setX(9);

}while(theD.getTheDungeon()[this.getX()][this.getY()].contains(Monster.MonsterType.GHOST));

// theD.getTheDungeon() --> returns Tile[][] array
// theD.getTheDungeon()[x][y] --> returns a Tile Object --> containing Monsters[]

// Now it adds itself to this CHANNEL
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

// move west
public void moveEast(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

// Goes EAST till it finds a TILE without another ghost
do
{
this.setX(this.getX() + 1);

// Wraps around ( if it goes beyond GRID)
if((this.getX()) > 9)
this.setX(0);

}while(theD.getTheDungeon()[this.getX()][this.getY()].contains(Monster.MonsterType.GHOST));

// theD.getTheDungeon() --> returns Tile[][] array
// theD.getTheDungeon()[x][y] --> returns a Tile Object --> containing Monsters[]

// Now it adds itself to this CHANNEL
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

/* **************************************************************** */

public String toString()
{
String str;
//str = super.getName() + " *** " + super.getMonsterType() + "\n";
str = String.format("%s %s", super.getName(), super.getMonsterType().toString());
return str;
}

}
```

### LabTest#2: Revised Solution -- Section 6 -- Class: Shoes

```public class Shoes extends Item
{
private int theSize;

public Shoes()
{
this.setSize(0);
}

public Shoes(String n, int p, int s)
{
super(n, p);
this.setSize(s);
}

public void setSize(int s)
{
this.theSize = s;
}

public int getSize()
{
return theSize;
}

public String toString()
{
String str;
str = String.format("Item Name:%s Item Price:%d Item Size:%d", super.getName(), super.getPrice(), this.getSize());
return str;
}
}
```

### LabTest#2: Revised Solution -- Section 6 -- Class: Shirt

```public class Shirt extends Item
{
public enum Size { S, M, L, XL };
private Size theSize;

public Shirt()
{
this.setSize(Size.S);
}

public Shirt(String n, int p, Size s)
{
super(n, p);
this.setSize(s);
}

public void setSize(Size s)
{
theSize = s;
}

public Size getSize()
{
return theSize;
}

public String toString()
{
String str;
str = String.format("Item Name:%s Item Price:%d Item Size:%s", super.getName(), super.getPrice(), this.getSize().toString());
return str;
}

}
```

### LabTest#2: Revised Solution -- Section 6 -- Class: Pant

```public class Pant extends Item
{
private int theSize;

public Pant()
{
this.setSize(0);
}

public Pant(String n, int p, int s)
{
super(n, p);
this.setSize(s);
}

public void setSize(int s)
{
this.theSize = s;
}

public int getSize()
{
return theSize;
}

public String toString()
{
String str;
str = String.format("Item Name:%s Item Price:%d Item Size:%d", super.getName(), super.getPrice(), this.getSize());
return str;
}
}
```

### LabTest#2: Revised Solution -- Section 6 -- Class: Shopping Cart

```public class ShoppingCart
{
public Item[] theItems;
public int item_count;
public int TotalPrice;

public ShoppingCart()
{
theItems = new Item[1000];
item_count = 0;
TotalPrice = 0;
}

/* ****************************************************************************************** */

// Setters and Getters

public int getItemCount()
{
return item_count;
}

public void setItemCount(int ic)
{
item_count = ic;
}

public void setTotalPrice(int t)
{
this.TotalPrice = t;
}

public int getTotalPrice()
{
}

public void setTheItems(Item[] t)
{
this.theItems = t;
}

public Item[] getTheItems()
{
return theItems;
}

/* ****************************************************************************************** */

{
theItems[item_count] = anItem;

item_count++;
}

/* ****************************************************************************************** */

public boolean removeItem(Item e)
{
boolean returnValue = false;
int matched_item;

if((matched_item = this.contains(e)) >= 0)
{
for(int i = matched_item; i < item_count - 1; i++)
{
theItems[i] = theItems[i+1];
}

item_count--;

this.setTotalPrice(this.getTotalPrice() - e.getPrice());
returnValue = true;
}

if(returnValue == false)
{
}
else
{
System.out.println("Item Removed:" + e);
}
return returnValue;
}

/* ****************************************************************************************** */

public int contains(Item e)
{
int item_match = -1;

for(int j = 0; j < this.getItemCount(); j++)
{
if(theItems[j].getName().equals(e.getName()) && theItems[j].getPrice() == e.getPrice())
{
item_match = j;
}
}
return item_match;
}

/* ****************************************************************************************** */

public int calculateTotalPrice()
{
this.setTotalPrice(0);

for(int i = 0 ; i < this.getItemCount(); i++)
{
TotalPrice += theItems[i].getPrice();
}

return this.getTotalPrice();
}

/* ****************************************************************************************** */

public void clear()
{
for(int j = 0; j < this.getItemCount(); j++)
{
theItems[j] = new Item("", 0);
}

// Create an empty array of Item type : Item[]
Item[] freshEmptyItems = new Item[1000];

// Set theItems to this freshEmptyItems
this.setTheItems(freshEmptyItems);

this.setItemCount(0);
this.setTotalPrice(0);

System.out.println("Cart Cleared");
}

/* ****************************************************************************************** */

public String toString()
{
boolean encountered_before;
int the_item_count;
String str = "";

for(int i = 0; i < this.getItemCount(); i++)
{
encountered_before = false;

// Check to see if encountered before
for(int j = 0; j < i; j++)
{
if(theItems[i].getName().equalsIgnoreCase(theItems[j].getName()))
{
encountered_before = true;
}
}

// if not encountered before then calculate its count
if(encountered_before == false)
{
// calculate the item_counts of each item
the_item_count = 1;
for(int k = i+1; k < this.getItemCount(); k++)
{
if(theItems[i].getName().equalsIgnoreCase(theItems[k].getName()))
{
the_item_count++;
}
}

// display
//System.out.println("Quantity = " + the_item_count + " " + theItems[i].getName());
//str += "Quantity = " + the_item_count + " " + theItems[i].getName() + "\n";
str += String.format("Quantity = %d %s %n", the_item_count, theItems[i].getName());
}

}
return str;
}

/* ****************************************************************************************** */

}

```

### LabTest#2 -- Section 6 -- Shopping Cart of Items

```
1) Create an Item class with a price and name attributes.
2) Create Shirt, Pants, and Shoes classes, with added size attribute. Shirt sizes are S,M,L,XL. Pant and shoe sizes are integers.
3) Create a shopping cart which can hold up to 1000 Items,
with methods :

b) removeItem(Item e)
c) int calculateTotal() ;returns the total price
d) clear(); removes all items from the shopping cart
e) toString(); each item in one line.
If an item is there more than once it should say
quantity=4 blue shirt
rather than "blue shirt" in 4 separate lines

```

### LabTest#2 -- Section 6 -- Driver Class ( You can use this to test your program )

```
public class Driver
{
public static void main(String[] args)
{

Shirt shirt1 = new Shirt("blue shirt", 100, Shirt.Size.M);
Shirt shirt2 = new Shirt("blue shirt", 120, Shirt.Size.S);
Shirt shirt3 = new Shirt("maroon shirt", 130, Shirt.Size.L);

Pant pant1 = new Pant("brown pant", 65, 32);
Pant pant2 = new Pant("black pant", 130, 34);
Pant pant3 = new Pant("brown pant", 100, 33);

Shoes shoe1 = new Shoes("black shoe", 200, 8);
Shoes shoe2 = new Shoes("black shoe", 200, 8);
Shoes shoe3 = new Shoes("grey shoe", 200, 8);

/* **************************************************************** */
ShoppingCart Cart = new ShoppingCart();

System.out.println("TOTAL PRICE = \$" + Cart.calculateTotalPrice());
System.out.println("ITEMS BOUGHT: \n" + Cart.toString());

/* **************************************************************** */

Cart.removeItem(shirt3);
Cart.removeItem(pant2);
Cart.removeItem(shoe2);

System.out.println("TOTAL PRICE = \$" + Cart.calculateTotalPrice());
System.out.println("ITEMS BOUGHT: \n" + Cart.toString());

/* ****************************************************************** */

Cart.clear();
System.out.println("TOTAL PRICE = \$" + Cart.calculateTotalPrice());
System.out.println("ITEMS BOUGHT: \n" + Cart.toString());

/* ******************************************************************* */

Shirt shirt4 = new Shirt("green shirt", 130, Shirt.Size.L);
Pant pant4 = new Pant("green pant", 130, 34);
Shoes shoe4 = new Shoes("green shoe", 200, 8);

System.out.println("TOTAL PRICE = \$" + Cart.calculateTotalPrice());
System.out.println("ITEMS BOUGHT: \n" + Cart.toString());

/* ******************************************************************** */

}
}

```

### LabTest#2-Section 6 -- Sample Output ( in accordance to above Driver Class)

Sorry about the minor glitch in the TotalPrice Calculation. I had forgotton to reset TotalPrice to 0 : It should be ok now
----------------------------------------------------------------------------------------
```
Item Added: Item Name: blue shirt Item Price: \$100 Item Size:M
Item Added: Item Name: blue shirt Item Price: \$120 Item Size:S
Item Added: Item Name: maroon shirt Item Price: \$130 Item Size:L
Item Added: Item Name: brown pant Item Price: \$65 Item Size:32
Item Added: Item Name: black pant Item Price: \$130 Item Size:34
Item Added: Item Name: brown pant Item Price: \$100 Item Size:33
Item Added: Item Name: black shoe Item Price: \$200 Item Size:8
Item Added: Item Name: black shoe Item Price: \$200 Item Size:8
Item Added: Item Name: grey shoe Item Price: \$200 Item Size:8
TOTAL PRICE = \$1245
ITEMS BOUGHT:
Quantity = 2 blue shirt
Quantity = 1 maroon shirt
Quantity = 2 brown pant
Quantity = 1 black pant
Quantity = 2 black shoe
Quantity = 1 grey shoe

Item Removed: Item Name: maroon shirt Item Price: \$130 Item Size:L
Item Removed: Item Name: black pant Item Price: \$130 Item Size:34
Item Removed: Item Name: black shoe Item Price: \$200 Item Size:8
TOTAL PRICE = \$785
ITEMS BOUGHT:
Quantity = 2 blue shirt
Quantity = 2 brown pant
Quantity = 1 black shoe
Quantity = 1 grey shoe

Cart Cleared
TOTAL PRICE = \$0
ITEMS BOUGHT:

Item Added: Item Name: green shirt Item Price: \$130 Item Size:L
Item Added: Item Name: green pant Item Price: \$130 Item Size:34
Item Added: Item Name: green shoe Item Price: \$200 Item Size:8
TOTAL PRICE = \$460
ITEMS BOUGHT:
Quantity = 1 green shirt
Quantity = 1 green pant
Quantity = 1 green shoe
```

### LabTest#2 -- Walk through GRID Dungeons

```
1) Create a class called Monster, with attribute name. You can have other enum variables too like :
public enum MonsterType { GOBLIN, ZOMBIE, GHOST };
public MonsterType type;
Feel free to create other enum variables ( if you feel you need more )

2) Create classes Goblin, Zombie, and Ghost which extends the Monster Class. Can  have attributes int x, int y.
3) Create Dungeon which is a (10x10) array of Tiles.
4) A Tile has a 1-D array of Monsters, which starts out empty.
5) The Dungeon class should have methods
deleteMonsters(x,y); //deletes all monster in x,y
toString();// prints out the dungeon, and its inhabitants
You can add other functions if you want to ( according to need )
6) The Monsters should all have:
moveNorth(); //moves north one
moveSouth();
moveEast();
moveWest();
except that:
the goblin will continue moving as long as there is someone else in its destination spot
the zombie kills (deletes) everyone else in its destination spot.
if a ghost lands in a Tile with another ghost, if keeps moving to the next spot.

```

### LabTest#2 -- Sample Output ( In Accordance to the Main Program given below )

• ```~~OUTPUT 1:~~
DUNGEON[1][0] CONTAINS ::    Cell[0]: Goblin1 GOBLIN
DUNGEON[1][1] CONTAINS ::
Cell[0]: Ghost1 GHOST
DUNGEON[2][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE

~~OUTPUT 2:~~
DUNGEON[1][1] CONTAINS ::
Cell[0]: Ghost1 GHOST
DUNGEON[1][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN
DUNGEON[2][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE

~~OUTPUT 3:~~
DUNGEON[1][1] CONTAINS ::
Cell[0]: Ghost1 GHOST
DUNGEON[1][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN
DUNGEON[1][3] CONTAINS ::
Cell[0]: Ghost2 GHOST
DUNGEON[2][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE

~~OUTPUT 4:~~
DUNGEON[1][1] CONTAINS ::
Cell[0]: Ghost1 GHOST
DUNGEON[1][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN
Cell[1]: Ghost2 GHOST
DUNGEON[2][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE

~~OUTPUT 5:~~
DUNGEON[1][0] CONTAINS ::
Cell[0]: Ghost2 GHOST
DUNGEON[1][1] CONTAINS ::
Cell[0]: Ghost1 GHOST
DUNGEON[1][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN
DUNGEON[2][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE

~~OUTPUT 6:~~
DUNGEON[1][0] CONTAINS ::
Cell[0]: Ghost2 GHOST
DUNGEON[1][1] CONTAINS ::
Cell[0]: Ghost1 GHOST
Cell[1]: Goblin2 GOBLIN
DUNGEON[1][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN
DUNGEON[2][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE

~~OUTPUT 7:~~
Monster: Ghost1 GHOST AT DUNGEON[1][1] GETS EATEN  UP
Monster: Goblin2 GOBLIN AT DUNGEON[1][1] GETS EATEN  UP
DUNGEON[1][0] CONTAINS ::
Cell[0]: Ghost2 GHOST
DUNGEON[1][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE
DUNGEON[1][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN

~~OUTPUT 8:~~
DUNGEON[1][0] CONTAINS ::
Cell[0]: Ghost2 GHOST
DUNGEON[1][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE
DUNGEON[2][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN

~~OUTPUT 9:~~
DUNGEON[1][0] CONTAINS ::
Cell[0]: Ghost2 GHOST
DUNGEON[1][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE
DUNGEON[2][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN

~~OUTPUT 10:~~
DUNGEON[1][0] CONTAINS ::
Cell[0]: Ghost2 GHOST
DUNGEON[1][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE
DUNGEON[2][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN

~~OUTPUT 11:~~
DUNGEON[1][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE
DUNGEON[1][9] CONTAINS ::
Cell[0]: Ghost2 GHOST
DUNGEON[2][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN

```
• ### 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
}

}
```
```  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]) {
}
else if (a[i] < b[i]) {
}
}
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);
}
}
```
```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.

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.

Also, here are the slides from the textbook.

## Tuesday, October 19, 2010

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

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 removeFriend(Person p) {
friends.removeFriend(p);
p.friends.removeFriend(this);
}

public void addWallMessage(String msg, Person author) {
if (friends.isFriend(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(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);

mark.addWallMessage("Wait a minute! We paid you to build that!", cam);

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
*/
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.

## Friday, October 8, 2010

### Dropbox has More Free Space for Students

If you've been using dropbox.com to sync your files, notice that they are now giving 500MB free space for each referral you make if you are a student (.edu email address), up to 16GB.

## Thursday, October 7, 2010

### HW 5: The Social Network

In light of the popularity of that movie and thus the upcoming demise of its subject (we all know that if Hollywood makes a movie about a computer-related innovation that said innovation is on its way out, see AOL and Virtual Reality) for this homework you will build the a few simple classes for a social network application.

Specifically, you will have `Person`s, each of whom has a name, a status that is either SINGLE, MARRIED, UNKNOWN, or ITS_COMPLICATED, as well as his own `FriendsList` and `Wall` on which others can post messages. A `Person` should have methods for adding a friend X, when we do this then that person is also added to X's friend list (that is, both are now each other's friend). Two persons with the same name (regardless of case) are the same person. Each person appears as a friend only once; trying to add the same person more than once does not do anything. A person can also un-friend other persons, thereby removing both parties from their respective FriendsLists.

We can also add posts to each person's wall, each post has a corresponding author (a Person). Only someone who is a friend of the Person can post on that person's wall.

You can assume that a person has a maximum of 1024 friends, and a maximum of 1024 posts on his wall.

Finally, you will also implement all the appropriate `toString` methods.

For example, the following code:

``` 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(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);

mark.addWallMessage("Wait a minute! We paid you to build that!", cam);

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);

}

```
should print out:
```Mark Zuckerberg SINGLE
0 Friends:
Wall:

Mark Zuckerberg SINGLE
2 Friends:
Cameron Winklevoss
Tyler Winklevoss
Wall:

Tyler Winklevoss MARRIED
1 Friends:
Mark Zuckerberg
Wall:

Mark Zuckerberg SINGLE
2 Friends:
Cameron Winklevoss
Tyler Winklevoss
Wall:
Cameron Winklevoss writes:
Yeah, its a Harvard-only friendster
Tyler Winklevoss writes:
Hello there! We have a project for you!

Tyler Winklevoss MARRIED
1 Friends:
Mark Zuckerberg
Wall:
Mark Zuckerberg writes:
Cool, I'll work on it

Mark Zuckerberg SINGLE
1 Friends:
Peter Thiel
Wall:
Cameron Winklevoss writes:
Yeah ha
Cameron Winklevoss writes:
Wait a minute! We paid you to build that!
Peter Thiel writes:
Sure
Cameron Winklevoss writes:
Hey, how is our social website coming?
Cameron Winklevoss writes:
Yeah, its a Harvard-only friendster
Tyler Winklevoss writes:
Hello there! We have a project for you!

Tyler Winklevoss MARRIED
0 Friends:
Wall:
Mark Zuckerberg writes:
Cool, I'll work on it

Cameron Winklevoss ITS_COMPLICATED
0 Friends:
Wall:
Mark Zuckerberg writes:
I'm unfriending you and your twin
Mark Zuckerberg writes:
Nah hah
Mark Zuckerberg writes:
Its going to take some time, I got finals

Peter Thiel UNKNOWN
1 Friends:
Mark Zuckerberg
Wall:
Mark Zuckerberg writes:
I made this cool website, want to fund me?

ERROR: Cameron Winklevoss is not a friend of Mark Zuckerberg
Mark Zuckerberg SINGLE
1 Friends:
Peter Thiel
Wall:
Cameron Winklevoss writes:
Yeah ha
Cameron Winklevoss writes:
Wait a minute! We paid you to build that!
Peter Thiel writes:
Sure
Cameron Winklevoss writes:
Hey, how is our social website coming?
Cameron Winklevoss writes:
Yeah, its a Harvard-only friendster
Tyler Winklevoss writes:
Hello there! We have a project for you!
```

When done, submit all your files to our dropbox and do so by Tuesday, October 19 @9am.

### Lab 13 - Section 5 -- Manipulation on Arrays

Problem 1 -- Page 529
1) Find Maximum and Minimum of the the Array
2) Find the Frequency of occurrence of each element ( optional )

### Chapter 7 Video

Below is the screencast for Chapter 7. This chapter intoduces the topic of arrays which are variables that can hold an array of different values. All programming languages have arrays; we can't live without them.

### Web Applications: Shameless Plug

If you are interested in building web applications, checkout my 242 class next semester. Because, all applications will be web applications.

### HW 4 Solution

Below is my solution to HW 4: Colors
```
public class Color {

/** The colors are numbers between 0 and 255, inclusive. */
private int red;

private int green;

private int blue;

/** A helper function that returns a number in the 0..255 range.
* @param x the number
* @return x if its in 0..255, 0 if x is negative, 255 otherwise
*/
private int boundColor (int x) {
if (x < 0 ) return 0;
if (x > 255) return 255;
return x;
}

public Color(int red, int green, int blue) {
this.red = boundColor(red);
this.green = boundColor(green);
this.blue = boundColor(blue);
}

public Color() {
this(0,0,0);
}

/** Creates a color, assumes that the arguments are values between 0 and 1.
* @param red
* @param green
* @param blue
*/
public Color (double red, double green, double blue) {
this.red = boundColor((int) (red * 255));
this.green = boundColor((int) (green * 255));
this.blue = boundColor((int) (blue * 255));
}

public Color(String name) {
this(0,0,0); //set all to 0
if (name.equalsIgnoreCase("red")) {
red = 255;
}
else if (name.equalsIgnoreCase("green")) {
green = 255;
}
else if (name.equalsIgnoreCase("blue")) {
blue = 255;
}
}

/** Turns in into a padded hex string. Assumes 0<= n <= 255.
* @param n the number
* @return a string representation of the number, of 2 characters
*/
private String makeHexString(int n) {
String value = Integer.toHexString(n);
if (value.length() < 2) {
return "0" + value;
}
return value;
}

/**
* Returns a color halfway between this one and other
* @param other
* @return a new color that is the average (on RGB) of this color and other
*/
public Color mixWith(Color other) {
Color newColor = new Color((red + other.red) / 2, (green + other.green) / 2, (blue + other.blue) / 2);
return newColor;
}

public String toString() {
return "#" + makeHexString(red) + makeHexString(green) + makeHexString(blue);
}

/**
* @param args
*/
public static void main(String[] args) {
//a constructor with all ints arguments, each is a number between 0 and 255.
Color red = new Color(255,0,0);
System.out.println(red);

//a constructor that understands "red", "green" and "blue".
Color blue = new Color("blue");
System.out.println(blue);
//a constructor with all doubles as arguments, each is a number between 0 and 1.
Color green = new Color(0.0, 1.0, 0.0);
System.out.println(green);
//if a number is out of range you push it back into the range!
Color reallyGreen = new Color(0.0, 100, 0.0);
System.out.println(reallyGreen);

//Mix colors by simply taking the average of each component (RGB).
Color purple = red.mixWith(blue);
System.out.println("purple=" + purple);
purple = purple.mixWith(red);
System.out.println(purple);
purple = purple.mixWith(red);
System.out.println(purple);
}
}
```

## Tuesday, October 5, 2010

### Lab 12 - section 6 - Person class

Problem 9 - page 435 (don't forget to write constructors)

### Lab 12 - Section 5 - Rational Number Class using GCD Calculation

Problem 12 -- Page 436