Friday, March 30, 2012

ArrayLists and HashSets

Next week we will be covering Chapter 12, which talks about some of the built-in collection classes in Java, such as ArrayList and HashSet and HashMap:





Wednesday, March 28, 2012

Lab 20: Stock Plot

In Java, like in most programming languages, reading data from a URL is nearly identical to reading from a file, or reading from the keyboard. Java uses the URL class for reading data from a URL, as shown in this example.

Google provides us with historical price information for all the stocks. Specifically, if you go to the url http://www.google.com/finance/historical?q=AAPL&output=csv you will get a text file, in CSV format, for the prices of AAPL (Apple Computer) stock for the last year. To get a different stock simply replace AAPL in that url with the sticker symbol for your desired stock (try GOOG, GE, INTC).

For this lab you will start with the code below:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;


public class PlotStock extends JPanel {

  /**
   * Initial Screen size.
   */
  public static final int WIDTH = 640;
  public static final int HEIGHT = 400;


  /**
   * Fetches stock data from google and prints it out to the
   * console.
   */
  private void getData(){
    try {
      //Get data on AAPL (Apple Computer) stock.
      //To get data on other sticker symbols simply replace AAPL with your
      // desired symbol, like GOOG.
      URL data = new URL("http://www.google.com/finance/historical?q=AAPL&output=csv");
      BufferedReader in = new BufferedReader(
        new InputStreamReader(data.openStream()));
      String inputLine;
      //TODO: rather than printing them out, we need to pick out the
      //  closing prices and save them for later plotting.
      while ((inputLine = in.readLine()) != null){
        System.out.println(inputLine);
      }
    }
    catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      System.out.println("Uh Oh, I cannot reach the Internet.");
    }
   }

  /**
   * This method gets called when the class first gets create and also whenever the
   * window needs to be redraw, like when the user changes its size, de-iconifies it,
   * moves it, etc.
   */
  public void paintComponent(Graphics g){
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(Color.black);
    getData();
    //Draw a line from 10,10 to the bottom right of the window.
    //TODO: draw the line graph of the closing prices instead.
    g2.drawLine(10,10, getWidth(), getHeight());
    //Notice that getWidth() and getHeight() can be used to give us
    // the width and height of the current window (which might be 
    // different from the original because the user changed it).
  }

  public static void main(String[] args) {
    String symbol = JOptionPane.showInputDialog("Enter Ticker Symbol:");
    if (symbol == null) System.exit(0); //quit if user hit Cancel
    JFrame frame = new JFrame("Window"); //frame is the window
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    PlotStock panel = new PlotStock(); //panel is the graphics area where we can draw
    frame.add(panel); //put the panel inside the window
    frame.setSize(WIDTH,HEIGHT); //set the window size to 640x400 pixels
    frame.setVisible(true); 
  }
}


When you run it you will notice that it first opens up a window asking you for a ticker symbol (try AAPL) and then prints out the prices for that stock on the console and pops up a graphic window with just a line.

For this lab you will change this program so that instead of printing out to the console it will draw a line chart of the closing prices of the given stock. Notice that the closing price is one of the columns on the give CSV file. You can ignore all the other columns. Your final plot should look something like the figure shown.

TIP: String.split(",",0) is very useful for parsing the CSV file.

Once you get it working, try re-sizing the window with your mouse: drag a corner to make the window bigger. Did your plot grow with the window? If not, that is OK, it is good enough for this lab.

However, if you want a fun little challenge (definitely doable within the lab time), try to make it so your plot stretches to fit the window. Note that you can get the current size of the window using getWidth() and getHeight(), as shown in the code. The rest is just a little bit of programming. You will need to find the max and min closing prices, and number of days of data, then scale these to fit the current window.

As always, turn it in at the dropbox.cse.sc.edu.



Monday, March 26, 2012

Lab 19: Sierpinsky Triangle

For this lab you will implement a recursive method that draws the Sierpinsky Triangle to various levels. You will start out with the following code:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * Triangle.java
 * @author Jose M Vidal 
 * Created on Mar 19, 2012
 * 
 */

public class Triangle extends JPanel {

  public void drawTriangle(Graphics2D g, int x1, int y1, int x2, int y2, int x3, int y3){
    g.drawLine(x1, y1, x2, y2);
    g.drawLine(x2, y2, x3, y3);
    g.drawLine(x3, y3, x1, y1);
  }
 
