import java.util.Iterator; public class Haddock implements Iterable{ private String greet = "You #!@ Miserable earthworms! Numbskulls! and Carpet-sellers!"; public void printWords(){ int i = 0; final int N = greet.length(); // skip leading non letters while (i{ // Exercise 2.3 // inv: if nextWord.size() = 0, the iterator is empty // else nextWord is the head. // i is either N or the first unprocessed letter in greet // N is the length of greet. final int N; int i; String nextWord; GreetIterator(){ i=0; N = greet.length(); findNext(); } /* pre: i is first non-processed letter in greet or N post: if hasNext is true then nextWord is head. i is first non-processed letter in greet or N */ private void findNext(){ // skip non letters while( i0; } public String next(){ String ret = nextWord; findNext(); return ret; } public void remove(){ throw new UnsupportedOperationException(); } } public Iterator iterator(){ return new GreetIterator(); } public static void foo(){ Haddock captain = new Haddock(); for(String s: captain) System.out.println("Haddock says: " + s); } }