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

Ask Questions?

View Latest Questions


 
 

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 exactly blank. This isn't a very good definition, but we'll use it for this program.

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
Easy as 1233
Don't worry - Be happy.5
error-prone1

Hints

Blank counter. The number of words it the number of blanks+1. Declare an int variable to count the number of blanks, initializing to zero at the beginning, incrementing it by 1 for every blank in the input string, and displaying it (plus 1) at the end.

Looking at every character in a string. You will have to have a loop so you can look at each character in the input string to see if it's a blank. This kind of loop needs a index into the string that starts at zero and is incremented each time thru the loop, stopping when it exceeds the last character index in the input string.

Here is a rough draft in pseudocode. Of course you have put this in a class, declare the main(...), declare the variables, etc, but this should give a general idea of how to go about it.

   1. Read a string from the user.
   2. Initialize the blank counter to zero.
   
   3. Set the string position variable to zero (ie, to point to first character).
   4. Loop while the position is less than the last position in the string.
        5. If the character at that position is a blank
            6. Increment the blank counter.
        7. Increment the position counter.
        
   8. After the loop end, display the number of blanks+1.

Use iterative programming to make it easier

Start with the minimum program, one that has a main program that does nothing. Compile and test it. Add a minor feature, eg, read a string. Compile and test it. Add another, etc.

Related Tags for Programming: Count Words - Dialog:
cstringooptexttimeinputiocountvariableuserwordloopchardisplaydefinitionnumbersumintriathisoodwritetaroocharactercharacterspingstartiftexforindexcteprogramtostopiniramblankeachincrementastcounterlantopwordsexteilitlastzerocanliinitputsplvaruseimartceenterinasstamntplaypartrseparatecaispcldeclareemendpimehrintoproppratectlxawhenwhichssuspsoeedisplayingginstaratanypinplayingrackincishaimellncrplusgoeaandartsaractbeginningstrrdsrtrtsxtxactvazs+ss+sriringrdthavbeginstabablhatdispeclfininitializinginitialisplayingplprppindonogronp