The exercise we discussed in class today:

import java.util.*; 

public class Exercise {
  public static void main(String[] args) {
    Stack<String> s = new Stack<String>();
    String sentence = "Mary had a little lamb."; 
    Scanner in = new Scanner(sentence); 
    while (in.hasNext()) {
      s.push( in.next() ); 
      System.out.println( s );  
    }
    String result = ""; 
    while (! s.empty()) {
      result += " " + s.pop();       
    }
    System.out.println( result );
  }
}

Here's how it runs for me: 

Welcome to DrJava.  Working directory is C:\Users\dgerman\Desktop
> run Exercise
[Mary]
[Mary, had]
[Mary, had, a]
[Mary, had, a, little]
[Mary, had, a, little, lamb.]
 lamb. little a had Mary


The discussion we had before that: 

import java.util.*; 
import java.io.*; 

public class Example {
  public static void main(String[] args) throws Exception {
    Scanner in = new Scanner(new File(args[0])); 
    Map<String, Integer> dictionary = new HashMap<String, Integer>();     
    while (in.hasNext()) { 
      String token = in.next();
      if (dictionary.get(token) == null) {
        dictionary.put(token, 1);  
      } else {
        dictionary.put(token, 1 + dictionary.get(token) );  
      }
      System.out.println( dictionary ); 
      ArrayList<Candidate> c = new ArrayList<Candidate>(); 
      for (String name : dictionary.keySet()) {
        c.add( new Candidate(name, dictionary.get(name)) );  
      }
      System.out.println( c ); 
      Collections.sort( c ); 
      System.out.println( c ); 
    }
  }
}

This relies on the following abstraction:

public class Candidate implements Comparable<Candidate> {
  String name; 
  int votes;
  public Candidate(String name, int votes) {
     this.name = name; 
     this.votes = votes;
  }
  public String toString() {
    return this.name + ":" + this.votes; 
  }
  public int compareTo(Candidate other) {
    // return this.votes - other.votes; 
    if (this.votes == other.votes) 
      return this.name.compareTo(other.name); 
    else 
      return other.votes - this.votes; 
  }
}

My votes.txt file looked like this: 

One One 
    Two

Three Three Three
   Two One

   Three 

I also promised a generic sort method for Monday. 

--