## 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.

# 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
```"abcde"
"12345"
```
then it should return a String with the value:
```"a1b2c3d4e5"
```
Answer:
```  /**
* 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:
```Columbia:3
Greenville:2
Charleston:1
```
Answer:
```  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:
columbia++;
break; //Don't forget the breaks!
case 864:
greenville++;
break;
case 843:
charleston++;
}
}
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){
super(x,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");
System.out.println(p);
System.out.println(e);
e.merge(p);
System.out.println(e);
p.merge(p);
System.out.println(p);
e.merge(p);
System.out.println(e);
p.addItUp(100);
System.out.println(p);
Enigma e2 = (Enigma)p;
e2.addItUp(500);
System.out.println(e2);
}
}
```
Answer:
```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:
```1
```
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.
Answer:
```  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.

Answer:
```public class Tracker {

private static int totalCount = 0;

private int count;

public Tracker(){
count = 0;
}

public String toString() {
count++;
totalCount++;

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`.

Answer:
```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:

UPS
FEDEX
USPS
Regular
\$10
\$12
\$9
Oversized
\$15
\$22
\$9

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.

Answer:
```  public static double getShippingCosts(Order o){
double basePrice = 0;
switch (o.getCarrier()) {
case UPS:
if (o.oversized())
basePrice = 15;
else
basePrice = 10;
break;
case FEDEX:
if (o.oversized())
basePrice = 22;
else
basePrice = 11;
break;
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

Answer:
```  /**
* 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'){
lengthA++;
};
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') {
count++;
}
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
`90.0`
Alert: Notice that this has to work when the lowest grades match, like in the example above where 3 of them where 0.

Answer:
```  /** 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;
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.

# 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 {
System.out.println("Starting");
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){
System.out.println(e.getMessage());
}
System.out.println("Done");
}

}
```
Answer:
```Starting
Got 5
X is less than 0
Done
```

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.
Answer:
```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:
```123432
3.14151
Ringo
```
write a program that reads those three values from the text file into an integer, double, and string variables, respectively.
Answer:
```import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

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();
inputStream.nextLine();
double d = inputStream.nextDouble();
inputStream.nextLine();
String s = inputStream.next();
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.
Answer:
```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){
System.out.println(GCD.gcd(10,5));
System.out.println(GCD.gcd(10,1));
System.out.println(GCD.gcd(8,6));
System.out.println(GCD.gcd(121,11));
}

}
```

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;
list.add(t);
another.add("Alice");
Test<String,String> justMe = new Test<String,String>();
justMe.add("Bob", "Charlie");
return tt;
}

}
```
Answer:
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
`another.add("Alice");`
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)
{
moves++;
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...

3

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

Notes:

Submit your HanoiTower.java file to espiggy@gmail.com before 4:00pm. No late submission accepted!

## Thursday, November 19, 2009

### Lab 22

Question 8 on Page 850.

Hint:

here is the code of class Spices .

```
import java.util.Scanner;

/**
Class for data on endangered species.
*/
public class Species
{
private String name;
private int population;
private double growthRate;

public void readInput( )
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the species' name?");
name = keyboard.nextLine( );

System.out.println(
"What is the population of the species?");
population = keyboard.nextInt( );
while (population < 0)
{
System.out.println("Population cannot be negative.");
System.out.println("Reenter population:");
population = keyboard.nextInt( );
}

System.out.println("Enter growth rate (% increase per year):");
growthRate = keyboard.nextDouble( );
}

public void writeOutput( )
{
System.out.println("Name = " + name);
System.out.println("Population = " + population);
System.out.println("Growth rate = " + growthRate + "%");
}

/**
Precondition: years is a nonnegative number.
Returns the projected population of the calling object
after the specified number of years.
*/
public int predictPopulation(int years)
{
int result = 0;
double populationAmount = population;
int count = years;
while ((count > 0) && (populationAmount > 0))
{
populationAmount = (populationAmount +
(growthRate / 100) * populationAmount);
count--;
}
if (populationAmount > 0)
result = (int)populationAmount;

return result;
}

public void setSpecies(String newName, int newPopulation,
double newGrowthRate)
{
name = newName;
if (newPopulation >= 0)
population = newPopulation;
else
{
System.out.println("ERROR: using a negative population.");
System.exit(0);
}
growthRate = newGrowthRate;
}

public String getName( )
{
return name;
}

public int getPopulation( )
{
return population;
}

public double getGrowthRate( )
{
return growthRate;
}

public boolean equals(Species otherObject)
{
return (name.equalsIgnoreCase(otherObject.name)) &&
(population == otherObject.population) &&
(growthRate == otherObject.growthRate);
}
}

```

Here is the code from Listing 12.5 on Page 821.

```

public class StringLinkedListSelfContained
{
private ListNode head;

public StringLinkedListSelf( )
{
head = null;
}

/**
Displays the data on the list.
*/
public void showList( )
{
ListNode position = head;
while (position != null)
{
System.out.println(position.data);
position = position.link;
}
}

/**
Returns the number of nodes on the list.
*/
public int length( )
{
int count = 0;
ListNode position = head;
while (position != null)
{
count++;
position = position.link;
}
return count;
}

/**
Adds a node containing the data addData at the
start of the list.
*/
public void addANodeToStart(String addData)
{
head = new ListNode(addData, head);
}

/**
Deletes the first node on the list.
*/
public void deleteHeadNode( )
{
if (head != null)
head = head.link;
else
{
System.out.println("Deleting from an empty list.");
System.exit(0);
}
}

/**
Sees whether target is on the list.
*/
public boolean onList(String target)
{
return find(target) != null;
}

// Returns a reference to the first node containing the
// target data. If target is not on the list, returns null.
private ListNode find(String target)
{
boolean found = false;
ListNode position = head;
while ((position != null) && !found)
{
String dataAtPosition = position.data;
if (dataAtPosition.equals(target))
found = true;
else
position = position.link;
}

return position;
}

public String[] toArray( )
{
String[] anArray = new String[length( )];

ListNode position = head;
int i = 0;
while (position != null)
{
anArray[i] = position.data;
i++;
position = position.link;
}

return anArray;
}

private class ListNode
{
private String   data;
private ListNode link;

public ListNode( )
{
link = null;
data = null;
}

public ListNode(String newData, ListNode linkValue)
{
data = newData;
link = linkValue;
}
}
}

```

## Tuesday, November 17, 2009

### Homework 8 Solution

Below is my solution for the Binary Search Tree:
```public class BinarySearchTree {

private BinarySearchTree left;

private BinarySearchTree right;

private int data;

public BinarySearchTree() {
left = null;
right = null;
}

/** Create a tree that consists of just one node with no children. */
public BinarySearchTree(int data) {
left = null;
right = null;
this.data = data;
}

/** Adds new number n to this BinarySearchTree, placing it in its correct place.
*
* @param n the number to be added
*/
public void add (int n) {
if (n <= data) {
if (left != null)
left.add(n);
else
left = new BinarySearchTree(n);
}
else { // n > data
if (right != null)
right.add(n);
else
right = new BinarySearchTree(n);
}
}

/** Returns the maximum number in this tree. */
public int max() {
if (right == null)
return data;
return right.max();
}

/** Returns the height of this tree. */
public int height() {
//The base cases are when a child is null.
return 1 + Math.max((left == null ? 0: left.height()),
(right == null ? 0: right.height()));
}
}
```

### Homework 9: Sets

For this homework you will implement a simple generic Set class. That is, you will implement a `class Set<T>` using Java's `ArrayList` as the data member that holds the values.

A set is defined as a collection of elements (in our case, all of the same type) such that every element appears at most once in the collection. The methods your `Set<T>` must implement are:

1. `Set()` the constructor takes no arguments and creates an empty set.
2. `String toString()` returns a string with all the elements of this set in printed form, as usual.
3. `void add(T x)` adds element `x` to the set. If `x` is already in the set then it does nothing.
4. `boolean contains(T x)` returns true if the set contains the element `x`, false otherwise.
5. `void add(Set<T> other)` adds the complete contents of the set `other` to this set.
6. `void subtract(Set<T> other)` removes every element of `other` that is in this set.
7. `boolean isSubset(Set<T> other)` returns true if and only if this set is a subset of `other`, that is, if all the elements in this set are also contained in `other`.

You will also implement some test cases in your `main()` to ensure that your class works correctly. This homework is due on Tuesday, November 24 @noon.

### Lab 21

Question 1 on Page 849.

## Thursday, November 12, 2009

### Lab 20

Given an array of unsorted integers, implement a recursive method to find the minimal value.

Input: 3, 7, 12, -3, 6, 0, -1, 23

Output: -3

(Hint: you can refer to the merge sort as listing 11.7)

### Chapter 12: Generics

Below is the screencast for Chapter 12 which talks about generics. The chapter also covers dynamic data structures but we will not be focusing on those, so you can skip those sections if you want, or you can read them and be ready for CSCE 146.
You should watch the screencast before class on Tuesday, November 17. Here are the slides from the textbook:

## Tuesday, November 10, 2009

### Homework 7 Solution

Below is my solution for the Field Notebook homework:
```import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.Scanner;

public class Notebook {

private Reading[] reading;

private int nextIndex = 0;

/** Maximum number of readings. */
private static final int SIZE = 100;

public Notebook(){
reading = new Reading[SIZE];
}

/**
* Creates a notebook by reading its contents from the given file.
* @param filename
* @throws IOException
*/
public Notebook(String filename) throws IOException {
try {
ObjectInputStream input = new ObjectInputStream (new FileInputStream(filename));
nextIndex = input.readInt();
reading = (Reading[])input.readObject();
input.close();
}  catch (ClassNotFoundException e) {
System.out.println("ERROR: File corrupted.");
e.printStackTrace();
}
}

/**
* Adds a reading to the notebook
* @param species name of the species
* @param count how many you saw
* @param comment
* @throws Exception if the notebook gets too big
*/
public void addReading(String species, int count, String comment) throws Exception{
//The right thing to do is use a data structure that expands as needed, but that's CSCE 146
//  so we just crash.
try {
if (nextIndex >= SIZE)
throw new Exception("Too many readings!");
reading[nextIndex] = new Reading(new Date(), species, count, comment);
nextIndex++;
}
catch (NegativeCountException e) {
System.out.println("Sorry, no negative animals allowed.");
}
}

public String toString(){
String result = "";
for(int i=0; i< nextIndex; i++){
result += reading[i].toString() + "\n";
}
return result;
}

/**
* Write this notebook out to a file. It can be read back using the constructor.
* @param filename name of the file
*
*/
public void writeToFile(String filename) {
try {
ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(filename));
out.writeInt(nextIndex);
out.writeObject(reading);
out.close();
} catch (FileNotFoundException e) {
System.out.println("ERROR: No such file. Did not write.");
} catch (IOException e) {
System.out.println("ERROR: IO. Did not write to file.");
}
}

public static void main(String[] args) throws Exception {

Scanner keyboard = new Scanner(System.in);
Notebook notebook = new Notebook();

while (true){
System.out.println("Command list: \n");
System.out.println("r - enter new Reading");
System.out.println("l - List all readings");
System.out.println("o - Open file with readings");
System.out.println("w - Write readings to a file");
System.out.println("q - Quit");
System.out.print("\nEnter command:");
String command = keyboard.nextLine();

if (command.equalsIgnoreCase("r")) {
System.out.print("Species name:");
String species = keyboard.nextLine();
System.out.print("Count:");
int count = Integer.parseInt(keyboard.nextLine());
System.out.print("Comment:");
String comment = keyboard.nextLine();
notebook.addReading(species, count, comment);
}
else if (command.equalsIgnoreCase("l")) {
System.out.println(notebook);
}
else if (command.equalsIgnoreCase("o")) {
System.out.print("Enter name of file to read:");
String filename = keyboard.nextLine();
try {
notebook = new Notebook(filename);
}
catch (FileNotFoundException e) {
System.out.println("ERROR: File " + filename +  " does not exists.");
}
}
else if (command.equalsIgnoreCase("w")) {
System.out.print("Enter name of file to write to:");
String filename = keyboard.nextLine();
notebook.writeToFile(filename);
}
else if (command.equalsIgnoreCase("q")) {
System.out.println("Bye bye.");
System.exit(0);
}
}

}

}

