Next: None. Up: More about loops. Previous: On the usefulness thereof.


Exercise

(This has nothing to do with anything of the above.)

Consider the following Tokenizer class to help with finding a sequence of words within a string. (You'll need to copy and paste this into BlueJ.)

public class Tokenizer {
    private String remaining; // words yet to be returned

    // (Constructor method) Constructs a Tokenizer for extracting
    // a sequence of words from !sentence!.
    public Tokenizer(String sentence) {
        remaining = sentence;
    }

    // Returns the next word found in the sentence.
    public String nextToken() {
        int space = remaining.indexOf(" ");
        if(space < 0) {
            // no more spaces are in the string; this is the last word
            String ret = remaining;
            remaining = "";
            return ret;
        } else {
            // take the first word off the string and return it
            String ret = remaining.substring(0, space);
            remaining = remaining.substring(space + 1);
            return ret;
        }
    }

    // Returns true if there are any more words remaining in the
    // sequence yet to be returned.
    public boolean hasMoreTokens() {
        return !remaining.equals("");
    }
}

Using this Tokenizer class, write a new class FindBWords containing a run() class method, which reads a line from the user and prints the words within it that begin with a capital B.

Beware the Jubjub Bird and shun the frumious Bandersnatch.
Beware
Bird
Bandersnatch
END OF WORDS


Next: None. Up: More about loops. Previous: Exercise.