  public void paintComponent(Graphics g){
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(Color.black);
    drawTriangle(g2,1,640, 320,0, 640,640);
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame("Window"); //frame is the window
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Triangle panel = new Triangle(); //panel is the graphics area where we can draw

    frame.add(panel); //put the panel inside the window
    frame.setSize(650,680); //set the window size to 640x640 pixels
    frame.setVisible(true); 
   }
}


which simply draws a triangle and change it so that it draws the Sierpinsky triangle to any desired level.

That is, change the drawTriangle method so that it takes as argument another variable, the level. If the level is 0 it will draw the triangle exactly as it does now.

But, if the level is 1 it will instead draw the 3 triangles, as shown in the first figure. In other words, it will draw three Sierpinsky level 0 triangles: one on the bottom left, one on the top, and one on the bottom right. Note that we do not draw the upside-down triangle in the middle, that one is just a side-effect from drawing the three other triangles. Similarly, if the level is 2 we draw 3 Sierpinsky level 2 triangles: one on the bottom left, one on the top, and one on the bottom right, and so on.

The program should work for all levels but, I note that running it for levels greater than 12 will take significant amounts of time, and will not change the look of the triangle because you have already reached the limits of the resolution (640 by 640 pixels)

As always, turn this in on the dropbox.cse.sc.edu.

Oh, and, how might this be related to exponential functions as discussed in class? Vihart explains:

HW 9: Numbers

For this homework you will write a program that prints out the numbers between 1 and 1000000 in English. That is, it will print out:
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifthteen
sixteen
seventeen
eightteen
nineteen
twenty
twentyone
twentytwo
twentythree
twentyfour
twentyfive
twentysix

...and so on...

one hundred and ninetyseven
one hundred and ninetyeight
one hundred and ninetynine
two hundred
two hundred and one
two hundred and two
two hundred and three
two hundred and four
two hundred and five
two hundred and six
two hundred and seven

...and so on...

nine hundred and ninetynine thousand nine hundred and ninetyfive
nine hundred and ninetynine thousand nine hundred and ninetysix
nine hundred and ninetynine thousand nine hundred and ninetyseven
nine hundred and ninetynine thousand nine hundred and ninetyeight
nine hundred and ninetynine thousand nine hundred and ninetynine
one million

You can download all the numbers if you want to see all of them.

Note that you must use a recursive method to generate the numbers. Look carefully at the numbers and notice the pattern, for example, the English for 136 is "one", then the words "hundred and" then the English for 36.

This homework is due Monday, April 2 @noon in the dropbox.cse.sc.edu.

Thursday, March 22, 2012

Recursion

On Monday's lecture we will discuss Recursion: Chapter 11 of the textbook.



Binary Search implementation using Recursion

Serializable Interface

You can easily write any Java object to a file, as long as it implements the Serializable interface. The following video shows you how:


Wednesday, March 21, 2012

Lab 18: Pride and Prejudice

In this lab we will explore how the characters in Jane Austen's masterpiece "Pride and Prejudice" feel. For this, you first need to head on over to Project Gutenberg and download a copy of the plain text version of the book to your desktop. Then, drag it over to your eclipse project (within the project, not within the src folder).

You will now write a program that reads this file looking for the phrase "I am" and prints out each time it finds it followed by the next four words, also keeping a count of how many it has found. The output of your program will look something like:
1- I am thinking of his marrying
2- I am sure she is not
3- I am glad to find that
4- I am not acquainted with him
5- I am sick of Mr. Bingley,"
6- I am sorry to hear _that_;
7- I am ! and it is
8- I am not afraid; for though
9- I am particularly acquainted with my

...and so on...

280- I am afraid; for what becomes
281- I am not indebted for my
282- I am more likely to want
283- I am happier even than Jane;
284- I am sure Wickham would like

You will find Scanner.findWithinHorizon("I am",0) will come in handy for this.

Your program will also write to a file called "out.txt" the count of how many times it has found "I am sure", "I am afraid" and "I am not afraid". The file should have these contents:
I am sure: 36
I am afraid:15
I am not afraid:5

Monday, March 19, 2012

Lab 17: Exceptions

For this lab you will implement a Date class and a DateFormatException class. The Date class keeps the date in three private int member variables, called month, day, year. It has the following methods:
  • Date(int month, int day, int year): is the constructor
  • toString(): returns the date in a String of the form 2/2/2002
  • public static Date parseDate(String d) throws DateFormatException: tries to parse the string d into a viable date. If it succeeds then it creates a new date and returns it. If it fails then it throws the DateFormatException. d is a viable date if it is in the form "m/d/y" where m is an integer between 1 and 12, d is an integer between 1 and 31, and y is an integer.