import java.io.Serializable;
import java.util.Date;

public class Reading implements Serializable {

private Date date;

private String species;

private int count;

private String comment;

public Reading(Date date, String species, int count, String comment) throws NegativeCountException {
super();
if (count < 0)
throw new NegativeCountException("There are no negative animals you dummy.");
this.date = date;
this.species = species;
this.count = count;
this.comment = comment;
}

public String toString() {
return date + "\t" + species + "\t" + count + "\t" + comment;
}

}

public class NegativeCountException extends Exception {

public NegativeCountException(String m) {
super(m);
}

}

```

### Lab 19

Question 8 on page 786.

Hint: refer to binary search class and demo on page 777-778.

### Homework 8: Binary Search Trees

A Binary Search Tree is a very commonly used data structure, about which you will learn much more in 146, that stores numbers in a tree where every node has two children (thus, binary). Each node contains a number. All the numbers on the left branch of a node are smaller than that node and, similarly, all the numbers on the right branch of a node are bigger than the node. The figure on the right shows an example.
Below you will find a partial implementation of a binary search tree with three methods missing: `add`, `max`, and `height`. For this homework you will implement these methods.
```public class BinarySearchTree {

private BinarySearchTree left;

private BinarySearchTree right;

private int data;

public BinarySearchTree() {
left = null;
right = null;
}

/** Create a tree that consists of just one node with no children. */
public BinarySearchTree(int data) {
left = null;
right = null;
this.data = data;
}

/** Adds new number n to this BinarySearchTree, placing it in its correct place.
*
* @param n the number to be added
*/
public void add (int n) {
//TODO
}

/** Returns the maximum number in this tree. */
public int max() {
//TODO
}

/** Returns the height of this tree. */
public int height() {
//TODO
}

public String toString() {
return toString("");
}

public String toString(String prefix) {
String result = "";
if (right != null)
result += right.toString(prefix + "-");
else
result += prefix + "- *\n";

result += prefix + " " + data + "\n";

if (left != null)
result += left.toString(prefix + "-");
else
result += prefix + "- *\n";

return result;
}

public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree(8);
tree.add(3);
tree.add(10);
tree.add(1);
tree.add(6);
tree.add(14);
tree.add(4);
tree.add(7);
tree.add(13);
System.out.println(tree);
System.out.println("Max=" + tree.max());
System.out.println("Height=" + tree.height());

}
}
```
The `main` method shown above constructs the tree shown in the figure. After you properly implement the methods, that `main` will run and will print out:
```--- *
-- 14
---- *
--- 13
---- *
- 10
-- *
8
---- *
--- 7
---- *
-- 6
---- *
--- 4
---- *
- 3
--- *
-- 1
--- *

