home  |  homework  |  labs

A Note on Homework 5

There is a flaw in the generic matrix problem. The problem is hereby suspended; you may cease working on it. You will be able to submit the project for extra credit: details in "Homework 6" below.

Homework 6

Assigned Friday, 5/12; due in class Thurs, 5/25.

Submission: paper submission only. For question 1, submit the sketch from A, the CREATEs from B, and the SELECTs and their descriptions from D. For question 2, submit the DatabaseDropdown class and a printout of one (short) test run, showing that it works with your database. For question 3, submit the Fraction class.

1) Database Design

You have been hired by the administration of a brand new liberal arts college to build a faculty database. The faculty is organized into a standard set of departments: English, Math, Classics, and so on. The college has hired faculty members, and each has been asked to propose courses they would like to teach. Courses may be team taught.

A. Sketch a design diagram of this faculty database. It must model departments, professors and courses at the minimum. Identify one-to-many and many-to-many relationships in your design, and indicate them on your diagram. Indicate simplifying assumptions explicitly wherever you make them.

B. Build a set of CREATE TABLE statements that corresponds to the sketch from A. Run them in mySQL to make sure they actually work.

C. Populate the tables with a small amount of fabricated data, just enough to be able to test D below.

D. Come up with five SELECT queries that answer interesting questions about your data. Run them against the data from C as a correctness check. Collect these five queries, along with plain English descriptions of what they do, in a text file.

20 points.

2) A Webapp Widget

It is common, in database webapps, to provide drop-down menus of various slices of the data, since these are extremely user-friendly interface tools.

To give an example, at any travel website such as Expedia or Travelocity, you will encounter drop-down menus of airports. Imagine such a site was backed by a database with a table Airports as follows:

and so on. This corresponds closely to the following drop-down menu:
<select name=AirportID>
 <option value=3>JFK</option>
 <option value=4>LaGuardia</option>
 <option value=1>Midway</option>
 <option value=2>O'Hare</option>
which looks like this when rendered on a page:

Using packages you have already built, build a DatabaseDropdown class with the following properties:

Like the ResultTable you built in lab, the DatabaseDropdown should produce an HTML select based on real data from a table in your own database. Submit a sample test that shows that it does.

10 points.

3) Fractions

ERROR: Please note that the method over in the following interface mistakenly took a Complex in my original writeup for this problem. I have corrected it to over(Fraction that) as intended.

One more numerical class to implement: the fraction. It must implement the following methods:

public int getNum()
public int getDenom()
public Fraction negate()
public Fraction reciprocal()
public Fraction plus(Fraction that)
public Fraction minus(Fraction that)
public Fraction times(Fraction that)
public Fraction over(Fraction that) // division: "this" over "that"
public Fraction tothe(int power) // exponentiation: "this" to the "power"
public double approx() // the approximate numerical value of the fraction
public boolean equals(Object o)
public String toString()

The twist to writing a Fraction is that you will want to simplify fractions at construction time. That is, when you construct a new Fraction(12,24), the constructor should reduce the numerator and denominator to 1 and 2, respectively. Having this reduction done in the constructor will make the rest of the methods much easier in ways I hope will become clear as you work on this problem.

The way to reduce fractions is to compute the greatest common denominator of the numerator and the denominator at construction time, and then use it to divide both quantities. The greatest common denominator, or gcd, can be computed with the following recursive algorithm (see Note below):

gcd(a,b) = a, if b = 0, or
           gcd(b, a mod b) if b > 0
Note: in order to work, this algorithm assumes that a and b are both nonnegative and that a is greater than or equal to b.

Include the method

private static int gcd(int a, int b)
in your Fraction class, and build the rest of the class upon it.

10 points.

4) Extra Credit: Generic Matrices

The problem with the generic matrices as previously assigned was due to the fact that arrays (more specifically, two-dimensional arrays) were used to represent the values in an array beyond the scenes. This gave rise to some unfortunate type problems which were ultimately implementational impasses.

There are various ways to make the generic matrix work; the easiest, perhaps, is to change the internal implementation of your matrix to use Lists rather than arrays. If you change your arrays to lists, everything should work fine.

Get generic matrices up and running for extra credit. Furthermore, you may submit partially-working generic matrices for partial extra credit.

10 extra credit points.

Final Project

Due date for non-graduators: Tues, 6/6, 9 AM.
Due date for graduating seniors: Thurs, 6/1, 9 AM.

Note that your last lab period on Thursday 5/25 will be an open session for working on your final projects.