For example, if you were to run this main:
public static void main(String[] args){
  Date d = null;
  Scanner keyboard = new Scanner(System.in);
  boolean goodDate = false;
  do {
   System.out.print("Enter a date:");
   String w = keyboard.next();
   try{
    d = Date.parseDate(w);
    goodDate = true;
   } catch (DateFormatException e){
    System.out.println("Bad user! " + w + " is not a date I understand.");
   }
  } while (! goodDate);
  System.out.println("Finally! You entered a well-formatted date: " + d);
 }

it could result in the following interaction:
Enter a date:chanchan
Bad user! chanchan is not a date I understand.
Enter a date:44/44/44
Bad user! 44/44/44 is not a date I understand.
Enter a date:1/44/2012
Bad user! 1/44/2012 is not a date I understand.
Enter a date:44/24/2012
Bad user! 44/24/2012 is not a date I understand.
Enter a date:3-3-2012
Bad user! 3-3-2012 is not a date I understand.
Enter a date:3/19/2012
Finally! You entered a well-formatted date: 3/19/2012

TIP: Checkout Integer.parseInt() and String.split(), they are your secret weapon.

HACKER FYI: parseDate is a static method that creates new instances of the class. We call methods like this factories.

Test 2 Points Distribution

Below is the points distribution for Test 2. Points are not grades. We will talk about grades in class.



Friday, March 16, 2012

HW 8: Employment Data

You are working in the University admissions office and students keep asking you about how the job market for different majors is fearing. You figure that a good place to start in answering that question is by looking at how many people currently work in each particular job in the US. You figure that someone must have already gathered that data and, after a bit of googling (or, binging) around, you come across the occupational employment statistics page from the Bureau of Labor Statistics. In that page you find a link to the raw data files.

For this homework you will only need to download the oe.occupation and oe.data.0.Current files.

First, take a look at the oe.occupation file. Each line in this file lists a different occupation by first listing the occupation code, a space, then the English description, a space, then a number (1). Your program will need to first read all these occupations codes and descriptions into an array so it can then ask the user for which occupation he wants to know the total number of people employed.

The oe.data.0.Current file contains all the data. It is a large file (266MB) and the .gov site is slow so, here is my copy. The oe.txt file describes the format of the data in this file in detail, but I will explain below what you need to do for this HW. The oe.data.0.Current file looks like
series_id year period value footnote_codes
OEUM001018000000000000001      2010 S01        61790 
OEUM001018000000000000002      2010 S01          2.2 
OEUM001018000000000000003      2010 S01        16.72 
OEUM001018000000000000004      2010 S01        34780 

The series_id (OEUM000040000000000000001) can be broken out into:
Code     Value(Example)

survey abbreviation =  OE
seasonal(code)  =  U
area_code  =  0000400
industry_code  =  000000
occupation_code  =  000000 
datatype_code  =  01

For this HW we are only interested in lines with a series_id that starts with OEUS and have a datatype_code (end with) of 01, which corresponds to "number of jobs". The occupation_code corresponds to the code from the oe.occupation file.

Your program will first read in and parse the occupations from the oe.occupation file. It will then show the user the list of all occupation codes, numbered, and ask him to pick one. It will then open up the oe.data.0.Current file and add up the values (fourth column) of all the rows that with a series_id that starts with OEUS, ends with 01, and matches the user's chosen occupation code. Finally, it will print out this number. Here is a sample run:

0 - All Occupations 
1 - Management Occupations 
2 - Chief Executives 
3 - General and Operations Managers 

....and so on.....

817 - Mine Shuttle Car Operators 
818 - Tank Car, Truck, and Ship Loaders 
819 - Material Moving Workers, All Other 

Which of the occupations above do you need data for?
Enter number:77
Working......
17750 persons work as Actuaries in the US.

Here are a few more sample outputs so you can see the sums that I got. I am omitting the list of occupations as it is always the same.
Enter number:66
Working......
3294290 persons work as Computer and Mathematical Occupations in the US.

Enter number:69
Working......
335330 persons work as Computer Programmers in the US.

Enter number:70
Working......
499880 persons work as Software Developers, Applications in the US.

Enter number:94
Working......
144870 persons work as Electrical Engineers in the US.

Enter number:101
Working......
223470 persons work as Mechanical Engineers in the US.

Enter number:119
Working......
1072400 persons work as Life, Physical, and Social Science Occupations in the US.