Max=14
Height=4
```
This homework is due Tuesday, November 17 at noon.

## Thursday, November 5, 2009

### Lab 18

Question 1 on Page 744.

Note: only use a text file.

### Chapter 11: Recursion

Chapter 11 deals with the topic of recursion. Recursion is not a language feature, it is simply having a method call itself. All programming languages are capable of recursion. Recursion is a technique that makes certain algorithms (which we do not cover in this class) much easier to write and understand.
You will need to have watched the above screencast by Tuesday, November 10, before class. Here are the slides from the textbook:

## Tuesday, November 3, 2009

### Lab 17

Qestion 2 on Page 673.

## Friday, October 30, 2009

### Chapter 10 Lecture

Below is the screencast for the chapter 10 which deals with reading and writing streams to files. I/O operations like these are slightly different on every programming language, but the basic ideas are the same.

You must have watched the screencast by Tuesday, November 3 before class. The textbook slides are below.

### Homework 7: Field Notebook For this homework you will implement a minimal field notebook, as might be used by a bird or butterfly watcher on the field (on her Android phone, one presumes). Your application will need to implement at least three classes:
1. `Reading` is a specific observation that the user makes. This class has data members
1. `date` of type `Date`, the date of the reading, which you will assign automatically to the current time.
2. `species` is a `String` which is the name of the species of animal the user saw.
3. `count` is an `int` that is the number of animals the user saw.
4. `comment` a `String` comment
2. `Notebook` is a collection of up to 100 readings. It should support, adding a new reading, printing, saving to a file, and reading back from a file.
3. `NegativeCountException` is an `Exception` that you will raise if the user ever tries to enter a negative number of animals. Your program will throw this exception and also catch it, so the program does not crash.

Your program will support the saving of the whole notebook to a file and the subsequent loading of a notebook from a file. The whole thing will be controlled via a text-based interface, as such:

```Command list:

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:r
Species name:swallowtails
Count:3
Comment:Fluttering in the sunshine.
Command list:

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:r
Species name:Jezebel
Count:11
Comment:Hard to count in the daylight.
Command list:

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:l
Fri Oct 30 14:11:31 EDT 2009 swallowtails 3 Fluttering in the sunshine.
Fri Oct 30 14:12:02 EDT 2009 Jezebel 11 Hard to count in the daylight.

Command list:

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:r
Species name:Duke of Burgundy
Count:1
Comment:Did not expect to see this one here!
Command list:

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:l
Fri Oct 30 14:11:31 EDT 2009 swallowtails 3 Fluttering in the sunshine.
Fri Oct 30 14:12:02 EDT 2009 Jezebel 11 Hard to count in the daylight.
Fri Oct 30 14:12:37 EDT 2009 Duke of Burgundy 1 Did not expect to see this one here!

Command list:

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:w
Enter name of file to write to:notebook.dat
Command list:

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:l
Fri Oct 30 14:11:31 EDT 2009 swallowtails 3 Fluttering in the sunshine.
Fri Oct 30 14:12:02 EDT 2009 Jezebel 11 Hard to count in the daylight.
Fri Oct 30 14:12:37 EDT 2009 Duke of Burgundy 1 Did not expect to see this one here!

Command list:

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:q
Bye bye. //at this point the program stops.

//we start it again
Command list:

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:l

Command list:

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:o
Enter name of file to read:notebook.dat
Command list:

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:l
Fri Oct 30 14:11:31 EDT 2009 swallowtails 3 Fluttering in the sunshine.
Fri Oct 30 14:12:02 EDT 2009 Jezebel 11 Hard to count in the daylight.
Fri Oct 30 14:12:37 EDT 2009 Duke of Burgundy 1 Did not expect to see this one here!

Command list:

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:r
Species name:Speckled wood
Count:200
Comment:A gaggle of butterflies.
Command list:

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:l
Fri Oct 30 14:11:31 EDT 2009 swallowtails 3 Fluttering in the sunshine.
Fri Oct 30 14:12:02 EDT 2009 Jezebel 11 Hard to count in the daylight.
Fri Oct 30 14:12:37 EDT 2009 Duke of Burgundy 1 Did not expect to see this one here!
Fri Oct 30 14:14:53 EDT 2009 Speckled wood 200 A gaggle of butterflies.

Command list:

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:r
Species name:zabulon skipper
Count:-1
Comment:lets try this
Sorry, no negative animals allowed.
Command list:

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:o
Enter name of file to read:thisfilenamedoesnotexist.dat
ERROR: File thisfilenamedoesnotexist.dat does not exists.
Command list:

r - enter new Reading
l - List all readings
o - Open file with readings
w - Write readings to a file
q - Quit

Enter command:q
Bye bye.

