package dk.itu.oop.lecture5; public class WordExtractor implements OOPIterator { private OOPIterator in; private String word; /* word is either null, indicating iterator is empty, or word is head. * in is positionen at the beginning of the next word to become head. */ public WordExtractor(OOPIterator in){ this.in = in; extractWord(); } /* pre: none * post: inv. */ private void extractWord(){ if (!in.hasNext() ){ word = null; return; } StringBuffer b = new StringBuffer(); char c = ( (Character)in.next() ).charValue(); while ( in.hasNext() && c != '.' ){ b.append( c ); c = ( (Character)in.next() ).charValue(); } word = b.toString(); } public boolean hasNext(){ return word != null; } public Object peek(){ return word; } public Object next(){ Object o = peek(); extractWord(); return o; } public OOPIterator cloneMe(){ try{ WordExtractor clone = (WordExtractor)super.clone(); clone.in = in.cloneMe(); return clone; }catch(CloneNotSupportedException e){ return null; } } public static void main(String[] args){ String haddock = "You #!@ Miserable earthworms! Numbskulls! and Carpet-sellers"; OOPIterator itr = new WordExtractor( new CompactNonLetters( new CharacterIterator( haddock ) ) ); while (itr.hasNext()) System.out.println( itr.next() ); } }