Java Notes
Programming: Count Words - Dialog
Description
Write a program which counts the number of words in text the user enters. Assume that a word is any characters separated by blanks. This isn't a very good definition, but we'll use it for this program.
Don't be fooled by multiple blanks. "test this" is two words, and so is "test this". Only count blanks if the last character you saw was not a blank, or you were at the beginning.
Examples
Because of our definition of "word" is any characters separated from others by a blank, "123" is a word, as well as "-".
Input | Count |
---|---|
Hello | 1 |
Hello world. | 2 |
Hello world. | 2 |
Easy as 123 | 3 |
Don't worry - Be happy. | 5 |
error-prone | 1 |
Hints
Trim. First you should use trim()
to get rid
of blanks on the beginning and end.
Loop. Loop across the string one position at a time.
Extra credit possiblities
- Handle the case of zero length input.
- After displaying an answer, go back to ask for another line.
- Only count "words" that contain alphabetic characters (test with
Character.isLetter()
). - If you're only allowing alphabetics, try handling contractions, like "don't"?