```

This homework is due Tuesday, November 10 @noon.

## Thursday, October 29, 2009

### Lab test 2 review

Today we will have review for lab test 2. No lab assignment.

### Section 005: Lab test 2 sample codes

```public class Drink
{
private String name;
private String brand;
private double calories;

public Drink()
{
name = "";
brand = "";
calories = 0;
}

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

public String getName()
{
return name;
}

public void setBrand(String s)
{
brand = s;
}

public String getBrand()
{
return brand;
}

public void setCal(double i)
{
calories = i;
}

public double getCal()
{
return calories;
}

public void printInfo()
{
System.out.println("Name: " + name);
System.out.println("Brand: " + brand);
System.out.println("Calories: " + calories);
}

}

```
```public class FruitJuice extends Drink
{
private double fruitPercentage;
private String fruit;

public FruitJuice()
{
super();
fruitPercentage = 0;
fruit = "";
}

public void setFruitPercentage(double fruit)
{
fruitPercentage = fruit;
}

public double getFruitPercentage()
{
return fruitPercentage;
}

public void setFruit(String s)
{
fruit = s;
}

public String getFruit()
{
return fruit;
}

public void printInfo()
{
super.printInfo();
System.out.println("Fruit Percentage: " + fruitPercentage + "%");
System.out.println("Fruit: " + fruit);
}

}

```
```public class Soda extends Drink
{
private double caffinePercent;

public Soda()
{
super();
caffinePercent = 0;
}

public void setCaffinePercent(double caffine)
{
caffinePercent = caffine;
}

public double getCaffinePercent()
{
return caffinePercent;
}

public void printInfo()
{
super.printInfo();
System.out.println("Caffine Percent: " + caffinePercent + "%");
}

}

```
```import java.util.Scanner;

public class DrinkList
{

public static String lowestCalorie(Drink[] drinks)
{
Drink drink = drinks;

for(int i = 0; i < drinks.length; i++)
{
if(drinks[i].getCal() <= drink.getCal())
{
drink = drinks[i];
}
}

String lowest = drink.getName();
return lowest;
}

public static void printAll(Drink[] drinks)
{
for(int i = 0; i < drinks.length; i++)
{
drinks[i].printInfo();
System.out.println();
}
}

public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);

boolean run = true;

System.out.println("How many drinks will you be entering?");
int num = keyboard.nextInt();
System.out.println();

Drink[] drinks = new Drink[num];

for(int i = 1; i <= num; i++)
{
keyboard.nextLine();

System.out.println("Information on Drink " + i + ": ");

System.out.print("Type of Drink (Soda or Fruit) ");
String type = keyboard.nextLine();

System.out.print("Enter " + type + "'s name: ");
String name = keyboard.nextLine();

System.out.print("Enter " + name + "'s brand: ");
String brand = keyboard.nextLine();

System.out.print("Enter " + name + "'s calories: ");
double calories = keyboard.nextDouble();
keyboard.nextLine();

if(type.equalsIgnoreCase("Soda"))
{
System.out.print("Enter the percentage of caffine in " + name + ": ");
double caffine = keyboard.nextDouble();

Soda soda = new Soda();

soda.setName(name);
soda.setBrand(brand);
soda.setCal(calories);
soda.setCaffinePercent(caffine);

drinks[i - 1] = soda;

}
else if(type.equalsIgnoreCase("Fruit"))
{
System.out.print("Enter the fruit in " + name + ": ");
String fruit = keyboard.nextLine();

System.out.print("Enter the  percentage vitamin (Daily value) in " + name + ": ");
double vitamin = keyboard.nextDouble();

FruitJuice juice = new FruitJuice();

juice.setName(name);
juice.setBrand(brand);
juice.setCal(calories);
juice.setFruit(fruit);
juice.setFruitPercentage(vitamin);

drinks[i - 1] = juice;

}
else
{
System.out.println("Sorry, but I didn't recognize the kind of drink.");
System.out.println("Next time put the type in right.");
i--;
}

System.out.println();
}

String option = keyboard.nextLine();

do
{
System.out.println("Enter choice (\"Lowest Calorie\", \"PrintAll\", or \"exit\" ): ");
option = keyboard.nextLine();

if(option.equalsIgnoreCase("Lowest Calorie"))
{
System.out.println(lowestCalorie(drinks));
}
else if(option.equalsIgnoreCase("PrintAll"))
{
printAll(drinks);
}
else
{
System.out.println("Please enter one of the available commands.");
}

}while(!option.equalsIgnoreCase("Exit"));

System.out.println("Thanks for using the program. :)");

}

}

```

### Chapter 9 Lecture

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.
You must have watched this screencast by Tuesday, November 3.

## Tuesday, October 27, 2009

### Test 2

Here is our second test along with the answers to each question:
1. (20%) The following program

```  public static void main (String[] args){
//create animal with name "bunny" and weight of 10
Animal bunny = new Animal("bunny", 10);
Animal fox = new Animal();
System.out.println(fox);
System.out.println(bunny);
bunny.feed(4);
System.out.println(bunny);

}
```
prints out the following when run (every `println` in the code above corresponds to one line below):

```name: weight:-1
name:bunny weight:10
name:bunny weight:14
```
Implement the missing `Animal` class so that it works as shown.

Answer:
```public class Animal {

private String name;

private int weight;

public Animal (){
name = "";
weight = -1;
};

public Animal (String n, int w){
name = n;
weight = w;
}

public String toString(){
String result = "name:" + name + " weight:" + weight;
return result;
}

public void feed(int amount){
weight += amount;
}

}
```

2. (20%) What does the following program print out when run?

```public class Counter {

public static int alpha;

public int beta;

public Counter (){
alpha = 5;
beta = 10;
}

public void increase() {
alpha = alpha + 1;
beta = beta + 1;
}

public String toString() {
return "alpha=" + alpha +"  beta=" + beta;
}

public static void main(String[] args){
Counter x = new Counter();
Counter y = new Counter();
System.out.println(x);
System.out.println(y);
x.increase();
System.out.println(x);
System.out.println(y);
Counter z = new Counter();
System.out.println(z);
System.out.println(x);
}

}
```
Answer:
```alpha=5  beta=10
alpha=5  beta=10
alpha=6  beta=11
alpha=6  beta=10
alpha=5  beta=10
alpha=5  beta=11

