This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Search count in String Input Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Search count in String Input" Watch "Search count in String Input" New topic
Author

Search count in String Input

Eshwar Prasad
Ranch Hand

Joined: Mar 21, 2008
Posts: 202

I have a input in program as string "I am in america. am in". Here we notice that "am" and "in" words appears twice. So I want my output as below

I--1
am--2
in--2
america--1

So i tried below code..Here my first system.out.println just prints matched words like "am" and "in" not others. Please let me know where am i going wrong.

>
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11153
    
  16

look at where your System.out.println statement is. it's inside the block where you check to see if two strings are equal. since no string ever matches 'america', you will never print anything out for the 'america' string.

for fun, try changing your input string to "I am in america. am in am".

you'll get even stranger results....

you don't want to print out the count as soon as you find a match, since you might find more than one match (as the above suggested string illustrates).

You need to keep a counter for each word you find. Personally, i'd suggest using a map with the word as the key, and an int counter as the value.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Search count in String Input
 
Similar Threads
Performance!!
OutPut of abstract class constructor calling method
Performance!!
Displaying dice combinations
help with curly braces!!