Home Java Java-tips Examples-introductory Dialog Programming: Count Words - Dialog

Ask Questions?

View Latest Questions

Advertisement


 
 

Programming: Count Words - Dialog
Posted on: July 26, 2006 at 12:00 AM
Write a program which counts the number of words in text the user enters.

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 "-".

InputCount
Hello1
Hello world.2
Hello world.2
Easy as 1233
Don't worry - Be happy.5
error-prone1

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"?
Advertisement


DMCA.com