```

3. (20%) In the game of chess the rook can capture other pieces that are in his same row or in his same column. Implement a function which, given a 2-dimensional array of integers and a row and column position, returns true if there are any non-zero numbers on the same row or on the same column. For example, the following program:

```public class Rook {

public static void main(String[] args){
int[][] board = new int;
for (int i=0; i < 8; i++){
int[] col = {0,0,0,0,0,0,0,0};
board[i] = col;
}

board = 1;

//root has a kill if there is a non-zero number anywhere in row 1, or in column 2.
if (rookCanKill(board,1,2))
System.out.println("Root has kill at 1,2");
else
System.out.println("Root cannot kill at 1,2");

//root has a kill if there is a non-zero number anywhere in row 2, or in column 2.
if (rookCanKill(board,2,2))
System.out.println("Root has kill at 2,2");
else
System.out.println("Root cannot kill at 2,2");
}

}
```
prints out:

```Root has kill at 1,2
Root cannot kill at 2,2
```
Implement the public static boolean rookCanKill(int[][] board, int row, int col) function.

Answer:
```  public static boolean rookCanKill(int[][] board, int x, int y){
for (int i=0; i < board.length; i++)
if (board[x][i] != 0) return true;
for (int i=0; i < board.length; i++)
if (board[i][y] != 0) return true;
return false;
}

```

4. (20%) What does the following program print out when we run its `main`?

```public class A {

public A (){
System.out.println("Creating A");
}

public void talk (){
System.out.println("I am A!");
}

public void whine(){
System.out.println("I am Always last.");
}

public void whine(int x){
System.out.println("Am I late?");
}

}
```
```public class B extends A{

public B (){
System.out.println("Creating B");
}

public void talk (){
System.out.println("I am B!");
}

public void whine(){
System.out.println("I am Bored.");
}

}
```
```public class C extends B{

public C (){
System.out.println("Creating C");
}

public void talk (){
System.out.println("I am C!");
}

public void whine(){
System.out.println("I am Cursed.");
super.whine();
}

public void whine(int x){
System.out.println("I am Crazy.");
whine();
}

public static void main(String[] args){
C c = new C();
c.talk();
c.whine();
B b = (B) c;
b.talk();
b = new B();
b.whine();
}

}
```
Answer:
```Creating A
Creating B
Creating C
I am C!
I am Cursed.
I am Bored.
I am C!
Creating A
Creating B
I am Bored.
```

5. (20%) Write some code which creates an array and populates it with the day of the month for all the days of a non-leap year. That is, given that the months have the following number of days:

Month
Days
January
31
February
28
March
31
April
30
May
31
June
30
July
31
August
31
September
30
October
31
November
30
December
31

you will create an array `dayNumber` which has the number of the day of the month for each day of the year, as such:

```dayNumber = 1
dayNumber = 2
:
dayNumber = 31
dayNumber = 1  //February first
dayNumber = 2
:
dayNumber = 28
dayNumber = 1
:
:
dayNumber = 31
```
You will not receive credit for writing down 365 assignment statements, or for writing an array literal with each of the 365 values in it. You should use a for-loop. Hint: use an array literal to store the number of days in each month.

Answer:
```public class Days{

public static void main(String[] args){
int[] dayNumber = new int;
int[] daysInMonth = {31,28,31,30,31,30,31,31,30,31,30,31};
int day = 1;
int month = 0;
int i = 0;
while (month < daysInMonth.length){
dayNumber[i] = day;
i++;
day++;
if (day > daysInMonth[month]){
day = 1;
month++;
}
}
//print it out
for (i=0;i<dayNumber.length;i++)
System.out.println(i + " " + dayNumber[i]);
}

}
```

The grade distribution for this test is shown in the graph below.

### Lab test 2 for Section 006

Write a program that basically simulates a poker game.

You need to implement:

Card class

type: spades, diamond, club, heart

value: A, 2, 3, ..., J, Q, K (you can use 1 to 13)

a constructor to set the type and value

getType, getValue

CompareTo(Card anotherCard)

// compare the value first

// if they are equal, compare the type(spades > diamond > club > heart)

toString() // type and value in the range 1 to 13 if you use integer

Player class

player's name

an array of 5 cards

giveCard(Card p) // give a card to this player

getMaxIndex() // get the index of the maximum card

getCardByIndex(int i) // get cards[i]

toString()

PokerGame class

Test your previous two classes. There is no extra credits for those who write a friendly UI using Scanner class.

1. Create a set of cards(52 cards without joker, use loop to assign the values and types)

2. Create 2 players

3. Give each player 5 cards randomly, print out the cards of each player by calling toString()

4. Get the max card of each player and compare

Hints:

1. You may use an array of 52 length to mark if the corresponding card is given out.

2. Use the following code to generate a random number if you need.

Random rand = new Random();

int num = rand.nextInt(10); // returns a integer from 0 to 9

System.out.println((num+1));

You can add more data members and methods in your classes if you think they are helpful. But you may lose credits if they are harmful to your structure of the class.

Please send your program to xusun09@gmail.com no later than 6:00pm today, and use "CSCE145-LABTEST2-NAME" as the subject.

### Lab test 02 for Section 005

The Drink.java class is the super class. It has set and get methods for the attributes name, brand, calories. The Soda and FruitJuice classes inherit the Drink class. The soda class has attributes caffeine percentage. The FruitJuice has attributes vitaminPercentage and fruit. Add a printInfo method in the Drink class and then override that method in the subclasses.

The DrinkList.java will contain your main method, which is where you will declare your array of Drink items, and control execution. In addition, the DrinkList class has 2 methods:

1) printDrinkWithLowestCalories (Drink[] drink) searches the array for the drink with Lowest calories and prints it's name and brand.

2) printAll(Drink[] drink prints the information of all (this includes Soda and FruitJuice information) drinks stored in the array.

here is the sample output:

Please enter the number of drinks to be read: 2

Data For Drink 1:

Type of Drink (Soda/Fruit)? Soda

Enter Soda's name: Sierra Mist

Enter Sierra Mist's brand: Pepsi Co

Enter calories for Sierra Mist: 150

Enter percentage caffeine for Sierra Mist : 0

Data For Drink 2:

Type of Drink (Soda/Fruit)? Fruit

Enter Name: Orange juice

Enter the brand name of Orange Juice: Tropicana

Enter calories of Tropicana: 240

Enter Tropicana's fruit: Orange

Enter Tropicana's percentage vitamin (Daily value): 100

Enter choice ("Low Calorie" or "PrintAll" or "exit" ): Low Calorie

Sierra Mist

Enter choice ("Low Calorie" or "Brand" or "exit" ): exit

Thank you for using the program.

HINT: declare printAll(Drink[] drink) as static method in DrinkList class like this:

public static void/String printAll(Drink[] drink)

NOTE: submit your program before 4:00pm to espiggy@gmail.com. NO late submittion accepted!!

## Monday, October 26, 2009

### ACM Fall Brawl

Our ACM student chapter (you should join, if you are a Computer major) is holding their annual Fall Brawl: a fighting videogame tournament. It is only \$5 to participate and there will be prizes.

## Thursday, October 22, 2009

### Sudoku Example from Class

You will probably need some extra time to digest the example I did in class, so I am posting it here. It successfully ran two test cases so it must be correct, of course (NOT).
```
public class Sudoku {

/** 0 means box is blank, otherwise only numbers 1..9 are allowed */
private int[][] board = new int;

public Sudoku(){
board = 1;
//  board = 1;

}

/** @return true if theBoard[rowoffset..rowoffset+2][coloffset..coloffset+2]
* does not contain more than one copy of 1..9. That is, if the 3x3
* box is a legal subbox
*/
private boolean isLegalBox(int[][] theBoard, int rowOffset, int colOffset){
boolean[] check = new boolean;
for (int row = rowOffset; row < rowOffset + 3; row++){
for (int col =colOffset; col < colOffset + 3; col++){
if (board[row][col] == 0)
continue;
if (check[ board[row][col] ])
return false;
else
check[ board[row][col] ] = true;
}
}
return true;
}

public boolean isLegalBoard(int [][] theBoard){

//check all rows
for (int row = 0; row < 9; row++){
boolean[] check = new boolean;
for (int i =0; i < 10; i++)
check[i] = false;
for (int col =0; col < 9; col++){
if (board[row][col] == 0)
continue;
if (check[ board[row][col] ])
return false;
else
check[ board[row][col] ] = true;
}
}

//check all columns
for (int col = 0; col < 9; col++){
boolean[] check = new boolean;
for (int i =0; i < 10; i++)
check[i] = false;
for (int row =0; row < 9; row++){
if (board[row][col] == 0)
continue;
if (check[ board[row][col] ])
return false;
else
check[ board[row][col] ] = true;
}
}

//check all 9 boxes
for (int row = 0; row < 9; row+=3){
for (int col =0; col < 9; col+=3){
if (! isLegalBox(theBoard, row, col))
return false;
}
}

return true;
}

public boolean isLegal(){
return isLegalBoard(board);
}

public String toString(){
String result = "";
for (int row = 0; row < 9; row++){
for (int col =0; col < 9; col++){
result += Integer.toString(board[row][col]) + " ";
}
result += "\n";
}
return result;
}
}