Enter number:146
Working......
3360 persons work as Sociologists in the US.

Enter number:1
Working......
6066780 persons work as Management Occupations in the US.

Enter number:295
Working......
7394880 persons work as Healthcare Practitioners and Technical Occupations in the US.


I note that my numbers do not exactly match theirs. For example, for "Computer Programmers" I got 335,330 but their webpage shows 333,620 (wepage with all occupations). I blame it on shoddy accounting in the Obama administration. Still, its pretty close.

TIP: You will want to create a class that holds the collection of occupations from the oe.occupation file, along with an Occupation class which holds just one occupation: its name and its code.

TIP: It takes my laptop about 15 seconds to process the whole file. That is way too long when trying to debug the program, so I added temporary code to only read in the first few thousand lines. I then get rid of that code when the program works. BTW, the file has about 5 million lines.

This homework is due in the dropbox.cse.sc.edu on Monday, March 26 @noon. When you turn it in, do not upload the text files. We already have a copy, and we don't need 120 more copies.



Reading and Writing Files

On Wednesday's lecture we will cover the reading and writing of files (Chapter 10).

Reading a CSV file


Writing to a text file


Binary files


Thursday, March 15, 2012

Test 2 and Lab Test 2

Here are the Test 2s and the answers:

  1. (25%) What does the following program print out when run?

    public class Boat extends Ship {
    
     private int seaWorthinessRating;
    
     public Boat(double maxSpeed) {
      super(maxSpeed);
      seaWorthinessRating = 33;
     }
    
     public Boat(double maxSpeed, int rating) {
      super(maxSpeed);
      seaWorthinessRating = rating;
     }
    
     public String toString(){
      return "mp=" + maxSpeed + " seaworth=" + seaWorthinessRating;
     }
    
    }
    
    public class SailBoat extends Boat {
    
      public String toString(){
        return "Sailboat";
      }
    }
    
    public class Ship {
    
     protected double maxSpeed;
    
     public Ship(double maxSpeed){
      this.maxSpeed = maxSpeed;
     }
    
     public String toString(){
      return "maxSpeed="  + maxSpeed;
     }
    
     public static void main(String[] args){
      Ship s1 = new Ship(1);
      System.out.println(s1);
      Ship s2 = new Boat(2,66);
      Ship s22 = new Boat(8);
      System.out.println(s2);
      System.out.println(s22);
      SailBoat s3 = new SailBoat(3,77);
      System.out.println(s3);
      Ship s4 = (Ship)s3;
      System.out.println(s4);
     }
    }

  2. (25%) What is wrong with the program below? Explain.
    public interface Drinkable {
     public void drink();
    
     public boolean isEmpty(){ return false;}
    }
    
    public class RedBull implements Drinkable {
    
     private int size;
    
     public RedBull(int size){
      this.size = size;
     }
    
     public void drink(){
      System.out.println("Yuuuuuckkkkk");
     }
    
     public boolean isEmpty(){
      return true;
     }
    
    }
    Answer: An interface cannot implement a method.
  3. (25%) Implement a static method which takes as an argument an array of integers a and returns a new array, lets call it r, where r[0] has the sum of a[0] + a[1], and r[1] has the sum of a[2] + a[3], and so on. You can assume that the length of a is even.
  4. Answer:
    public static int[] everyOther(int[] a){
      int[] result = new int[a.length/2];
      for (int i = 0; i < a.length; i+=2) {
       result[i/2] = a[i] + a[i+1];
      }
      return result;
     }
            
  5. (25%) Take a look at this code:
    public class Plant {
    
     private String name;
    
     public Plant(String name){
      this.name = name;
     }
    
     public String getName(){
      return name;
     }
    
     public static void main(String[] args){
      Plant[] garden = new Plant[3];
      garden[0] = new Plant("Vine");
      //Create a Rosemary plant with the name Vanity
      // it will have 1024 leaves by default
      garden[1] = new Rosemary("Vanity");
      //This one will have 2048 leaves
      garden[2] = new Rosemary("Pride", 2048);
    
      for (Plant p: garden){
       System.out.println(p.getName()); //print their names
      }
      //getRosemaries() returns the total number of rosemaries
      //  that have been created.
      System.out.println("There are " + Rosemary.getNumRosemaries()
        + " rosemary plants.");
    
      Rosemary r = new Rosemary("Loathing");
      System.out.println(r.getName());
      System.out.println("There are " + Rosemary.getNumRosemaries()
        + " rosemary plants.");
    
     }
    }
            
    Implement the missing Rosemary class so that when we run the code above it will print:
    Vine
    Rosemary:Vanity numLeaves=1024
    Rosemary:Pride numLeaves=2048
    There are 2 rosemary plants.
    Rosemary:Loathing numLeaves=1024
    There are 3 rosemary plants.

    See the comments in the code for hints on what the various
    methods and attributes Rosemary must have.

    Answer:

    public class Rosemary extends Plant {
    
     private int numLeaves;
    
     private static int numCreated = 0;
    
     public Rosemary(String name) {
      super("Rosemary:" + name );
      numLeaves = 1024;
      numCreated++;
     }
    
     public Rosemary(String name, int numLeaves) {
      super("Rosemary:" + name );
      this.numLeaves= numLeaves;
      numCreated++;
     }
    
     public String getName(){
      return super.getName() + " numLeaves=" + numLeaves;
     }
    
     public static int getNumRosemaries(){
      return numCreated;
     }
    
    
    }
