When a method throws an exception, Java requires that it be caught. Some exceptions require action on the programmer’s part and others simply need to be reported to the user. The Java class that we will develop in this article is concerned with the latter type of exception. Instead of rewriting code every time you need to catch an exception, you can create a class to do most of the work for you.
This time, before starting out, we pulled over to the side of the road, got out the Java API and checked StringTokenizer for directions.
The first thing to notice is the StringTokenizer constructor that we chose to use (line 105).; it takes three arguments, the String to be tokenized, the character to use as a delimiter and finally a boolean that determines whether or not to return the delimiter as a token. This is ideal because we are not discarding the spaces between words.
The “hasMoreTokens” method is used to control our “while” loop (line 109). Inside the loop we simply reconstruct our string including spaces and add a newline when it exceeds the recommended length.
What could be simpler? Using one more line than the “quickAndDirty” method we have created more functional code without sacrificing clarity.
Larger Issues
At this point it is fairly obvious what the final form of our code should be. Drop the first two methods of parsing text, make a slight change to the “doDialogue” method and call only one method and finally, remove “main”. However, there is a larger lesson to be learned here.
Java is an object-oriented language with a large API. This means that much of the work you need to do may already have been done. Look around and take advantage of existing classes. In this case we found a class ideally suited to our needs –- StringTokenizer –- that performed the job in many fewer lines and made for more intelligible code. Programming with a high level language such as Java is more than just formulating your algorithm and implementing it. While nobody can know all of the classes available and all of their methods, a general knowledge of the language’s capability can be enormously helpful and a real timesaver. Do this and you won’t re-invent classes that already exist.
While you can create functional code without asking for directions, don’t. Roll down the window and ask ‘cause you’ll get there faster and more easily.