```

### Lab 16 Define a Class named Product whose objects are records for a department. A Product has the id number (use type String). Define a Class named Book. Derive this class from Product. You can define the attributes of Book. For example, A Book object has the id (defined in Product class), the book name (use type String) and the price (use type double). Define another Class named Shirt. Derive this class from Product. Define the attributes of Shirt. For example, A Shirt object has the id (defined in Product class), the color (use type String), and the size (use type String). Give your classes a reasonable complement of constructions and accessor methods, and a toString() methods which can display the infomation of product in the cart.

Define a Class named Cart whose objects are records for customer. A customer has the contents which is the array of Product in the cart. Give your classes a reasonable complement of constructions and accessor methods, a add mothods with product object as parameter which can add the product to your cart (the array of product), and a toString() methods which can display the infomation of all product in the cart

## Tuesday, October 20, 2009

### Lab 15

Question 5 on page 608.

## Monday, October 19, 2009

### HW5 example

```// FifteenPuzzle.java
public class FifteenPuzzle {
private int[][] board;
private int blank_x;
private int blank_y;

public FifteenPuzzle()
{
this.board = new int;
int num = 1;
for (int i=0; i<4; ++i)
for (int j=0; j<4; ++j)
{
this.board[i][j] = num++;
}
this.blank_x = 3;
this.blank_y = 3;
}

public String toString()
{
String strBoard="";
for (int i=0; i<4; ++i)
{
for (int j=0; j<4; ++j)
{
if (this.board[i][j]==16)
strBoard += "   ";
else
strBoard += String.format("%3d",this.board[i][j]);
}
strBoard += "\n";
}
return strBoard;
}

public boolean moveUp()
{
if (this.blank_x>0)
{
int temp = this.board[blank_x][blank_y];
this.board[blank_x][blank_y]=this.board[blank_x-1][blank_y];
this.board[blank_x-1][blank_y]=temp;
this.blank_x--;
return true;
}
return false;
}

public boolean moveDown()
{
if (this.blank_x<3)
{
int temp = this.board[blank_x][blank_y];
this.board[blank_x][blank_y]=this.board[blank_x+1][blank_y];
this.board[blank_x+1][blank_y]=temp;
this.blank_x++;
return true;
}
return false;
}

public boolean moveLeft()
{
if (this.blank_y>0)
{
int temp = this.board[blank_x][blank_y];
this.board[blank_x][blank_y]=this.board[blank_x][blank_y-1];
this.board[blank_x][blank_y-1]=temp;
this.blank_y--;
return true;
}
return false;
}

public boolean moveRight()
{
if (this.blank_y<3)
{
int temp = this.board[blank_x][blank_y];
this.board[blank_x][blank_y]=this.board[blank_x][blank_y+1];
this.board[blank_x][blank_y+1]=temp;
this.blank_y++;
return true;
}
return false;
}

public boolean isWinner()
{
int num = 1;
for (int i=0; i<4; ++i)
for (int j=0; j<4; ++j)
{
if (this.board[i][j] != num++)
return false;
}
return true;
}
}

// Demo.java
// report bugs to xusun09@gmail.com

import java.util.Scanner;
public class Demo {

public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
FifteenPuzzle fp = new FifteenPuzzle();

System.out.println(fp.toString());
System.out.println("Enter command or 'done' to finish");

while(true)
{
System.out.print("Enter command (u,d,l,r):");
String command = reader.nextLine().toLowerCase();
if (command.equals("u"))
fp.moveUp();
else if (command.equals("d"))
fp.moveDown();
else if (command.equals("l"))
fp.moveLeft();
else if (command.equals("r"))
fp.moveRight();
else if (command.equals("done"))
break;
System.out.println(fp.toString());
if (fp.isWinner())
System.out.println("WINNING BOARD!!\n");
}
}
}

