import java.util.*;
import java.io.*;
/**
* WordScanner
*
* Provides a String iterator that wraps a Reader. Objects of this class
* scan through the input, returning the sequence of legal words.
*
* A word is a string of letters (upper and lower case A-Z) that does not
* include any whitespace, numbers or punctuation characters.
*
* The scanner returns the words in the order found, skipping any
* punctuation, numbers or whitespace.
*
*
*/
public class WordScanner implements Iterator {
private Reader r;
private int c;
// Invariant:
// c is -1 for EOF, otherwise initial letter
// starting the next word (stored as int).
public WordScanner (Reader initR) throws IOException {
r = initR; //new FileReader(filename);
skipNonLetters();
}
// scans the file to make c equal to the next letter character in
// the file. If there are none left, c is -1.
private void skipNonLetters() throws IOException {
c = r.read();
while (!Character.isLetter(c)) {
if (c == -1) {
return;
}
c = r.read();
}
}
/**
* Returns true if there is a word available.
*/
public boolean hasNext() {
return (c != -1);
}
/**
* Returns the next word available from the Reader and then skips
* all non-letter characters.
*
* Throws "NoSuchElementException" if there is not another character
*
* @see java.util.Iterator#next()
*/
public String next() {
// c is a letter
try {
String s = "";
while (Character.isLetter(c)) {
s = s + (char)c;
c = r.read();
}
skipNonLetters();
return s;
} catch (IOException e) {
throw new NoSuchElementException();
}
}
/**
* Unsupported by this iterator.
*/
public void remove() {
throw new UnsupportedOperationException ();
}
}