The final project will be worth 120 points altogether. You need not submit anything on paper. It will consist of a JSP webapp which includes the interface to your project, user documentation, and developer documentation (both described below). I will evaluate it according to the following elements:

Concept. Does your web application represent a strong, sensible concept?

Use. Does it work? Is it easy to use? Is it useful?

Appearance. Is your web application attractive, or at least not painful, to behold? Note that cascading style sheets are a good tool for unifying and enhancing the appearance of your application.

User Documentation. Your web application must include clear documentation for its users, on the site itself. Your user documentation should inform users of the features available in your application. Assume no expertise on your users' part. You may wish to include examples. Clear language matters; your grammar and spelling should be correct.

Developer Documentation. Your web application must include clear documentation for any developers who might either collaborate with you in developing your web application, or who might inherit the project from you at some point in the future. This documentation must appear on the site itself. Your developer documentation must include a javadoc site of any Java classes and interfaces you built for your webapp, and the CREATE TABLE statements (and, optionally, a diagram) that describe any database schema you are using. If your schema includes simplifying assumptions about the domain being modeled in your database, state them clearly here.

Four minute presentation in class, Tuesday 5/30. You will have four minutes to show off your work in the last class of the quarter. The quality of the presentation will be part of how your final project is evaluated. Your web application must be up and running and ready to be shown from my laptop, which will be hooked up to the projector. It is understood that your work will be in an unfinished state, but it should at that point be well on its way.

Creativity, panache, elan, and other intangibles. A portion of the 120 points are reserved for the intangible qualities of your project.

Homework 4.5

Send me an email with one paragraph or so about what you might like to do for your final project. I will give you feedback on your choice. Send the email no later than Tuesday (5/9) night. Whatever you choose is not binding so be fearless.


Homework 5

assigned Thurs 5/4, due in class Thurs 5/11 at 3:00

Submission instructions: please copy and paste new interfaces and classes into a single document and print it out. Use a small font and print double-sided to mimimize page length. Submit the hard copy; no electronic submission is required. You are on your honor to submit code that compiles. We reserve the right to ask for an electronic copy of your code if we decide we'd like to run it.

Note. Start thinking about this assignment well in advance of its due date, so you don't get conceptually stuck the night before.

1) HTML Forms

A few weeks ago you created a simplified Java abstraction for HTML tables. For this question, you will build a similar simplified abstraction to represent HTML forms. Specifically, you will build models of forms which consist of inputs and selects.

Please copy your html package into the current homework project, and proceed by adding to that package.

Start by defining a subinterface FormElement as follows:

public interface FormElement extends HTML {}

You will create the class Form, which must implement the interface HTML. You will also build Input and Select classes, both of which will be implementations of the interface FormElement.

There is informal information on these (and all) HTML elements at

For a more rigorous though less user-friendly treatment of HTML, have a look at
It's up to you how closely to model these form elements in your classes.

Inputs: Build representations of HTML inputs (as in <input type=submit>) where type is either text, hidden, password, reset, or submit. Two possible approaches to this modeling problem come to mind (there are surely others): make a class hierarchy in which each type of input has its own class (as in TextInput, HiddenInput, etc.) or make an enum InputType and have each Input object maintain a private InputType. Choose either one.

Selects: Build a representation of HTML selects (drop-down menus). A select is essentially a collection of HTML options, so you will correspondingly need Select and Option classes. It is not necessary to model OptGroups, though you may if you like.

Once you have all these classes up and running, you should be able to construct a Form object, call toHTML() on it, and get a nice HTML representation thereof.

10 points.

2) SQL Queries

For this question you will add to the SQL query abstraction package you will have begun to build for the last lab.

An INSERT query has the form

INSERT INTO SomeTable (a,b,c) VALUES(1,2,3);
a) Build an InsertQuery class.

SELECT queries can have ordering constraints on them, as in

SELECT firstName, lastName
FROM students
ORDER BY lastName ASC;
SELECT capital, pop
FROM States
ORDER BY pop DESC, capital ASC;
b) Enrich your SelectQuery class so that it includes ordering constraints.

An UPDATE query has the form

SET pop=0;
SET price=price+50;
c) Build an UpdateQuery class.

Note that you need not model WHERE clauses in any of your classes.

10 points.

3) [SUSPENDED: See note above] A Generic Matrix Class

Please create a package genericMatrix for this problem.