```

## Thursday, October 15, 2009

### Homework 6: Media Library

For this homework you will implement a series of Java classes which are meant to be at the heart of a media library program (like iTunes). The diagram above is a UML diagram. Your textbook explains these diagrams in detail starting in page 559. You will implement all the classes described in the above diagram along with their respective attributes and methods
There are some some further requirements:
1. Each of the leaf classes must implement a `toString` that adds all the information particular to that class to the string, and that calls the parent `toString` method to get the common parts. For example, only movies have a rating but all media has a title.
2. Every class should have two constructors (these are not shown in the UML diagram): one that takes no arguments and sets values to the empty string, 0, or equivalent, and one that takes all the arguments for that class. Constructors should call the parent constructor when appropriate.
3. The movie ratings are only one of:G, PG, PG-13, R, NC-17, X. You must implement set/get methods to ensure no one can set the rating to something else.
4. The `equals` method in `Media` only test that the titles are the same, but the one in `Song` also tests that the artists are the same.
5. You must also write a `main` method that tests all your classes and their methods.
This homework is due by noon on Thursday, October 22.

### Lab 14

Question 4 on page 608.

## Tuesday, October 13, 2009

### Lab 13

Quesiton 2 on page 529.

## Monday, October 12, 2009

### HW4 example

```// Vector.java
public class Vector {
private double dx,dy;

public Vector(double _x, double _y)
{
this.dx = _x;
this.dy = _y;
}
public void addVector(Vector otherVector)
{
this.dx += otherVector.dx;
this.dy += otherVector.dy;
}
public void subtractVector(Vector otherVector)
{
this.dx -= otherVector.dx;
this.dy -= otherVector.dy;
}
public void multiply(int a)
{
this.dx *= a;
this.dy *= a;
}
public double getMagnitude()
{
return Math.sqrt(dx*dx+dy*dy);
}
public void normalize()
{
double magnitude = getMagnitude();
if (magnitude==0)
return;
this.dx /= magnitude;
this.dy /= magnitude;
}
public String toString()
{
return ("("+Double.toString(this.dx)+", "+Double.toString(this.dy)+")");
}

}

//VectorDemo.java
public class VectorDemo {

public static void main(String[] args) {
// TODO Auto-generated method stub
Vector v1 = new Vector(3,4);
System.out.println(v1.toString());
v1.multiply(3);
System.out.println(v1.toString());
Vector v2 = new Vector(6, 8);
v1.subtractVector(v2);
System.out.println(v1.toString());
v1.normalize();
System.out.println(v1.toString());
}

}
```

## Tuesday, October 6, 2009

### Homework 5: The Fifteen Puzzle In the fifteen puzzle you are given a board with embedded tiles, numbered 1 to 15, which can only be moved up, down, left, or right to occupy the one blank spot. That is, you can only move a tile that is a neighbor of the blank spot. Another way of looking at it is to say that you can only move the blank spot up, down, left or right, exchanging it with the tile that is already in that position.

For this homework you will implement a FifteenPuzzle class that has the following methods:

1. A constructor that initializes the board to the solved position, with the blank on the bottom left, as shown in the figure.
2. A `toString()` method which prints a pretty board, like the ones shown below.
3. The methods `moveUp`, `moveDown`, `moveLeft`, and `moveRight` which move the empty space up, down, left, and right, respectively. The functions should do nothing if called with a board configuration that would make it impossible to execute the action. For example, if the space is in the bottom right and we ask it to `moveDown` it should stay there. The program should not crash.
4. The method `isWinner` which returns true if the board is in its initial configuration.

You will also implement a `main` function that asks the user which way he would like to move the tile and then performs the move, by calling one of the `moveX` methods, and displays the new board. Below is a sample interaction with the program:

``` 1  2  3  4
5  6  7  8
9 10 11 12
13 14 15

Enter command or 'done' to finish
Enter command (u,d,l,r):u
1  2  3  4
5  6  7  8
9 10 11
13 14 15 12

Enter command (u,d,l,r):r
1  2  3  4
5  6  7  8
9 10 11
13 14 15 12

Enter command (u,d,l,r):l
1  2  3  4
5  6  7  8
9 10    11
13 14 15 12

Enter command (u,d,l,r):r
1  2  3  4
5  6  7  8
9 10 11
13 14 15 12

Enter command (u,d,l,r):d
1  2  3  4
5  6  7  8
9 10 11 12
13 14 15

WINNING BOARD!!

Enter command (u,d,l,r):l
1  2  3  4
5  6  7  8
9 10 11 12
13 14    15

Enter command (u,d,l,r):l
1  2  3  4
5  6  7  8
9 10 11 12
13    14 15

Enter command (u,d,l,r):u
1  2  3  4
5  6  7  8
9    11 12
13 10 14 15

Enter command (u,d,l,r):u
1  2  3  4
5     7  8
9  6 11 12
13 10 14 15

Enter command (u,d,l,r):r
1  2  3  4
5  7     8
9  6 11 12
13 10 14 15

Enter command (u,d,l,r):d
1  2  3  4
5  7 11  8
9  6    12
13 10 14 15

Enter command (u,d,l,r):done

```

You must use a 2-dimensional array to implement the board. This homework is due by Thursday, October 15 @ noon.

Tip: To turn an integer into a string that is padded on the left with enough spaces to ensure it is of length at least 3, use `String iAsPaddedString = String.format("%3d",i);` where `i` is the integer.

For hackers only: write a method that solves the puzzle. A good way to do it is using the A-star algorithm. You will learn all about this and other search algorithms if you take our Artificial Intelligence class (CSCE 580)

### Chapter 8 Lecture

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. You must have watched this screencast by Tuesday, October 13.

Also, here are the slides from the textbook.

### Lab 12

Quesiton 1 on page 529.

Have fun!

NOTE: For section 005 (the 2pm section), today's lab has been moved from B205 to Swearingen 1D29 !!!!

## Friday, October 2, 2009

### Chapter 7 Lecture

Below is the screencast for Chapter 7, which you must have watched by Tuesday, October 6. This chapter intoduces the topic of arrays which are variables that can hold an array of different values. All programming languages have arrays.

Here are the textbook slides for this chapter.

## Thursday, October 1, 2009

### Lab 11

Question 9 on Page 330.

Have fun!

## Wednesday, September 30, 2009

### Homework 4: Vectors A vector in 2-dimensional space, as used in math an physics, is just a pair of numbers: delta-x and delta-y. We call these numbers the components of the vector. Vectors are drawn as arrows. For example, the vector in the figure has a delta-x of 2, and a delta-y of 3. In physics, vectors represent forces. Adding two vectors represents placing those two forces on an object. The resulting force is just the addition of the two vectors. You can add two vectors by simply adding their delta-x and delta-y values. That is, the new delta-x is the sum of the delta-x of the two other vectors.
More formally, for vectors `v1` and `v2` with components `v1.dx`, `v1.dy` and `v2.dx`, `v2.dy`, we can define various vector operations:
• Vector addition: `v1 + v2 = v3` is implemented as `v3.dx = v1.dx + v2.dx` and `v3.dy = v1.dy + v2.dy`
• Vector subtraction: `v1 - v2 = v3` is implemented as `v3.dx = v1.dx - v2.dx` and `v3.dy = v1.dy - v2.dy`
• Vector scalar multiplication: `v1 * c = v2` where `c` is a constant is implemented as `v2.dx = v1.dx * c` and `v2.dy = v1.dy * c`
• Vector magnitude of `v1` is a number equal to the square root of `v1.dx*v1.dx + v1.dy*v1.dy`.
• A vector `v1` can be normalized by setting `v1.dx = v1.dx / v1.magnitude` and `v1.dy = v1.dy / v1.magnitude`
For this homework you will implement a `Vector` class that has the following data members:
1. dx, a double
2. dy, a double
and the following methods:
1. A constructor that takes as argument two numbers which will become the delta-x and delta-y
2. `public void addVector(Vector otherVector)` which adds `otherVector` to this vector
3. `public void subtractVector(Vector otherVector)` which subtracts `otherVector` from this vector
4. `public void multiply(int a)` does a scalar multiplication of this vector by `a`
5. `public double getMagnitude()` returns the magnitude of this vector.
6. `public void normalize()` normalizes this vector.
7. `public String toString()` returns a printable version of the vector.

You must also implement a `main` function that tests all your methods to make sure they are correct.

One very important rule you must follow is Don't Repeat Yourself (DRY) which means that:

“Every piece of knowledge must have a single, unambiguous, authoritative representation within a system ”
In other words, any value that can be calculated from data member values must be calculated from data members values. This homework is due Tuesday, October 6 @ noon.

### lab test 1 demo for sec 6

```import java.util.Scanner;