and the other one
  1. (25%) What does the following program print out when run?

    public class Boot extends Shoe {
    
     protected int height;
    
     public Boot(int height){
      super(9);
      this.height = height;
     }
    
     public Boot(int height, int size){
      super(size);
      this.height = height;
     }
    }
    
    public class Ugg extends Boot {
    
     public Ugg(int height, int size) {
      super(height,size);
      height--;
     }
    
     public String toString(){
      return "Ugg size=" + super.toString() + " height=" + height;
     }
    }
    public class Shoe {
    
     private int size;
    
     public Shoe(){
      size = 7;
     }
    
     public Shoe(int size) {
      this.size = size;
     }
    
     public String toString() {
      return "Shoe [size=" + size + "]";
     }
    
     public static void main(String[] args) {
      Shoe s1 = new Shoe();
      System.out.println(s1);
      Boot s3 = new Ugg(7,9);
      System.out.println(s3);
      Boot s4 = new Boot(5,15);
      System.out.println(s4);
      Ugg s5 = new Ugg(9,16);
      System.out.println(s5);
      Boot s6 = (Boot)s5;
      System.out.println(s6);
     }
    }

  2. (25%) What is wrong with the program below? Explain.
    public interface Playable{
    
     public void play() {
      super();
     };
    
     public int timeLeft();
    }
    
    public class Media {
    
     protected String title;
    
     public Media(String title){
      this.title = title;
     }
    }
    
    public class Song extends Media implements Playable{
    
     protected int runningTime;
    
     public Song(String name, int runningTime){
      super(name);
      this.runningTime = runningTime;
     }
    
     public void play(){
      System.out.println("Playing....");
     }
    
     public int timeLeft(){
      return runningTime - 10;
     }
    }
            
    Answer: An interface cannot implement a method.

  3. (25%) Implement a static method which takes as an argument an array of integers a and returns a new array, lets call it r, where r[0] contains the sum of a[0] and a[last index in a], r[1] contains the sum of a[1] and a[last index in a minus 1], and so on. You can assume that the length of a is even.

    Answer:

    public static int[] fold(int[] a){
      int[] result = new int[a.length/2];
      for (int i = 0; i < a.length / 2; i++) {
       result[i] = a[i] + a[a.length - 1 - i];
      }
      return result;
     }
                                        
  4. (25%) Take a look at this code:
    public interface LeafEater {
              public void eatLeaf();
    }
    
    public class Mammal {
    
     protected int numToes;
    
     protected static int count = 0;
    
     public Mammal(){
      numToes = 5;
      count++;
     }
    
     public String toString(){
      return "Mammal with " + numToes + " toes.";
     }
    
     public static void main(String[] args) {
      Mammal[] animals = new Mammal[4];
      animals[0] = new Mammal();
    
      //Creates a giraffe with 8 toes and height of 10.0 feet.
      animals[1] = new Giraffe();
    
      //Creates a giraffe with 5 toes and height of 14.6 feet.
      animals[2] = new Giraffe(14.6);
    
      //Creates a giraffe with 8 toes and height of 10.0 feet.
      animals[3] = new Giraffe();
      for (Mammal m : animals){
       System.out.println(m);
      }
    
      //getCount() returns the number of Mammals that have been created.
      System.out.println("There are " + Giraffe.getCount() + " mammals");
     }
    }

    Implement the missing Giraffe class so that when we run the code above it will print:
    Mammal with 5 toes.
    Mammal with 8 toes.-- Giraffe: 10.0 feet.
    Mammal with 5 toes.-- Giraffe: 14.6 feet.
    Mammal with 8 toes.-- Giraffe: 10.0 feet.
    There are 4 mammals
    See the comments in the code for hints on what the various methods and attributes Giraffe must have.

    Answer:

    public class Giraffe extends Mammal implements LeafEater{
    
     private double height;
    
     public Giraffe(){
      super();
      height = 10;
      numToes = 8;
     }
    
     public Giraffe(double height){
      super();
      this.height = height;
     }
    
     public String toString(){
      return super.toString() + "-- Giraffe: " + height + " feet.";
     }
    
     public static int getCount(){
      return count;
     }
    
     public void eatLeaf() {
      System.out.println("Yummm, leaves are good.");
    
     }
    
    }            