The Matrix you built for the last assignment contained numbers of type int. Let's say you needed matrices of double values instead. One way to handle the situation would be to copy and paste your int Matrix and comb through it and change a bunch of ints to doubles. But then you might need a matrix of Complex values. Later, a matrix of Longs. More copying and pasting? Let's not. There's a better way.

You could instead make your Matrix class generic, as in Matrix<T>. But there's a problem: Matrix<T> is a little too generic. We don't want our users to create Matrices of, say, Ducks or Turkeys. What we want is instead is

Matrix<T extends Num<T>>
where Num<T> is an interface for numerical objects.

Your task is this:

Having done all that, you now have a class from which you could build matrices of Integers, Doubles, Floats, BigIntegers, BigDecimals, and so on.

A few points you will need to know for this problem:

10 points.

Homework 4

assigned Tues 4/18, due in class Thurs 4/27 at 3:00

Submission: Please bring a hard copy of your matrix implementation to class on Thursday 4/27. No online submission required. Please feel free to copy and paste the code into a document (external to Eclipse) and use a small font to save pages. You need not submit any code for your JSP pages; we can look at them directly if we need to.

Check out the new jsp help section of this course website.

Please note the due date of this assignment.

1) The Matrix Has You

Build an integer matrix class as specified by the following interface:

public interface Matrix {
  public int element(int r, int c);
  public int numRows();
  public int numCols();
  public Matrix plus(Matrix that);
  public Matrix times(int scalar);
  public Matrix times(Matrix that);
  public Matrix negated();
  public Matrix minus(Matrix that);
  public Matrix transpose();
  public Matrix tothe(int power);
  public boolean isUpperTriangular();
  public boolean isLowerTriangular();
  public boolean isDiagonal();
  public String toString();
  public boolean equals(Matrix m);

16 points.

2) Simple JSP #1

Connect your quadratic equation solving classes to the web with a JSP webapp. A visitor to the site should be able to specify a quadratic equation, click a button, and view the pair of solutions to the equation.

Create this JSP webapp in a folder called

(please note the amendment) on the CS file system.

Provide a clearly marked link to this webapp from your CS102 page.

6 points.

3) Simple JSP #2

Create a color viewer webapp. Your visitor should be able to enter one number each for red, green and blue. Once they enter that information, they should be taken to a page to see a sample of that color as well as its hex code representation.

Create this JSP webapp in a folder called

(please note amendment) on the CS file system.

Provide a clearly marked link to this webapp from your CS102 page.

8 points.

Homework 3

assigned Tues 4/11; due Tuesday 4/18 at noon

Submit this assignment just as you submitted Assignment 3.

For this homework, create an Eclipse project cs102.hw3.

1) Basketball Teams

Inside your cs102.hw3 project, create a package basketball. You will populate that package with two interfaces and four classes.

A basketball player class will implement the following interface:

public interface BBP { // BBP for BasketBall Player
  public String getLastName();
  public String getFirstName();
  public Gender getGender();
  public int height();   // in inches
  public int yearsExp(); // years of experience; a rookie has 0
  public String toString();

Correspondingly, a basketball team will implement the following interface:

public interface BBT { // BBT for BasketBall Team
  public String teamName();
  public int numPlayers();
  public int numMen();
  public int numWomen();
  public boolean isCoed();     // has players of both genders
  public int totalHeight();    // in inches
  public double avgHeight();   // in inches
  public int totalYearsExp();  // years of experience
  public double avgYearsExp(); // years of experience
  public String toString();

Implement the following:

The TeamTester class should simply demonstrate the correct workings of your classes.

10 points.

2) A Model of HTML Tables

Inside your cs102.hw3 project, create a package html. Create the following interfaces and classes in that package.

For this question, we will consider a simplified model of HTML tables.

Define an enum HAlignment for horizontal alignment, whose members are LEFT, CENTER, RIGHT and JUSTIFY.

Define the interface HTML. The interface need only specify one method:

Define the interface TableCell. This interface should extend HTML and need not specify any methods at all. (Food for thought: why define an interface with no methods?)

Define the classes TH and TD. Each must implement the interface TableCell. Each must have a horizontal alignment and a String of content.

Define the class TR, for table row. A table row consists of an arbitrary number of TableCells. TR must implement the HTML interface.

Define the class Table. A table consists of an arbitrary number of TRs. Table must implement the HTML interface.

Please provide all of the following constructors:

Please provide a TableTester class as well.

10 points.

3) HTML Basketball Teams

In this last question, you will hack on the basketball package to augment it with HTML features.

Add the following method to the interface BBP:

This method should take the basic elements of information about a player and lay them out in a table row in some sensible way. You will need to import various elements of the html package into BBP.java to get this to work; Eclipse will help you do so.

Similarly, extend the BBT interface to include

This table need only consist of one row per player on the team.

You should now add a line of code or two to your TeamTester class to test the asTable() method.

4 points.

4) Quadratic Equations

In cs102.hw3, create a package quadratic. Copy your class Complex from last week into it.

Then implement a pair of classes that realize the following pair of interfaces:

public interface Quadratic {
  public double a();
  public double b();
  public double c();
  public double discriminant();   // b^2 - 4ac
  public String toString();       // a sensible String representation
  public ComplexPair solutions(); // use the quadratic formula

public interface ComplexPair {
  public Complex first();
  public Complex second();
  public String toString();

Also include a tester class.

8 points.

Homework 2

assigned Tuesday, 4/4; due Tuesday, 4/11 at noon

Submission instructions: You will submit this work in both electronic and hard copy form. The reason we ask you to submit both is that we can run the code from the electronic copy, and we can write our feedback on the hard copy.

  1. Upload the electronic copy to the chalk site by noon on Tuesday. The place to submit is under Assignments | Submit Homework 2 Here. Look for the spot that says "Attach local file"; you will be able to upload your homework there.
  2. Bring a hard copy to class Tuesday afternoon.

1) SimSomething

You're probably all familiar with simulation style amusements like "SimCity", "Roller Coaster Tycoon", "The Sims" and so on. For this exercise, assume you are an object-oriented programmer who has been charged with developing such a game.

Choose the subject of the game and a title for it. Think about the classes and objects that would manifest themselves in your game model. Then choose three classes from your imagined class hierarchy and write out "class skeletons" which will consist only of the class name and the class's private instance variables.

For example, say you decide to build the game SimChicago. The model Chicago around which this game will be based will include various elements of the real Chicago, including but not limited to skyscrapers, ballparks, and hot dog vendors. One of those three classes might be sketched as follows:

public class HotDogVendor {
  // private instance variables
  private String name;
  private int height; // in cm
  private int weight; // in pounds
  private String pitch; // the thing the vendor yells when selling hotdogs
  private int voiceVolume;
  private int numDogs;
  private boolean hasKetchup;
  private boolean hasMustard;

4 points.

2) An HTML Object

An HTML horizontal rule (<hr>) is in some sense a tangible thing, or at least a visible thing. Horizontal rules, and HTML elements in general, can be modeled well with objects.

Assume an hr can have the following attributes:

Be mindful that any of these attributes could be missing altogether.

The "noshade" attribute has no value, unlike the vast majority of HTML attributes. You include it as follows:

<hr noshade>

Define a class HR with private instance variables, a no-args constructor, a constructor with four arguments corresponding to the four attributes above, and a public method toHTML() returning a String.

The String produced by toHTML() should only include the attributes of the hr whose values are defined. In more concrete terms, the following is fine

<hr align="right">
but the following is not
<hr align="right" size= width=>
even though the latter would be handled in a reasonable way by browsers.

Define a class HRTester with a main method which demonstrates that your HR class is working.

8 points.

3) A Complex Number Object

I have prepared a helper handout on complex numbers for interested students: here it is.

A complex number is a number of the form a+bi where a and b are real numbers.

Write the class Complex. Implement the following methods:

The output types for each method have been left for you to determine. Each output type will be either double, Complex or String (no void methods).

Submit the class Complex, and a class ComplexTester whose main method tests Complex.

10 points.

Homework 1

assigned Tues 3/28/06, due Thurs 3/30/06, 3 PM

Get yourself a CS account if you don't have one already. You can do so by visiting

There might be a 24 hour lag in this step, so do it *immediately*.

Make a directory in your CS home called html. Within that directory, make another called cs102, and in that one, another called project. In each of these folders, make a file called index.html. The end result should be something like this:

 - whoeveryouare/
   - html/
     - index.html
     - cs102/
       - index.html
       - project/
         - index.html
In the foregoing diagram, everything with a slash after it is a directory (i.e., a folder).

Put a little something on each page, including the following links:

Be aware that what you put on these pages is public. Everyone in the world can see it. Don't put your email address on these pages: for those who publish their email addresses, spamming awaits.

That's all worth five points. For another point, use a cascading stylesheet somewhere.

You will not need to submit anything for this assignment, since we will be able to see your work online. Just do it Thursday by 3:00.