public class Labtest1demo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader = new Scanner(System.in);
String input = reader.nextLine();
for (int i=0; i<input.length(); ++i)
{
if (i==0)
{
if (input.charAt(i)=='A' && input.charAt(i+1)==' ')
System.out.print("ONE");
else System.out.print(input.charAt(i));
}
else if (i==input.length()-1 && input.charAt(i)=='a' &&
input.charAt(i-1)==' ')
{
System.out.print("one");
}
else if (input.charAt(i)=='a' && input.charAt(i-1)==' ' &&
input.charAt(i+1)==' ')
{
System.out.print("one");
}
else System.out.print(input.charAt(i));
}

}

}

```

## Tuesday, September 29, 2009

### Test 1 Solutions and Grades

Below is our first test, along with the answers.
1. (10%) The following program fails to compile. Why does it fail to compile?
```public class BrokenA {
public static final double RATE = 0.5;

public static void main(String[] args) {
double x = 0;
x = 10 * RATE;
RATE = 20;
}
}
```
Answer: Because we are trying to re-set the value of `RATE` which is a `final` variable.

2. (40%) What does the program below print when it runs?
```import java.util.Scanner;

public class Mystery {

public static void main(String[] args) {
String sentence = "A rebel without a clue";
for (int i = 0; i < sentence.length(); i++){
char c = sentence.charAt(i);
int r = 0;
for (int j = 0; j < sentence.length(); j++){
if (sentence.charAt(j) == c)
r++;
}
System.out.println(c + ":" + r);
}
}

}
```
Answer:
```A:1
:4
r:1
e:3
b:1
e:3
l:2
:4
w:1
i:1
t:2
h:1
o:1
u:2
t:2
:4
a:1
:4
c:1
l:2
u:2
e:3
```

3. (50%) Write a program that:
1. Asks the user to enter any number of words. If the user enters the word done then the program ends. You can assume the user will always enter a word (he will not type in spaces, numbers, etc.)
2. After the user enters each word you will print out a score such that:
1. If a word has 9 or fewer letters the score is 2 times the number of letters.
2. If a word has 10 or more letters the score is 10 plus 2 times the number of letters.
3. If a word starts with the letter 'z' then it gets a score of 500, regardless of how many letters it has.
4. After the user enters done, you print out the longest word.

Below is a sample session:
```Enter word:hello
Score=10
Enter word:howareyouthere
Score=38
Enter word:a
Score=2
Enter word:z
Score=500
Enter word:zoologically
Score=500
Enter word:done
The longest word was howareyouthere
```
Answer:
```import java.util.Scanner;

public class WordChecker {

public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String longest = "";
while  (true){
System.out.print("Enter word:");
String word = keyboard.next();
if (word.equalsIgnoreCase("done"))
break;
System.out.print("Score=");
if (word.substring(0,1).equalsIgnoreCase("z"))
System.out.println(500);
else if (word.length() > 10)
System.out.println(10 + 2*word.length());
else
System.out.println(2*word.length());
if (word.length() > longest.length())
longest = word;
}
System.out.println("The longest word was " + longest);
}
}
```

Below is the grade distribution for this test. The zeros are people who did not take the test. I will be handing back the tests on our next class.

### lab test 1

From a given string, replace all instances of 'a' with 'one' and 'A' with 'ONE'.

Example Input: " A boy is playing in a garden"

Example Output: " ONE boy is playing in one garden"

-- Not that 'A' and 'a' are to be replaced only when they are single characters, not as part of another word.

-- You cannot use "replace" or "replaceAll"

### Lab Test 01

For today's lab test, you need to write a Java program Calculator.java, that takes as input a simple mathematical expression and evaluates the expression. A simple mathematical expression contains two operands that will be input individually. You need to implement the addition, subtraction and multiplication on integers in your program. Note that the user input is NOT case sensitive, which means "Add" or "ADD" are all valid input. In addition, you need to count the number of completed calculations performed, and output this when the user quits the program.

Example Output

Welcome to the Calculator program.

Please enter your name:

Yi

Yi, please enter "Add" for addition, "Minus" for subtraction, "Multiply" for multiplication, or "Exit" to quit :

Add

Enter the first number:

2

Enter the second number:

22

The value of 2 + 22 is:

24

Yi, please enter "Add" for addition, "Minus" for subtraction, "Multiply" for multiplication, or "Exit" to quit :

multiply

Enter the first number:

3

Enter the second number:

5

The value of 3 * 5 is:

15

Yi, please enter "Add" for addition, "Minus" for subtraction, "Multiply" for multiplication, or "Exit" to quit :

Addd

Error: Addd is an invalid input

Yi, please enter "Add" for addition, "Minus" for subtraction, "Multiply" for multiplication, or "Exit" to quit :

Exit

Yi completed 2 calculation.

Thank you for using the program. Goodbye.

File you must submit to xian@engr.sc.edu before the lab ends (29th, Sep. 4:00 pm):

Calculator.java

No late submission accepted!

Good luck!