And, here is my solution to the Lab Tests.

Wednesday, March 14, 2012

Exceptions

On Monday's lecture we will discuss Exceptions, which is Chapter 9 of the textbook. Here are a couple of videos on the topic.

Exceptions



Creating your Own Exceptions


Monday, March 12, 2012

The Computer Revolution


The computer revolution is about amplifying the abilities of the human mind. Modern civilization runs on software, but computers are still just machines that need to be told what to do and precisely how to do it, by humans (like you).


Camelot Homework Solution

Here is my solution to HW 7: Camelot.

Lab 16: Iterator

For this lab you will implement a WordList which is an infinitely expanding container of Strings. The WordList class will keep an array of Strings which starts at a size of 2 (the first array created is of size 2) but then doubles in size whenever the user of the class tries to add an element which would not fit in the current wordlist. For example, the first time it doubles will be when trying to add the third word, then on the fifth, then on the ninth, and so on.

Specifically, WordList will implement the following methods:
  • add(String w): adds the string w to the word list, and expands the size of the underlying array if needed, by doubling its size. It returns the WordList.
  • size(): returns the number of words in the WordList
  • length(): returns the length of the array
  • toString(): all the words, separated by spaces.

Furthermore, the WordList implements the following interface:
public interface Iterator {

 /**
  * Resets the iterator to point to the first word.
  */
 public void resetIterator();
 
 /**
  * Returns the next word. If we are beyond the end then return null.
  * Also moves the iterator to the next word.
  * @return the next word or null.
  */
 public String getNext();
 

 /**
  * @return true if there are still words to iterate over. 
  *   false if we have reached the end
  */
 public boolean hasNext();
}


For example, the following code:
public static void main(String[] args) {
  //Test adding words
  WordList l = new WordList();
  System.out.println("There are " + l.size() + " words.");
  System.out.println("The words array is of length " + l.length() + ".");
  l.add("We").add("are").add("the").add("priests").add("of");
  l.add("The").add("Temples").add("of").add("Syrinx");
  System.out.println(l);
  System.out.println("There are " + l.size() + " words.");
  System.out.println("The words array is of length " + l.length() + ".");
  l.add("Our").add("great").add("computers").add("fill").add("the").add("hallowed").add("halls");
  System.out.println(l);
  System.out.println("There are " + l.size() + " words.");
  System.out.println("The words array is of length " + l.length() + ".");
  //Test REALLY big word lists
  for (int i = 0; i < 10000000; i++) {
   l.add("Rush");  
  }
  System.out.println("There are " + l.size() + " words.");
  System.out.println("The words array is of length " + l.length() + ".");
  
  //Test the iterator
  System.out.println("--Testing the iterator");
  l = new WordList();
  l.add("We").add("have").add("assumed").add("control");
  l.add("There").add("is").add("trouble").add("with").add("the").add("trees");
  l.resetIterator();
  while (l.hasNext()){
   String w = l.getNext();
   System.out.println(w);
  }
 }
prints out
There are 0 words.
The words array is of length 2.
We are the priests of The Temples of Syrinx 
There are 9 words.
The words array is of length 16.
We are the priests of The Temples of Syrinx Our great computers fill the hallowed halls 
There are 16 words.
The words array is of length 16.
There are 10000016 words.
The words array is of length 16777216.
--Testing the iterator
We
have
assumed
control
There
is
trouble
with
the
trees

Friday, March 9, 2012

Lab Solutions

My solutions for the last two labs:
In case you haven't noticed, on the right menu bar under "Labels" you can click on the solution label to see all the solutions, and only the solution, posts.

Sunday, March 4, 2012

Dinosaurs Programming


Actually, the biggest problem T-Rex has is that his tiny arms make it really hard for him to type.