// CountWords.java // Counts the number of words in the TextField myTF // Uses loops, Java 1.0 action() method, and BorderLayout import java.awt.*; import java.applet.*; public class CountWords extends Applet { TextField myTF = new TextField(); Label wordCount = new Label("Type a sentence and press ENTER"); public void init() { setLayout(new BorderLayout()); add("North", wordCount); add("South", myTF); } public boolean action(Event e, Object o) { wordCount.setText("Words = " + countWords()); return true; } public int countWords() { int numWords = 0; boolean inAWord = false; String sentence = myTF.getText(); for (int i = 0; i < sentence.length(); i++) { char ch = sentence.charAt(i); if (ch == ' ') // It is a space { if (inAWord) // Leaving word; reset { inAWord = false; } else { // Another space; do nothing } } else // Not a space { if (inAWord) { // Do nothing; already counted word } else // Starting new word; count it { numWords++; inAWord = true; } } } return numWords; } }